ewok
ewok

Reputation: 21503

NodeJS Express: json not being included in response

I've written a super simple server that takes POST requests with a name, and writes the name to a file, GETs return all the names, and DELETEs delete the name file. My problem is in the DELETE method. When I send a 205 to indicate that the names file was deleted, the JSON is being included in the response, but when I send the 204, indicating that no file exists to delete, the response comes back empty.

Here's the method defining the behavior:

function clearNames(req, res) {
    fs.unlink('names.txt', function(err){
        if (err) {
            res.status(204).json({'success': true});
        } else {
            res.status(205).json({'success': true});
        }
    });
}

and here's the result. The first request is sent when a name file exists, and deletes the file. The second is sent after the file is deleted, so no file exists to delete:

$ curl -X DELETE -w ' %{http_code}' http://localhost:18080/api/names 
{"success":true} 205
$ curl -X DELETE -w ' %{http_code}' http://localhost:18080/api/names 
 204
$

Upvotes: 0

Views: 908

Answers (1)

Olli K
Olli K

Reputation: 1760

In the error-case you're sending a status 204, which means "No content", and thus the client doesn't expect any content after that. Change the status to something that would include a response body and it should work.

Quote from the specs:

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

A 205 status shouldn't also include a body, so I suggest you change it as well.

Upvotes: 1

Related Questions