前端项目部署
1. 本地服务器部署
1.1 npm run build
使用该指令打包得到dist文件夹
1.2 创建服务
1.3 配置package.json
//注意这里-g,不然可能无法运行nodemon脚本
//nodemon: 启动服务的
npm install -g nodemon
//
npm install express
//引入express
const express = require('express')
//配置端口号
const PORT = 8088
//创建app服务实例
const app = express()
//配置静态资源
app.use(express.static(__dirname + '/public'))
//绑定端口监听
app.listen(PORT, () => {
console.log(`启动成功,http://localhost:${PORT}`)
})
输入命令
nodemon server.js
本地部署完成
1.4 刷新页面404问题
- 更改路由模式
-
无法匹配后端路由时,返回index.html
app.get('*', (req, res) => { res.sendFile(__dirname + '/public/index.html') }) -
使用中间件connect-history-api-fallback(推荐)
//安装 npm i connect-history-api-fallback //引入 const history = require('connect-history-api-fallback') //使用 app.use(history()) //配置 app.use(history({ rewrites:[ //配置对象控制跳转 // {from: /^\/login.$/, to: (context) => context.parsedUrl.path} ] }))
1.5 ajax请求失效
因为打包完之后不包含代理服务器
//处理请求
npm i http-proxy-middleware
//配置代理,转发请求
app.use(
'/dev',
createProxy({
target: 'http://sph-h5-api.atguigu.cn',
changeOrigin: true,
pathRewrite: {'^/dev' : ''}
})
)
2. nginx服务器配置
1.1 安装nginx
1.2 配置nginx.conf
//要运行的端口
listen:
//在location中配置要读取的文件
location / {
//dist文件所在位置
root C:\Users\xuxue\Desktop\前端项目\noCodePlatform\dist;
index index.html index.htm;
}
注: win11可能c盘会有权限,此时可以将dist的内容复制到nginx的html文件夹
1.3 解决404问题
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;#404问题
}
//使用try_files, 若找不到uri对应的文件则返回index.html
1.4 转发请求
location /dev/ {
#访问dev的东西时,转发
proxy_pass http://sph-h5-api.atguigu.cn/;
}
注: 此时/dev 后有 / , .cn后有 / 此时拼接完的url中不包含dev
3. 云服务器部署
与nginx类似,需要xshell与xftp控制服务器以及上传资源
实际上就是在服务器上跑nginx