proxy代理的使用(解决跨域,配置多个代理)

1,007 阅读2分钟

proxy代理的使用(解决跨域,配置多个代理)

vue cli3示例

image.png

  devServer: {
    proxy:{
      "/api": {
          target: "http://www.xiongmaoyouxuan.com", // 需要代理的域名
           ws: false, // 是否启用websockets
          changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
          pathRewrite: {  //重写匹配的字段,如果不需要在请求路径上,重写为""
              "^/api": "/api"
          }
      },
   
  },
  }
 
  //cli2的放在config文件夹中的index.js  中
    dev: {
    proxyTable:{
      "/api": {
          target: "http://www.xiongmaoyouxuan.com", // 需要代理的域名
           ws: false, // 是否启用websockets
          changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
          pathRewrite: {  //重写请求路径上匹配到的字段,如果不需要在请求路径上,重写为""
              "^/api": "/api",
              "demo.json": "index.json"
          }
      },
  },
  }

在创建axios的时候,beseURL这样配置

    baseURL:"/api",
    timeout: 6000,//请求超时时间
})
 

创建的请求

  return request({
    url: '/search/home',
    method: 'GET'
  })
}
 

这样匹配到这个字段时就会代理到target去,将target添加到/前面,在根据pathRewrite,然后是你请求的ajax
意思大概就是,你的beseURL加上你请求的url满足proxy的匹配,那你的代理就是没问题的
同时处理的也是匹配到的部分。
这样虚拟服务器请求的的就是

www.xiongmaoyouxuan.com/api/search/…

但你本地看见的请求地址可能是这样的

image.png

配置多个代理

只需让你本地请求,满足代理的规则即可

      "/api": {
          target: "http://www.xiongmaoyouxuan.com", 
          // ws: true, 
          changeOrigin: true
          pathRewrite: {
              "^/api": "/api"
          }
      },
      "/user": {
          target: "http://www.xiongmaoyouxuan.com",
          // ws: true, 
          changeOrigin: true
          pathRewrite: {
              "^/user": "/api"
          }
      },
   
  }, 

在创建axios的时候,beseURL这样配置

    baseURL:"/",
    timeout: 6000,//请求超时时间
})
 

创建的请求

export function getData() { //get
  return request({
    url: 'api/search/home',
    method: 'GET'
  })
}
export function getData1() { //get
  return request({
    url: 'user/search/home',
    method: 'GET'
  })
}