javascript - VM1661 :1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

标签 javascript reactjs express

大家好,我的网站长期以来一直存在错误,我在整个互联网上搜索了答案,但没有找到任何解决方案,这是我的onsubmit 代码

onSubmit = () => {
    fetch("http://localhost:2000/signin", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: this.state.signinEmail,
        password: this.state.signinPassword,
      }),
    })
      .then((response) => response.json())
      .then(console.log(this.state.signinEmail, this.state.signinPassword))
      .then((data) => console.log(data));
  };

我还检查了网络选项卡的响应,它说成功,但收到此错误不知道如何摆脱它。我也检查了解决方案 写 Accept:application/json 但仍然没有用的 Stackoverflow,但它给了我“错误的请求”错误 后台代码为:

app.post("/signin", (req, res) => {
  if (
    req.body.email === database.users[0].email &&
    req.body.password === database.users[0].password
  ) {
    res.send("success");
  } else {
    res.status(400).json("error logging in");
  }
});
 

我还通过 Postman 对其进行了测试,它可以成功运行,没有任何错误。 这是 json 服务器。 enter image description here

最佳答案

当您向服务器发出请求并将响应解析为 JSON,但它不是 JSON 时,就会发生这种情况。

fetch('/url').then(res => res.json())

实际请求运行良好。它得到了回应。但是 res.json() 失败了。

根本原因是服务器返回了 HTML 或其他一些非 JSON 字符串。

您可以尝试将 res.json() 更改为 res.text()

onSubmit = () => {
    fetch("http://localhost:2000/signin", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: this.state.signinEmail,
        password: this.state.signinPassword,
      }),
    })
      .then((response) => response.text())
      .then((data) => console.log(data));
  };

关于javascript - VM1661 :1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67252514/

相关文章:

Javascript 警报数组/对象值

javascript - D3.js 使用外部数据强制布局图空白

javascript - DOM 更改时触发一次事件

javascript - 我可以检查什么来确保 Angular 已完成加载并可以使用

reactjs - iOS DatePicker 在 React Native 中不显示

node.js - jade能在不刷新页面的情况下显示新的值吗?

node.js - 查询 MongoDB 嵌套字段

javascript - 为什么按钮在这里不采用父级的全尺寸?

reactjs - Jest/Enzyme document.createRange 不是挂载函数

javascript - 无法从另一台电脑查看局域网上的 React 应用程序