繁体   English   中英

当我尝试在我的 React 项目中获取数据时,我收到此错误: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

[英]When i try to fetch data in my React project, then I get this error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我想在我的反应项目中使用特定的 email 从 MongoDb 获取过滤数据。 因此,我使用 email 创建了一个 HTTP 请求,然后尝试使用该数据,然后我收到以下错误:

GET http://localhost:5000/bloodRequest/amin@gmail.com 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我的客户端请求代码:

  useEffect(() => {
    fetch(`http://localhost:5000/bloodRequest/amin@gmail.com`)
      .then((res) => res.json())
      .then((data) => setRequests(data));   }, [requests]);

我的服务器端代码:

  app.get("/donateBlood/:email", async (req, res) => {
      const email = req.params.email;
      const query = { email: email };
      const cursor = donateBloodsCollection.find(query);
      const result = await cursor.toArray();
      res.json(result);
    });

但是,当我更改 HTTP 请求语法并在 HTTP 链接中间使用 email 时,它工作正常。 例子:

客户端代码:

 useEffect(() => {
    fetch(`http://localhost:5000/amin@gmail.com/bloodRequest`)
      .then((res) => res.json())
      .then((data) => setRequests(data));   }, [requests]);

服务器端代码:

app.get("/:email/donateBlood", async (req, res) => {
      const email = req.params.email;
      const query = { email: email };
      const cursor = donateBloodsCollection.find(query);
      const users = await cursor.toArray();
      res.json(users);
    });

在那种情况下,它可以正常工作,我不知道为什么? 你能解释一下吗?

The fetch call is calling a URL /bloodRequest/amin@gmail.com , the corresponding server API definition has /donateBlood/:email , so the 404 error you have got is expected.

GET http://localhost:5000/bloodRequest/amin@gmail.com 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Try either changing the client-side URL to /donateBlood/amin@gmail.com or server-side API to /bloodRequest/:email .

PS:基本上,您尝试的代码在语法上是有效的。 它一定是由于 URL 中的拼写错误或在特定更改后未重新启动服务器而失败。 我可以在您发布的工作代码中看到相同的 URL 不匹配,因此它也应该抛出 404。如果它还不起作用,请发布您尝试过的确切代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM