Minor API Action issue on NodeJS and crap API endpoint

Wappler Version : v5.x
Operating System : N/A
Server Model: NodeJS
Database Type: N/A
Hosting Type: N/A

Situation

@jellederijke has to perform an API Action to a third-party API, that answers an HTTP 200 OK status code and Content-Type application/json, however, the response body is empty.

Actual behavior

Error is logged to console due to failure to decode JSON due to empty body. Error is logged, NOT THROWN:

if (res.headers['content-type'] && res.headers['content-type'].includes('json')) {
    try {
        body = JSON.parse(body);
    } catch (e) {
        console.error(e);
    }
}

Desired behaviour:

If response body is empty, do not attempt to JSON decode, even if Content-Type application/json is set (see modified 1st line):

if (res.headers['content-type'] && res.headers['content-type'].includes('json') && body) {
    try {
        body = JSON.parse(body);
    } catch (e) {
        console.error(e);
    }
}

Additionally, instead of logging error to console, THROW the error.

2 Likes

Yes, thank you @Apple. The error logged is:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/opt/node_app/lib/modules/api.js:97:41)
    at IncomingMessage.emit (node:events:525:35)
    at IncomingMessage.emit (node:domain:489:12)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

and the relevant file is

lib/modules/api.js
1 Like

We log the error since we expected a json response, we do not throw the error and instead go further with the raw body of the response. This is done because not all API behave correctly, sending the incorrect content-type headers or wrong status code. There is a status code 204 for when you response with no content 204 No Content.

I can remove the console logging, it is only there for debugging when it fails. The api call should still be successful and the body in your case would be empty as expected. You are correct that we probably could just skip the parse if there is no body, it does try the parsing due to the headers telling him it is a json content.

Ok, don’t worry about the console logging, it can stay like that, you can just change the if condition. The error in this scenario won’t be logged with the if condition fix

In this case the api-enpoint is all put and post endpoints by AFAS. Which is quite a big company. So I doubt they will quicly change this from a 200 to a 204. Would be great if the if (pun intended) condition could be edited. :grin: