[英]React proxy doesn't work on npm run build
我正在嘗試使用 axios 與后端服務器通信。 所以我在 package.json 中添加了代理,如下所示。
package.json
"proxy": "http://backend:8080",
它適用於“npm start”,但是當我嘗試“npm run build”時,我無法與后端通信。
axios.get('/member/login',{
headers :{
Authorization : hash
}
})
因此,我嘗試將完整的 url 如下所示,但仍然無法通信。
axios.get('http://backend:8080/member/login',{
headers :{
Authorization : hash
}
})
我怎么解決這個問題??
好像是npm運行構建后通過server.js部署的。所以為了以防萬一,我也上傳server.js代碼。
服務器.js
const http=require("http");
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
app.get("/ping",(req,res) =>{
res.send("pong");
});
app.use(express.static(path.join(__dirname,"build")));
app.use('/', express.static(__dirname+'/server/build'))
app.get("/*",(req,res) => {
res.set({
"Cache-Control":"no-cache, no-store, must-revalidate",
Pragma:"no-cache",
Date:Date.now()
});
res.sendFile(path.join(__dirname,"build","index.html"));
});
http.createServer(app).listen(port,()=>{
console.log(`app listening arr ${port})`);
});
React uses http://localhost:3000/ by default, backend port could be anything other than 3000. say if the backend port is 8080, then url to get data: http://localhost:8080/
代理功能僅用於開發(使用npm start
)。 女巫意味着它不適用於生產(使用npm build
)。 你可以在這里查看
在生產中( npm run build
)它只是創建 static 文件來部署,這使得代理沒有意義,因為在這個階段沒有開發服務器。 相反,現在您必須在您選擇的任何服務器上提供您的 static 文件。 例如,在nginx 服務器中,您可以使用proxy_pass
您可以嘗試使用默認值:
axios.defaults.baseURL = 'http://backend:8080';
您是否安裝並導入了 axios?
npm 安裝 axios
從'axios'導入axios;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.