Vue使用代理处理跨域及注意点

webpack链接: https://webpack.docschina.org/configuration/dev-server/#devserverproxy.

假设接口地址为:
http://localhost:9000/api/contact
http://localhost:9000/api/contactList
http://localhost:8000/api/xxx

配跨单域


//配代理:
    proxyTable: {
      "/api":"http://localhost:9000"
    } 
//发请求
const body = axios.get("/api/contactList")
    proxyTable:{ 
         "/api":"真正接口的域(服务器的地址)"
    }
    
    发请求时  直接往 /api/path 上发  

    或者配置基地址    baseURL:"/api",
    发送请求时可写const body = axios.get("/contactList")

配跨多域

//配代理:
 proxyTable:{
      "/9000":{
        target: "http://localhost:9000",
        pathRewrite: {"^/9000" : ""}
      },
      "/8000":{
        target: "http://localhost:8000",
        pathRewrite: {"^/8000" : ""}
      },
    }

//发请求:
const body  = axios.get("/9000/api/contactList")
const body2 = axios.get("/8000/api/xxx")
    proxyTable:{
        "/标识":{
            target: "真正接口的域",
            pathRewrite: {"^/标识" : ""}
        }
    }
    发请求时 直接往  /标识/api/path 上发

    或者添加多个实例配置基地址 :
    baseURL:"/9000/api"
    baseURL:"/8000/api"
    发请求时只需要写
    const body  = $axiosInstance1.get("/contactList")
    const body2 = $axiosInstance2.get("/xxx")

注意点

  1. 所有请求的baseURL中都不能将域名固定死
  2. 在对应的静态资源服务器中配代理!
    vue-cli脚手架去修改 config / index.js—>proxyTable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值