在前端请求时候会发生跨域,反向代理就是解决跨域方法之一。
例如 请求的地址为https://www.vue-js.com/api/v1/topics
在vue.config.js中配置
module.exports = defineConfig({
transpileDependencies: true,
devServer:{
proxy:proxy,
port:8089
}
})
const proxy:{
"/api":{
changeOrigin:true,
pathRewrite:{
"^/api":"/api/v1/topics"
},
target:"https://www.vue-js.com"
}
}
我们在请求时候比如 axios.get({ url:"/api" })
在发送后代理服务器会把这个请求拦截了,把axios.get({ url:"/api" })中的/api前面加上proxy的target,添加之后为https://www.vue-js.com/api就相当于axios.get({ url:"https://www.vue-js.com/api" }),然后通过proxy的pathRewrite属性的替换方式,把https://www.vue-js.com/api中的/api替换成/api/v1/topics,最后总的请求地址为https://www.vue-js.com/api/v1/topics。