简体   繁体   中英

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, GET s return all the names, and DELETE s 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
$

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM