部署后,不管页面空白还是报错,实际上都是资源引用的路径不对造成的,根据路径来实际解决就可以了
history模式:
vue中使用history模式加上NGINX的使用会导致路径冲突,解决如下:
server {listen 8025;server_name localhost; # 或者您的实际域名/IP 地址location / {root D:\hwj\xuexi\code\my-project\dist; index index.html;try_files $uri $uri/ /index.html; # 解决 Vue 路由刷新 404 问题}}
vue.config.js (关键:publicPath: '/', //设置为绝对路径)
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave:false,configureWebpack: { devtool: 'source-map'},publicPath: '/', //设置为绝对路径
})
public目录下的index.html (关键点:<%= BASE_URL %>)
<!DOCTYPE html>
<html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1.0"><link rel="icon" href="<%= BASE_URL %>favicon.ico"><title><%= htmlWebpackPlugin.options.title %></title><link rel="stylesheet" href="<%= BASE_URL %>layui-v2.9.20\layui\css\layui.css"><script src="<%= BASE_URL %>layui-v2.9.20\layui\layui.js"></script><script src="<%= BASE_URL %>jquery-3.6.0.min.js"></script></head><body><noscript><strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><!-- built files will be auto injected --></body>
</html>
hash模式:
hash模式就没那么多事了,就是路径有点不好看
NGINX中配置如下:(好处:在同一个域名下的80端口,我可以配置test请求是访问前端,detail请求就是访问后端。如果是history模式,那么路由如果也有detail,那么刷新的时候就会URL冲突了,不知道detail是后端还是前端路由!)
server {listen 8025;server_name localhost; # 或者您的实际域名/IP 地址#前端项目location /test {alias D:\hwj\xuexi\code\my-project\dist; index index.html;try_files $uri $uri/ /test/index.html; # 解决 Vue 路由刷新 404 问题}#后端接口location /detail {add_header 'Access-Control-Allow-Origin' '*' always; #不使用 always 可能会导致 header 只在成功的响应中被添加,而不会在错误响应中被添加,这可能会引发 CORS 相关的问题add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';add_header 'Access-Control-Allow-Headers' '*';add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';if ($request_method = 'OPTIONS') {return 204;}proxy_pass http://192.168.1.99:8093/terminal;proxy_set_header Origin $http_origin;proxy_set_header Access-Control-Request-Headers $http_access_control_request_headers;proxy_set_header Access-Control-Request-Method $http_access_control_request_method;}}
vue.config.js中也要改动下
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave:false,configureWebpack: { devtool: 'source-map'},publicPath: '/test', //设置为绝对路径
})