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!');
});