前端Vue项目处理跨域请求问题解决方案(后端未加cors),前端调后端
vue.config.js中加,自己修改后端服务服务器地址和端口号
module.exports = {devServer: {port: 80,https: false,open: true,proxy: {"/test": { // 代理标识(匹配以 /test 开头的请求)target: "http://xxx", // 目标服务器地址changeOrigin: true, // 允许跨域pathRewrite: {"^/test": "" // 去掉请求路径中的 /test 前缀}}},disableHostCheck: true}
}
api文件夹下的index.js或你命名的api.js文件修改你请求的接口地址为,xxx是域名端口后的后台接口地址:
export function get_data(data) {return request({url: `/test/xxx`, //xxx是域名端口后的后台接口地址method: "get",params: data, // 保留参数传递timeout: 50000,});
}
但以上仅限于在开发环境中解决跨域和同源策略阻挡问题,前端项目打包部署nginx时,还需要在nginx的conf文件中配置反向代理,把所有原本直接请求 http://xxx.com
你自己后端服务器服务的代码,改为通过代理路径 /api
发起请求,从而绕过浏览器的同源策略阻挡
要在前端部署的nginx的conf的配置文件中加上反向代理地址
location /test {proxy_pass http://xxx;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;
}