React脚手架配置axios代理 (1.配置在package.json, 2.配置在setupProxy.js)

1:给项目安装axios

npm install axios

2:导入axios工具包

import axios from 'axios';

React脚手架添加中间代理实现跨域(方法一)

配置单个代理

在项目的package.json文件中添加:

"proxy":"http://localhost:5000/"

使用的地方直接使用

import axios from 'axios';
  

click = () => {
    axios.get('http://localhost:3000/ctiy').then(
      response => {
        console.log('获取数据成功',response.data)
      },
      error => {
        console.log('获取数据失败',error)

      }
    )
}

React脚手架添加中间代理实现跨域(方法二 :setupProxy.js)

配置多个代理

  1. 在src文件中添加setupProxy.js文件 ,无需单独应用,webpack会自动引入文件。 
  2. setupProxy.js中写的是common.js语法
  3. setupProxy.js中的文件内容

react17版本的代理配置需要在src/setupProxy.js中配置

 

setupProxy.js内容

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    proxy('/api11', {
      target: "http://localhost:5000",
        //target配置成'http://localhost:5000'意味着只要发现/api11前缀的请求,
        //就自动转发到'http://localhost:5000'这个地址,
        //并且通过配置pathRewrite: {'^/api11': ''}把添加了/api11的请求地址还原回去
      changeOrigin: true, 
        // 控制服务器收到的请求头中的Host的值 如果设置为true,服务器不会知道真实的请求地址,
        //只会知道代理的地址,如果设置为false,服务器会知道真正请求的地址
      pathRewrite: {'^/api11': ''} 
        // 重写请求路径 这个必须要加,如果不加 服务器端收到的请求地址是 /api/url 请求地址就不对了
    }),
    proxy('/banzhuan', {
      target: "http://localhost:5001",
      changeOrigin: true,
      pathRewrite: {'^/banzhuan': ''}
    })
  )
}

 

react18版本的配置,主要的差异是需要用http-proxy-middleware中的createProxyMiddleware创建代理

 

setupProxy.js内容

const {createProxyMiddleware} = require('http-proxy-middleware');

module.exports = function (App) {
  App.use(
    createProxyMiddleware('/api11', {
        target: 'http://localhost:5000',
        changeOrigin: true,
        pathRewrite:{'^/api11':''}
      }
    ),
    createProxyMiddleware('/banzhuan', {
        target: 'http://localhost:5001',
        changeOrigin: true,
        pathRewrite:{'^/banzhuan':''}
      }
    )
  )
}

页面使用

使用页面内容
  click = () => {
    axios.get('http://localhost:3000/api11/ctiy').then(
      response => { console.log('请求成功', response) },
      error => {console.log('请求失败,',error)}
    )
  }
  clickCase = () => {
    axios.get('http://localhost:3000/banzhuan/cars').then(
      response => { console.log('小汽车请求成功', response) },
      error =>{console.log('失败',error)}
    )
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值