be-codified
be-codified

Reputation: 6124

Express/node.js 204 HTTP code response issue

Here is my code:

.put(function(req, res) {
  User.findById(req.params.user_id, function(err, user) {
    if(err) return res.send(err);

    user.dateEdited = new Date();
    user.save(function(err) {
      if(err) return res.send(err);

      return res.status(204).json(customHTTPcodeReponses.updated(user))
    });
  });
});      

Part of my middleware called customHTTPcodeReponses

updated: function(data) {
  return {
    code: 204,
    status: 'Success',
    message: 'Resource updated (or soft deleted)',
    data: data
  };
}

I as figured out, 204 is not supposed to return any data, so I am not getting any back. But I would like to have this data to see what was really changed. How could I hande response code then?

Have in mind that if I use

res.status(200).json(customHTTPcodeReponses.updated(user))

data is shown.

If you need some extra explanation, please ask.

Upvotes: 5

Views: 18956

Answers (3)

Rajesh Kumar Yadav
Rajesh Kumar Yadav

Reputation: 1

yes if you have to send response message the use 200 or you can also use 404 because of 204 return no message in body

Upvotes: 0

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

yes, you are correct. This http status not allowed messages because it means "No Content". If you send content, use other statuses. For details look at document: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. There is part: "The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields."

If you want to send not content but metadata with addictional info, in this document there is part : "The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.". I think it is formal answer for your question.

If you not so formal, use status '200' with metadata as content.

edit: to send data in header :

res.header(field, [value])

Upvotes: 10

ivoszz
ivoszz

Reputation: 4478

It is simple. If you need some data back, just use return code 200 and return that data. If you don't need send back any data, use 204. You can set header with 204 to indicate operation status or url like Location with return code 201, but I am not sure this is a good idea.

Upvotes: 1

Related Questions