问题
我们遇到请求后台接口遇到Access-Control-Allow-Origin 时,那说明跨域了,
开发中遇到请求后台接口跨域问题时,可以尝试使用代理方法,需要配置前端代码.
vue版
1.在vue.config.js中设置如下代码片段
devServer: {
hot: true,//热更新
port: 1234,//访问项目时的端口号
open: true,//编译自动打开浏览器
secure:false,//若target是https,并且secure是true,就会停止访问
proxy: {
'/api': {
target: "http://www.xxx.com",
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': "",
},
},
},
},
2.注意在使用时url地址需要写成这样,不要带域名,
request({
url: '/api/login', //如果proxy下配置的是'api' url要写成'api/login'否则匹配不到
method: 'post',
data,
})
uni-app版
1.在manifest.json文件 源码视图下
"h5": {
"devServer": {
"hot": true,
"port": 5173,
"proxy": {
"/api": {
"target": "http://www.xxx.com",
"ws": true,
"changeOrigin": true,
"pathRewrite": {
"^/api" : ""
}
}
}
}
},
2.注意在使用时url地址注意不要带域名.
当请求后台接口遇到Access-Control-Allow-Origin错误时,说明存在跨域问题。为解决此问题,可以配置前端代理。在Vue项目中,可以在vue.config.js中设置devServer的proxy属性,将/api路径指向目标服务器。对于uni-app,需在manifest.json的h5部分配置devServer和proxy。在使用时,URL应仅包含/api路径,不带域名。

1858

被折叠的 条评论
为什么被折叠?



