vue2中请求跨域配置
实例:
请求接口为:http://api.zhuishushenqi.com/cats/lv2/statistics
在vue.config.js文件里配置:
写法一:
module.exports = {
devServer:{
port:9009,
proxy:{
"/aaa":{
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
pathRewrite:{
"^/aaa": ""
}
}
}
}
}
请求接口:
Axios.get("/aaa/cats/lv2/statistics").then(res=>{
console.log(res);
})
请求成功:
Request Url并不是真实请求路径,真实请求路径在网页上是看不到的,
1.请求接口的前缀有/aaa,触发代理请求,
2.代理请求把ip替换成target的地址
3.pathRewrite,将请求路径中的/aaa替换成""
pathRewrite作用:
“^/aaa”:在整个请求路径中匹配以字符串/aaa开头的的字符,并替换为""
请求路径变化:
pathRewriteh写法遇到的一些问题:
1.重写路径为 /
pathRewrite:{
"^/aaa": "/"
},
结果:可以请求成功,但真实请求路径多了一个/
2.不写pathRewriteh配置项
proxy:{
"/aaa":{
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
} ,
}
请求结果:404,重写失败,只替换了target配置的域名
写法二:
module.exports = {
devServer:{
port:9009,
proxy:{
"/cats":{
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
pathRewrite:{
"^/cats": "/cats"
}
}
}
}
}
页面请求:
Axios.get("/cats/lv2/statistics").then(res=>{
console.log(res);
})
请求成功:
pathRewrite配置项的匹配内容与接口的一段路径相同,
pathRewrite原理与写法一相同,
由于生产环境代理不起作用,建议还是用写法二,不然还需另外处理请求路径中多出来的aaa,
查看真实请求路径
module.exports = {
devServer:{
port:9009,
proxy:{
"/cats":{
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
pathRewrite:{
"^/cats": "/cats"
},
onProxyReq: (proxyReq, req) => {
console.log("原来请求路径:", req.originalUrl);
console.log("真实请求路径:",req.url);
},
onProxyRes(proxyRes, req, res) {
const realUrl = process.env.BASEURL + req.url || ''
proxyRes.headers['A-Realurl'] = req.url; // 添加响应头,A-Realurl是自定义命名,在浏览器中显示
console.log(realUrl);
},
} ,
}
}
}
请求结果:
vue3中跨域处理
vue-cli脚手架创建的vue3项目:
配置与上面vue2的配置相同,
构建工具为vite的vue3项目
在vite.config.js文件中配置:
写法1
export default defineConfig({
server: {
proxy: {
"/aaa": {
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/aaa/, ''),
bypass(req, res, options) {
console.log("req",req.url);
const realUrl = options.target + (options.rewrite ? options.rewrite(req.url) : '');
console.log(realUrl);
res.setHeader('A-realurl', realUrl); // 添加响应标头,A-realurl为自定义命名,在浏览器中显示
},
}
}
}
})
页面请求:
axios.get("/aaa/cats/lv2/statistics").then(res=>{
console.log("res",res);
}).catch(err=>{
console.log("错误",err);
})
请求成功,A-Realurl为请求的真实地址
rewire把请求路径根据正则表达式匹配aaa,并替换为"",
写法2:
export default defineConfig({
server: {
proxy: {
"/cats": {
target: "http://api.zhuishushenqi.com",
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/cats/, '/cats'),
bypass(req, res, options) {
console.log("req",req.url);
const realUrl = options.target + (options.rewrite ? options.rewrite(req.url) : '');
console.log(realUrl);
res.setHeader('A-realurl', realUrl); // 添加响应标头,A-realurl为自定义命名,在浏览器中显示
},
}
}
}
})
页面请求:
axios.get("/cats/lv2/statistics").then(res=>{
console.log("res",res);
}).catch(err=>{
console.log("错误",err);
})
请求结果: