vue 项目中解决跨域方法-代理
// 1. 起因:前端 localst:8000,请求后端接口,域名,端口,协议不同,浏览器同源策略,这时候出现了跨域问题
// 2. 我们请求的地址 /get/userinfo,它是拼接在 localhost:8000的后面,即localhost:8000/get/userinfo
// 3. 代理转发:即 localhost:8000/api/get,把/api 之前本地服务器地址改为后端接口,内部进行了处理
// 3.1 实际上 http:localhost:8000/api/get--->htttp:xxxxx(后端地址)/api/get
// 3.2 proxy 配置中,pahtRewirte 作用,内容处理将后端接口,htttp:xxxxx(后端地址)/api/get,的/api 删除
// 3.3 我们在浏览器看到 /api 不用理睬
在vue.config.js 中
devServer:{
proxy:{
'/api':{//表示拦截以/api开头的请求路径
target:'http://(这里填你项目真实的后端地址)',
changOrigin: true,//是否开启跨域
pathRewrite:{
'^/api':'' //重写api,把api变成空字符,因为我们真正请求的路径是没有api的
}
}
}
}
在使用 create 创建 axios 的实例的时候将baseURL设置为api
const request = axios.create({
baseURL: 'api',
timeOut: 5000
})