React配置代理方式(proxy)
React配置代理(proxy)
使用axios進行請求,而配置代理過程
第一種
在package.json中,添加proxy配置項,之后所有的請求都會指向該地址
但這種方法只能配置一次,也只有一個
- 示例:
"proxy":"https://localhost:5000"
添加后,重啟項目!?。∽屌渲梦募虞d生效
然后就可以進行請求了
比如請求地址是
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-middleware,react腳手架已經(jīng)安裝
module.exports = function(app){
app.use(
proxy.createProxyMiddleware('/api',{ //遇見/api1前綴的請求,就會觸發(fā)該代理配置
target:'http://localhost:5000', //請求轉發(fā)給誰
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-middleware,react腳手架已經(jīng)安裝
module.exports = function(app){
app.use(
proxy('/api',{ //遇見/api1前綴的請求,就會觸發(fā)該代理配置
target:'http://localhost:5000', //請求轉發(fā)給誰
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);}
)總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
react中fetch之cors跨域請求的實現(xiàn)方法
本篇文章主要介紹了react中fetch之cors跨域請求的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
修復Next.js中window?is?not?defined方法詳解
這篇文章主要為大家介紹了修復Next.js中window?is?not?defined方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
react-router-dom入門使用教程(前端路由原理)
這篇文章主要介紹了react-router-dom入門使用教程,主要包括react路由相關理解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08

