视频教程:前端项目部署
1、本地的服务器部署(node环境)
service.js
const express = require('express')
const app = express()
const history = require('connect-history-api-fallback')
const { createProxyMiddleware } = require('http-proxy-middleware')// 中间件设置静态资源目录
app.use(history())// 解决刷新404的问题:方法二 - 设置中间件
app.use(express.static(__dirname + '/public'))// 解决刷新404的问题:方法一 - 使用统配
// app.get('*', (req, res) => {
// res.sendFile(__dirname + '/public/index.html')
// })// 解决前端部署以后,ajax 发送不成功的问题
/*** 关于 ajax 发送失败原因:* vue项目中,vue.config.js 或者 vite.config.js 配置了代理,这个代理在开发环境中可以用,是由脚手架提供的,* 但是打包完了以后,打包出来的是 html、css、js 纯文件,没有脚手架了,也就没有代理服务器对接口进行转发了,* 那 ajax 访问的地址也就是错误的*/
app.use('/dev',createProxyMiddleware({target: 'http://sph-api.atguigu.cn',changeOrigin: true,pathRewrite: { '^/dev' : '' }})
)app.listen(3000, () => {console.log('服务启动成功。。。')
})
将打包出来的文件放到 node 环境下,指定的静态资源目录下,访问的时候,出现两个问题:
1、页面刷新 404
解决办法:
1)配置 vue 路由模式,将 history 模式改为 hash 模式,但是这种模式,地址栏比较丑,一般网站不会使用这种模式
2)node 环境修改,使用
app.get('*', (req, res) => {res.sendFile(__dirname + '/public/index.html')})
3)node 环境修改 - 使用 connect-history-api-fallback
中间件
const history = require('connect-history-api-fallback')
app.use(history())
2、ajax 请求失效了
出现这种情况的原因是:开发环境中,由脚手架提供了代理服务器,由代理服务器将接口进行转发。
而在生产环境中,使用的是打包出来的 html、css、js 这种纯文件,没有脚手架了,也就没有代理服务器对接口进行转发了,所以 ajax 访问的地址是错误的了。
vite.config.js
server: {proxy: {[env.VITE_APP_BASE_API]: {// 获取数据的服务器地址target: env.VITE_SERVE,// 是否允许跨域changeOrigin: true,// 路径重写rewrite: (path) => path.replace(/^\/api/, '')},}},
解决办法:
1)使用 http-proxy-middleware
中间件
service.js
const { createProxyMiddleware } = require('http-proxy-middleware')
app.use('/dev',createProxyMiddleware({target: 'http://sph-api.atguigu.cn',changeOrigin: true,pathRewrite: { '^/dev' : '' }})
)
如何解决?
2、nginx 服务器部署
- 将打包出来的文件,放到对应的目录
- 修改 nginx.config 文件
nginx.config
...
location / {root D:\dist # root 指向打包的文件所在的目录index index.html index.htm # 默认访问的文件try_files $uri/ $url/ /index.html; # 解决刷新 404(没有办法匹配资源时,匹配 index.html)
}location /dev/ {# 设置代理目标proxy_pass http://sph-api.atguigu.cn/; # 解决 ajax 地址错误的问题
}