I would like to have headers accompany the json object that I send over. When I try to setHeaders
, I get a Can't set headers after they are sent.
error.
I see in this SO post that
Since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format.
However, when I do res.status(404).json({"error", "message not found"})
no headers (the http status)accompany the json object that gets sent to the client. All the client sees is:
{
"error:": "Message Not Found"
}
Web service:
var express = require('express');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var app = express();
var message_dict = [];
app.set('json spaces', 40);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.json());
app.post('/messages', function(request, response){
var string_message = request.body.message;
var json_obj = request.body
var hash_key = crypto.createHash('sha256').update(string_message).digest('hex');
message_dict[hash_key] = json_obj
var encrypted_data = {'digest' : hash_key};
response.json(encrypted_data);
});
app.get('/messages/*', function(request, response) {
var hash_key = request.params[0];
if(hash_key in message_dict){
response.json(message_dict[hash_key]);
}
else{
response.status(404).json({'error:' : 'Messag Not Found'})
}
});
app.listen(8080, function() {
console.log('Example app listening on port 8080!');
});
I think you're confusing response headers and response body, .json()
sets the correct response headers (specifically Content-Type
), the response body is still only the param you pass into the call.
Is there a specific reason you want the response headers to appear in the response body? response headers are usually of very little use to the requester and can be easily accessed by when getting the response from the server (res.headers
property).
To actually answer your question (not sure why you would do that):
var json = {'error:' : 'Messag Not Found'}
response.type('application/json')
response.writeHead(404)
json.headers = response._header; // _header not documented but works
response.end(JSON.stringify(json));