好网站123,淘宝客建网站要钱的吗,权威解读当前经济热点问题,丽江网页制作公司使用axios进行请求#xff0c;而配置代理过程。
第一种
在package.json中#xff0c;添加proxy配置项,之后所有的请求都会指向该地址 但这种方法只能配置一次#xff0c;也只有一个 示例#xff1a;
proxy:https://localhost:5000
添加后而配置代理过程。
第一种
在package.json中添加proxy配置项,之后所有的请求都会指向该地址 但这种方法只能配置一次也只有一个 示例
proxy:https://localhost:5000
添加后重启项目让配置文件加载生效 然后就可以进行请求了 比如请求地址是 http://localhost:5000/api/index/index 那就可以写
axios.get(/api/index/index).then(response {console.log(成功了,response.data);},error {console.log(失败了,error);}
)第二种
在src中新建setupProxy.js必须是这个名字react脚手架会识别在文件中写以下配置内容最近的项目要使用高版本这个不然会导致项目无法启动 http-proxy-middleware高版本2以上
const proxy require(http-proxy-middleware)//引入http-proxy-middlewarereact脚手架已经安装module.exports function(app){app.use(proxy.createProxyMiddleware(/api,{ //遇见/api1前缀的请求就会触发该代理配置target:http://localhost:5000, //请求转发给谁changeOrigin:true,//控制服务器收到的请求头中Host的值pathRewrite:{^/api:} //重写请求路径下面有示例解释}),proxy.createProxyMiddleware(/api2,{target:http://localhost:5001,changeOrigin:true,pathRewrite:{^/api2:}}),)
}http-proxy-middleware低版本2以下
const proxy require(http-proxy-middleware)//引入http-proxy-middlewarereact脚手架已经安装module.exports function(app){app.use(proxy(/api,{ //遇见/api1前缀的请求就会触发该代理配置target:http://localhost:5000, //请求转发给谁changeOrigin:true,//控制服务器收到的请求头中Host的值pathRewrite:{^/api:} //重写请求路径下面有示例解释}),proxy(/api2,{target:http://localhost:5001,changeOrigin:true,pathRewrite:{^/api2:}}),)
}写好以后重启项目 然后进行请求
假设地址是 http://localhost:5000/api/index/index
//没有开启重新路径
axios.get(/api/index/index).then(response {console.log(成功了,response.data);},error {console.log(失败了,error);}
)
//开启重写路径
axios.get(/api/api/index/index).then(response {console.log(成功了,response.data);},error {console.log(失败了,error);}
)