【发布时间】:2022-01-03 02:40:36
【问题描述】:
我正在使用 React、Express、PostgreSQL、Node 和 Fetch API。当我尝试运行“GET”请求(在try 块内)以从我的数据库中获取数据时,请求失败(并进入catch 块)并出现以下错误:
Unexpected token < in JSON at position 0
这是我在前端的失败代码:
const getRequests = async () => {
try {
const responseInfo = await fetch("/api/advice-requests", {
headers: { "Accept": "application/json" },
});
if (responseInfo.status === 200) {
console.log("200 running"); // This is logged to the console.
const data = await responseInfo.json();
console.log("data :", data); // This is NOT logged to the console. It fails.
setAdviceRequests(data.requests);
setResponses(data.responses);
return;
}
} catch (error_o) {
// The UI is updated with the text of the below error
setError(
"Something went wrong on our end. We are looking into how we can improve..."
);
return;
}
};
这是我的一些服务器代码(还有更多,但不相关),包括我为解决此问题而进行的一些更改。
const adviceRequests = require("./controllers/adviceRequests");
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cors());
app.options("*", cors());
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "../build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "../build", "index.html"));
});
}
app.get("/api/advice-requests", adviceRequests.getAll);
app.listen(PORT, () => {
console.log(`SERVER RUNNING ON ${PORT}.`);
});
最后,这里是adviceRequests.getAll 函数:
getAll: async (req, res) => {
const db = req.app.get("db");
try {
let requests = await db.requests.getAll(req.session.user.id);
let responses = await db.responses.getAll([req.session.user.id]);
return res.status(200).send([requests, responses]);
} catch (error) {
return res.status(500).send({
message:
"Something went wrong on our end. We are looking into how we can improve.",
error,
});
}
},
更多信息:
- 代码在本地运行时运行良好
- 即使在实时服务器上,我也可以成功运行多个 POST 请求以进行身份验证和添加请求。我就是无法得到它们。
- 我对此进行了相当多的研究,并将我自己的发布作为最后的手段。到目前为止,对其他人有用的东西都对我有用。
【问题讨论】:
标签: node.js reactjs postgresql express fetch-api