[英]React Fetch to Node Server in Herokuapp
I'm attempting to fetch data from my node.js server (which is on port 7000) through react in heroku with this code:我正在尝试通过在 heroku 中使用以下代码做出反应,从我的 node.js 服务器(位于端口 7000)中获取数据:
const { name } = e.target.elements;
let details = {
name: name.value,
};
let response = await fetch("/post", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
},
body: JSON.stringify(details),
});
and this server setup:这个服务器设置:
if(process.env.NODE_ENV === "production") {
app.use(express.static('../client/build'));
app.get('*', (req, res) => {
req.sendFile(path.resolve('client/build/index.html', { root: "../" }));
});
}
app.post("/post", async (req, res) => {
const queryRes = await searchFromQuery(req.body.name);
res.json({
status: queryRes.isFound ? "found" : "notFound", teaminfo: {
name: queryRes.name,
number: queryRes.number,
avgScore: queryRes.avgScore,
predictedScore: queryRes.predictedScore,
}
});
});
app.listen(PORT, console.log(`Server started on port ${PORT}`));
app.get("/", function(req, res) {
res.sendFile('client/build/index.html', { root: "../" });
});
However, when I print out req there doesn't seem to be any data related to the react request.但是,当我打印出 req 时,似乎没有任何与反应请求相关的数据。 I believe it has to do with my express setup (which I set to express.static() for heroku, though it was initially express.json())
我相信这与我的快速设置有关(我为 heroku 设置为 express.static(),尽管它最初是 express.json())
Additionally, the proxy in my package.json is still set to http://localhost:7000
.此外,我的 package.json 中的代理仍设置为
http://localhost:7000
。
Issue resolved by adding app.use(express.json())
back to the server file alongside static.通过将
app.use(express.json())
与 static 一起添加回服务器文件解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.