vue3 跨域

前后端分离开发时,不得不面对跨域问题。对于跨域,可以用两种办法进行处理。
1.安装nginx,将后端和前端都代理带nginx上。
2.在vue-cli中配置proxy,将api请求代理到API服务器上。设置devServer.proxy

    devServer: {
        open: true, //是否自动弹出浏览器页面
        host: "localhost", 
        port: '8081',
        https: false,
        hotOnly: false, 
        proxy: {
            '/api': {
                target: 'http://localhost:5000', //API服务器的地址
                ws: true,  //代理websockets
                changeOrigin: true, // 虚拟的站点需要更管origin
                pathRewrite: {   //重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
                    '^/api': ''
                }
            }
        },
    }

所以若是后端的API为'/aaa/ccc',我们需要在发请求时将路径设置为'/api/aaa/ccc',这样我们的请求才会被proxy代理到。


vite跨越

//vite.config.js
server: {
port: '3000',
open: false, //自动打开
base: "./ ", //生产环境路径
proxy: { // 本地开发环境通过代理实现跨域,生产环境使用 nginx 转发
// 正则表达式写法
'^/api': {
target: 'http://xxx.xxx.xxx.xxx:9999', // 后端服务实际地址
changeOrigin: true, //开启代理
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},


nginx跨越处理

location @router{   #重点:这里用来进行重写操作, 对应上面的@router
rewrite ^.*$ /index.html last;
}
location ~ /api/ { #重点: api转发,转发到你的api发布地址
rewrite /api/(.*)$ /$1 break;
proxy_pass http://xxx.xxx.xxx.xxx:8888;
}


链接: https://www.fly63.com/course/30_1429