多種解決react中跨域問題方案
在網上看到了多種解決react跨域的方法,但是在實際的項目中並不是所有的方法都是可行的。
一、最簡單的操作
在package.json中加入
"proxy": "http://localhost:8000"
然后你頁面中的請求fetch('/api/userdata/')就會轉發到proxy中的地址
也就是真實的請求是http://0.0.2.89:7300/api/userdata/,而且也不會有跨域問題
因為在瀏覽器看來,你只是發了fetch('/api/userdata/'),沒有跨域問題
二、添加多個代理
在package.json中加入
"proxy": {
"/api": {
"target": "http://localhost:8000",
"changeOrgin": true
},
"/app": {
"target": "http://localhost:8001",
"changeOrgin": true
}
},
使用方法
axios.post('/api/users').then(res =>{
console.log(res)
})
但是當重新執行npm start時會報錯,說"proxy"的值應該是一個字符串類型,而不能是Object。
其原因是由於react-scripts模塊的版本過高,需要刪除到原目錄下node_modules中的react-scripts文件夾,安裝低版本
npm install react-script@1.1.1 --save
的確跨域問題可以解決了,但是又出現了新的問題,我在項目中使用了sass,當把react-scripts改為低版本后並不支持對sass的解析,如果要想支持sass的話,需要到 node_modules/react-scripts/config中進行配置,但是並不推薦你這樣做。
三、最佳推薦
下載 http-proxy-middleware
npm i http-proxy-middleware --save
創建 src/setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// /api 表示代理路徑
// target 表示目標服務器的地址
app.use(
proxy('/api', {
// http://localhost:4000/ 地址只是示例,實際地址以項目為准
target: 'http://localhost:4000',
// 跨域時一般都設置該值 為 true
changeOrigin: true,
// 重寫接口路由
pathRewrite: {
'^/api': '' // 這樣處理后,最終得到的接口路徑為: http://localhost:8080/xxx
}
})
)
}