1. 前言
- 可能我们经常有场景 配置多个代理,但是在具体发起请求的时候 就不知道怎么发了,因为
axios
中的baseurl
只能配置一个,- 之前有文章vue-axios配置写过解决方案,但不是重点
- 所以单独在写篇文章
config.js
文件配置多个代理,axios如何发起请求,如何配置baseurl
2. 代理配置
config.js
devServer:{ open:true, host:"127.0.0.1", // host:"yzs.com",//host文件配置域名 proxy:{ "/dyapi":{ target:"http://xx.x.cn/api/RoomApi", ws:true, ChangeOrigin:true, pathRewrite:{ "^/dyapi":"" } }, '/elmapi':{ // 不一定非得写域名/一般是写 所有接口前面 都一样的 部分/url target:'https://xx.xx.org', ws:true, changeOrigin:true, pathRewrite:{ '^/elmapi':'' } } } }
- 配置多个代理
3. axios 二次封装
http.js
文件
//************2. 创建实例 */ const instance = axios.create({ baseURL: "/dyapi", // timeout: 1000, // headers: {'X-Custom-Header': 'foobar'} });
- 只配置了 一个常用的
baseurl
4. 页面使用 dyapi
代理的使用
dyapi
代理的使用
import request from '@/src/api/http.js'; export const getLiveList = (params = {offset:0,limit:10})=>{ return request.get("/live",{ params }) }
- 就是直接 使用
- 因为 二次封装
http.js
里面 已经设置了baseURL: "/dyapi",
- 实际请求效果: ``http://127.0.0.1:8081/dyapi/live?offset=0&limit=10`
5. 页面使用 elmapi
代理
5.1 通用方式
- 核心代码
import request from '@/src/api/http.js'; export const postLiveList = (params ={name:"玩被"})=>{ return request({ url:"/v1/captchas",// 接口地址 method:"POST" // 请求方式 baseURL:'/elmapi',// baseurl data:params,// post请求参数 }) }
- 直接通用配置 的
baseURL:'/elmapi',
- 这个优先级会高于 二次封装
http.js
里面的baseURL
- 实际请求效果:
http://127.0.0.1:8081/elmapi/v1/captchas
5.2 实例使用
- 核心代码
import request from '@/src/api/http.js'; export const postLiveList = (params ={name:"玩吧"})=>{ return request.post("/v1/captchas",params,{ baseURL:'/elmapi', }) }
- 具体的
post
实例 使用'- 注意参数的配置
6. 后记
- 有些文章需要 专一一个知识点
- 有些需要体系的总结