vue创建页面时,假如设置的端口是8080,而后台端口是4000,当用axios进行数据交互时就会出现跨域问题。解决的办法很简单:
- 与package.json文件同级的目录下新建一个文件vue.config.js
在vue.config.js中进行如下配置
module.exports = {
devServer: {
proxy: {
'/api': {
//后端请求的地址
target: 'http://localhost:4000',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
}
}
}
前端发送请求http://localhost:8080/api/login?实际上请求的是http://localhost:4000/ api/login?,相当于骗了浏览器,这里注意**“/api”一定不能漏掉**,具体axios写法如下:
import axios from 'axios'
export function getArticleById(id) {
return axios.get(
//请求的地址,实际是'http://localhost:4000' +`/article/${id}`
`/article/${id}`
).then(res => {
console.log(res)
}).catch(function (error) {
console.log("访问错误")
console.log(error);
});
}
亲测有效,可以完美解决跨域问题