Vue跨域访问后端API问题(code-200,但无返回内容)
2023-03-11 本文已影响0人
jnxc1888
之前的代码,是在这里加的
![](https://img.haomeiwen.com/i2469645/93836bb224ccd7a3.png)
但是白屏
因为vue是运行在8080端口,服务器端在8888端口,就猜想会不会是跨域
用了以下方法
解决Vue跨域访问后端API问题
例子:
// vue.config.js
module.exports = {
devServer: {
proxy: {
// 当你vue请求路径中包含/api,那么vue会自动帮你代理请求到你的后端地址
// 比如我vue请求的是 '/api/user/getUser',那么会帮我代理请求到后端地址
'/api': {
// 后端地址
target: "http://localhost:8081",
/**
官方文档的意思:将主机头的来源更改为目标 URL
简单理解就是需不需要代理
**/
changeOrigin: true,
/**
重写目标地址,比如我vue请求的是/api/user/getUser
经历过重写之后,我们请求的地址是http://localhost:8081/user/getUser
这里用的是正则表达式,^符号是用来限制开头
意思就是匹配vue请求的开头是否为/api,是的话就进行重写替换
**/
pathRewrite: {
["^/api"]: ""
}
}
}
}
}
在本项目中修改为:
proxyTable: {
'/': {
target: 'http://localhost:8888/xxx_admin/',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
}
},
![](https://img.haomeiwen.com/i2469645/223f3eaddfb6d76b.png)
成功