Vue及React中跨域配置

6 篇文章 0 订阅

Vue

配置代理
在 config/index.js 中配置 proxyTable

dev: {
  //......
  proxyTable: {
    '/api': {
      target: 'http://192.168.0.104/',  //目标接口域名
      changeOrigin: true,  //是否跨域
      pathRewrite: {
      	// 接口重写 替换请求地址中的指定路径
        '^/api': '/' // 调用接口时用 api 替换为空
        //例如要调用 http://192.168.0.104/getdata 直接写成 /api/getdata 即可
      }
    }
  }
 //......
}

使用示例
我们实际上是要调用的接口是 http://192.168.0.104/getdata , 示例将 http://192.168.0.104 替换成了我们在 proxyTable 中配置的 /api

// 直接使用 fetch 调用接口
fetch("/api/getdata",{
  method:"get"
}).then(res=>{
  return res.json()
}).then(data=>{
  console.log(data)
})

// axios 这里省略 axios 配置
this.$http.get("/api/getdata").then(res=>{
  console.log(res.data)
})

原理
发起请求时 Network 中可以看到 请求地址是 http://localhost:8080/api/getdata
我们配置的 proxyTable 拦截了/api及其前面的地址,替换成了 target 中的内容,因此实际访问 url 是 http://192.168.0.104/getdata
在这里插入图片描述

React

  1. proxy 配置
    可直接在 package.json 中配置 proxy
{
	"name": "work",
	"version": "0.1.0",
	"private": true,
	"proxy": "http://192.168.0.104/",
	......
}

如果需要配置多个

"proxy": {
  "/api": {
    "changeOrigin": true,
    "target": "http://192.168.0.104/"
  },
  ....更多配置
}

如果报以下错误,是因为 react-scripts 版本太高
重装 2.0 以下版本 npm i react-scripts@1.1.1 --save
When specified, “proxy” in package.json must be a string.
Instead, the type of “proxy” was “object”.
Either remove “proxy” from package.json, or make it a string.

2. http-proxy-middleware 插件

  • 首先安装 http-proxy-middleware
npm install http-proxy-middleware --save
  • 在 src 目录下新建 setupProxy.js
    创建好文件后会自动引用,无需其他配置
const { createProxyMiddleware } = require('http-proxy-middleware');
// 1.0以下 的版本用下面的方式引入模块
//const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    createProxyMiddleware("/api", {
      target: "http://192.168.0.104/",
      changeOrigin: true
    })
  );
  //......多个配置
  app.use(
    createProxyMiddleware("/url", {
      target: "http://192.168.1.114/",
      changeOrigin: true
    })
  );
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值