配置代理转发:
1、vue.config.js文件进行配置
const { defineConfig } = **require**('@vue/cli-service')
**module**.exports = defineConfig({
transpileDependencies: true,
devServer:{
// 设置项目端口和自动启动浏览器
host:'localhost',
port:8000,
open:true,
//配置代理
proxy:{
'api':{ //配置名为'api'的代理
target:'http://localhost:8082', //请求后台服务端的IP,即代理转发的目标地址
pathRewrite:{'^/api':''}, //重写请求路径
changeOrigin:true //开启跨域
}
}
}
})
2、axios请求中路径为:'/api/**'
getStudent() {
axios.get("/api/student/list").then(resp => {
this.tableData= resp.data;
})
},
上述代码具体解释如下:
当在前端发起请求时,如果路径以'/api'开头,代理会将这个请求转发到'http://localhost:8082',并且将路径中的‘/api’替换为空字符串,同时 changeOrigin:true会修改请求头中的host字段,使得目标服务器认为请求是从本地发起的,解决了跨域的问题