Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected token O in JSON at position 0 when I query an API

I know that the question is findable on the forum but no answer works for me. I have an angular service that calls a nodeJS API like this:

Angular service

public createUser(pUser: User): Observable<User> {
    var url = "http://localhost:5000/users";
    var json = JSON.stringify(pUser)
    return this.http.post<User>(url, pUser)
  }

NodeJS API

router.post('/', (req, res) => {
    console.log(req.body)
    User.create({ email: req.body.email, password: req.body.password })
    res.sendStatus(200);
});

The API is well called, the insertion into database works, but I have this message in the browser:

SyntaxError: Unexpected token O in JSON at position 0

The status of the request is 200 on return but the error is still present in the browser

I do not know if the problem comes from the front end or the backend.

After doing some research, I try to parse my object before sending it. I try to stringify too.

Without success

Is this someone would have the solution? thank you very much

like image 273
ChillAndCode Avatar asked Jan 01 '23 12:01

ChillAndCode


1 Answers

This error occurs when you try to parse invalid JSON.

Due to the default response type for angular is JSON and the default response of code 200 is 'OK'. You have to adapt one of them.

You can change the response type to text like this:

this.http.post<User>(url, pUser, {responseType: 'text'});

Or you return a JSON object:

res.status(200).send({ status: 'OK'});
like image 179
Norbert Bartko Avatar answered Jan 03 '23 02:01

Norbert Bartko