POST request response in custom database login script not JSON parseable

We wrote a Login and a Get User script for our custom database. While the Get User script is using request.get() to retrieve the user data from our API, the Login script is using a request.post() to get the user from our API with another endpoint.

I verified with curl that both endpoints return the exactly same JSON data:

{"user_id":11792,"nickname":"Norbert Schuler","email":"norbert.schuler@plant-for-the-planet.org","username":"norbert.schuler@plant-for-the-planet.org","email_verified":true,"user_metadata":{"locale":"de"},"app_metadata":{"type":"individual"}}

When debugging both scripts the log (console.log(body)) is showing that the Login script returns the JSON data in the body variable in a way that cannot be parsed (throwing a “SyntaxError: Unexpected token o in JSON at position 1” error when trying to run something like const user = JSON.parse(body);). The output of the debugger shows the following results.

For the Get User script:

[16:13:48.202Z]  INFO wt: new webtask request
[16:13:49.281Z]  INFO wt: {"user_id":11792,"nickname":"Norbert Schuler","email":"norbert.schuler@plant-for-the-planet.org","username":"norbert.schuler@plant-for-the-planet.org","email_verified":true,"user_metadata":{"locale":"de"},"app_metadata":{"type":"individual"}}
[16:13:49.284Z]  INFO wt: finished webtask request

For the Login script:

[16:20:36.951Z]  INFO wt: new webtask request
[16:20:38.222Z]  INFO wt: 
    {
      user_id: 11792,
      nickname: 'Norbert Schuler',
      email: 'norbert.schuler@plant-for-the-planet.org',
      username: 'norbert.schuler@plant-for-the-planet.org',
      email_verified: true,
      user_metadata: { locale: 'de' },
      app_metadata: { type: 'individual' }
    }
[16:20:38.223Z]  INFO wt: finished webtask request

Now why is the result of the request.post() different from request.get() and how can this be fixed to also get some JSON parsable string response?

how can this be fixed to also get some JSON parsable string response?

One is JSON notation as a serialized form, and the other JavaScript object constant notation.

Doing a JSON.stringify(body) should make it a parsable string, though it’s kind of unnecessary to do the JSON.parse() on it in the first place, cause in the end you’ll have a JSON.parse(JSON.stringify(body)), so in that case just go with const user = body instead, if I see it correctly.

2 Likes

Ok, so I just can use the answer of the post request directly as an object and can omit the JSON parsing. Thank you. I am just wondering, why the one request returns a string while the other returns an object, but that’s probably by their implementation.

Yep it’s probably by the implementation design.