Skip to content
Advertisement

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

Hi guys there have been an error in my site for quite long and I have searched whole internet for the answers but didn’t found any solutions here is my onsubmit code

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));
  };

Also i have checked the response of the network tab it says success but getting this error don’t know how to get rid of it. I have also checked the solution of the Stackoverflow that write Accept:application/json but still didn’t worked,but it gives me “bad request” error The backend code is:

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");
  }
});
 

I have also tested it through Postman it works successfully on it with no errors. This the json server. enter image description here

Advertisement

Answer

This happens when you make a request to the server and parse the response as JSON, but it’s not JSON.

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

The actual request worked fine. It got a response. But the res.json() is what failed.

The root cause is that the server returned HTML or some other non-JSON string.

You can try changing res.json() to 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));
  };
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement