Vue中使用proxy配置代理解决跨域问题
1、需求说明
在前后端分离开发中,前端发送ajax请求因为受到了浏览器同源策略的限制,会出现跨域的问题,在Vue项目中使用代理请求解决跨域问题。
如果使用vue/cli 4.x以上版本创建的Vue项目,在项目的根目录中创建 vue.config.js 配置文件。
2、代码实现
在Vue项目根目录创建 vue.config.js 配置文件,配置代码如下:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', //服务端地址
ws: true,
changeOrigin: true, // 允许跨域
pathRewrite: {
'^/api': '' // 标识替换,使用 '/api' 代替真实的接口地址
}
}
}
}
}
使用axios请求代码:
// 使用 '/api' 代替真实接口地址
// 真实地址为 http://localhost:3000/users/find
this.$axios.get('/api/users/find').then(res=>{
console.log(res)
})
代理配置的官方API地址:https://cli.vuejs.org/zh/config/#devserver-proxy
转载至:https://blog.csdn.net/p445098355/article/details/115973713?spm=1001.2014.3001.5501