问题
Vue 在向后端发送请求时会产生跨域问题而请求失败
解决办法
可以通过配置 vue.config.js
来解决。
在 vue.config.js
中,在 module.exports
中添加 devServer
字段值如下:
devServer: {
proxy: {
// detail: https://cli.vuejs.org/config/#devserver-proxy
'/api': {
target: `http://127.0.0.1:8085/api`,
changeOrigin: true,
pathRewrite: {
'^/api' : ''
}
}
}
}
假设 Vue 启动在 localhost:8080
,后端服务器启动在 localhost:8085
:
该设置会将原本发向 /api/login
的请求更换为 http://127.0.0.1:8085/api/login
得到相应数据,而浏览器则显示发向localhost:8080/api/login
,从而解决浏览器的跨域问题。
这样的话,在前端代码中需要发送请求的时候只需要发送 /api/...
即可,比如
axios.get('/api/login')
.then(function (response) {
console.log(response);
})