简单粗暴,依旧直接上代码
在实际项目中往往不想直接暴露后台的真实接口,我们可以通过配置代理接口进行伪装请求。
-
打开项目中
/config/index.js文件

-
找到
module.exports配置

-
在
dev模块中进行如下配置:

// Proxy
proxyTable: {
'/web/api': {
target: 'http://localhost:8081',
// 设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true,
pathRewrite: {
'^/web/api': ''
// 这里理解成用‘/web/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替
// 比如我要调用'http://localhost:8081/web/user/rest/get',
// 直接写‘/web/api/web/user/rest/get’即可
}
}
}
}
- 配置完成后重跑项目后就可以在
service.js组件中使用代理接口了

代理的分发
在面试的时候曾被问到,“如何在一个前端项目向不同的后台发送代理请求?”,当时有点懵,现在慢慢补课webpack理解了DevServer于是这些都支持配置。
proxy:{
'/admin': {
target: 'http://localhost:8081/',
changeOrigin: true,
pathRewrite: {
'^/web/api/manager': ''
}
},
'/user': {
target: 'http://localhost:8082/',
changeOrigin: true,
pathRewrite: {
'^/web/api/living': ''
}
}
}

本文介绍如何在前端项目中配置代理接口,以隐藏真实的后台接口,通过示例代码展示了如何设置不同模块的代理请求,适用于面试准备和技术提升。
416

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



