【问题标题】:Cannot run .JSON on response from the Fetch API无法根据 Fetch API 的响应运行 .JSON
【发布时间】: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


    【解决方案1】:

    每次我有这个“意外的令牌 开头

    我建议你将这个console.log("200 running"); 更改为console.log(responseInfo);,这样你就会注意到响应是否为json。

    据我所知,问题可能是定义 app.get 的顺序。请注意,快递服务先到先得,因此由于您已经定义了 app.get("/*"),因此所有内容都将通过该路由提供服务。另请注意,您正在发回一个 index.html,它与前端显示的问题相匹配。

    【讨论】:

    • 这是命令!太感谢了!!我花了大约 8 个小时来尝试不同的解决方案,并将 app.get("/*") 移到其他请求之下。感谢您抽出宝贵时间阅读并回答该问题。
    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2020-03-31
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多