- 这个问题出现在部署前后端分离项目时,前端访问后端接口出现的错误(Vue+SpringBoot)
- 找了很多出现同样问题的博客得到三种解决方法
1.修改前端Vue项目路由文件中mode属性值修改为hash(原本为history)
- 文件路径为src/router/index.js
-
const router=new Router({ mode: 'hash', //把history修改为hash base: process.env.BASE_URL, routes })
2.在vue.config.js文件中加上 (publicPath:'/',)
// 跨域配置 module.exports = { publicPath:'/', 这里加上这个 devServer: { //记住,别写错了devServer//设置本地默认端口 选填 port: 80, proxy: { //设置代理,必须填 '/api': { //设置拦截器 拦截器格式 斜杠+拦截器名字,名字可以自己定 target: 'http://自己服务器的ip地址:8080', //代理的目标地址 changeOrigin: true, //是否设置同源,输入是的 pathRewrite: { //路径重写 '^/api': ' ' //选择忽略拦截器里面的内容 } } }
3.修改Nginx里的配置文件nginx.conf
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html last; index index.html index.htm; } #如果你前项目中加了代理,那么就得加上这个 location ^~ /api/ { #注意这里得写对 proxy_pass http://自己服务器的地址:8080/; #后端服务的地址和端口号 } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
我的问题:我一开始 写的是 这种,发现没,少了个'/',然后这个符号是我噩梦的开始,搞了好几天才发现到
location ^~ /api { proxy_pass http://自己服务器的地址:8080/; #后端服务的地址和端口号 }
//vue.config.js module.exports = { publicPath:'/', devServer: { port: 80, proxy: { '/api': { // target: 'http://服务器地址:8080', //代理的目标地址 localhost changeOrigin: true, //是否设置同源,输入是的 pathRewrite: { //路径重写 '^/api': ' ' //选择忽略拦截器里面的内容 (这里得主要下有的是 '^/api': '/' ) } } }
//utils/request.js const service = axios.create({ timeout: 5000, baseURL: '/api', //这里也得注意,看看有没有写成'/api/' withCredentials: true });
总结:1,2种都试了没效果,第三种有效果,注意路径和匹配规则得写对,希望对你有帮助
We‘re sorry but XXX doesn‘t work properly without JavaScript enabled.
最新推荐文章于 2024-05-16 16:55:24 发布