react单独配置代理

首先在src文件下创建setupProxy.js文件,和App.js同一级,例如:

const { createProxyMiddleware } = require('http-proxy-middleware');
//更新后使用的是createProxyMiddleware,以前使用的是proxy
module.exports = function(app){
    app.use(
        createProxyMiddleware('/api1',{ //遇见/api1前缀的请求,就会触发该代理配置
            target:'http://localhost:5000', //请求转发给谁
            changeOrigin:true,//控制服务器收到的请求头中Host的值
            pathRewrite:{'^/api1':''} //重写请求路径(必须)
        })
    ),
    app.use(
        createProxyMiddleware('/api2',{ //遇见/api2前缀的请求,就会触发该代理配置
            target:'http://localhost:5000', //请求转发给谁
            changeOrigin:true,//控制服务器收到的请求头中Host的值
            pathRewrite:{'^/api1':''} //重写请求路径(必须)
        })
    )
    //.....可以定义多个不同的代理 
}
使用的时候,例如:
 1 search = ()=>{
 2         //获取用户的输入(连续解构赋值+重命名) {value:keyWord} keyWord就是value的别名
 3         const {keyWordElement:{value:keyWord}} = this
 4         //发送请求前通知App更新状态
 5         this.props.updateAppState({isFirst:false,isLoading:true})
 6         //发送网络请求
 7         axios.get(`/api1/search/users?q=${keyWord}`).then(
 8             response => {
 9                 // console.log(response.data.items)
10                 this.props.updateAppState({isLoading:false,users:response.data.items})
11             },
12             error => {
13                 //请求失败后通知App更新状态
14                 this.props.updateAppState({isLoading:false,err:error.message})
15             }
16         )
17     }

 

 

不停学习,热爱是源源不断的动力。
原文地址:https://www.cnblogs.com/ximenchuifa/p/14951378.html