react---配置代理

方式一:在package.json中添加proxy【 "proxy":"http://localhost:5000"  】

  • 优点:配置简单,前端请求资源时可以不加任何前缀。
  • 缺点:不能配置多个代理。
  • 工作方式:上述方式配置代理,当请求了3000(默认)不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)

方法二

  1. 创建代理配置文件,在src下创建配置文件:src/setupProxy.js

  2. 编写setupProxy.js配置具体代理规则:

    // const proxy=require('http-proxy-middleware') //低版本的http-proxy-middleware的引入方式,当前安装的2.0.6版本不适用
    const {createProxyMiddleware: proxy} = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use(
        proxy('/api1', {  //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
          target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址)
          changeOrigin: true, //控制服务器接收到的请求头中host字段的值
          /*
          	changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
          	changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000
          	changeOrigin默认值为false,但我们一般将changeOrigin值设为true
          */
          pathRewrite: {'^/api1': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
        }),
        proxy('/api2', { 
          target: 'http://localhost:5001',
          changeOrigin: true,
          pathRewrite: {'^/api2': ''}
        })
      )
    }
    
  • 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
  • 缺点:配置繁琐,前端请求资源时必须加前缀

案例代码【App.jsx】

import React, { Component } from 'react'
import axios from 'axios';
export default class App extends Component {
    getStudents=()=>{
        axios.get("http://localhost:3000/api1/students").then(
            res=>{console.log("res>>>",res.data);},
            err=>{console.log("err>>>",err);}
        )
    }
    getCars=()=>{
        axios.get("http://localhost:3000/api2/cars").then(
            res=>{console.log("res>>>",res.data);},
            err=>{console.log("err>>>",err);}
        )
    }
  render() {
    return (
      <div>
        <button onClick={this.getStudents}>请求学生数据</button>
        <button onClick={this.getCars}>请求汽车数据</button>
      </div>
    )
  }
}

【server1.js】

const express=require("express")
const app=express()

app.use((request,response,next)=>{
    console.log("有人请求服务器1了");
    console.log("请求Host",request.get('Host'));
    console.log("请求来自于",request.url);
    next()
})
app.get("/students",(req,res)=>{
    const students=[
        {id:"1",name:"Tom",age:12},
        {id:"2",name:"Mike",age:23},
        {id:"3",name:"Jerry",age:25},
    ]
    res.send(students)
})
app.listen(5000,()=>{
    console.log("listen http://localhost:5000");
})

【server2.js】

const express=require("express")
const app=express()

app.use((request,response,next)=>{
    console.log("有人请求服务器2了");
    console.log("请求Host",request.get('Host'));
    console.log("请求来自于",request.url);
    next()
})
app.get("/cars",(req,res)=>{
    const students=[
        {id:"1",name:"奔驰",price:112},
        {id:"2",name:"劳斯莱斯",price:623},
        {id:"3",name:"保时捷",price:525},
    ]
    res.send(students)
})
app.listen(5001,()=>{
    console.log("listen http://localhost:5001");
})

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值