0

I have created a little API using node.js, express and mysql. It's returning the json as expected. Now I would like to set the header .setHeader('Content-Type', 'application/json') too.

How do I need to alter this part to do so?

Working:

...
module.exports = app;
var server = http.createServer(app);
server.listen(4001);

Attempts (Not working):

...
module.exports = app;
//var server = http.createServer(app);
var server = http.createServer(function(req,res){
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.send(app);
      res.end();
});
server.listen(4001);

Found my mistake. Had to use:

res.json({"status": 200, "error": error, "response": null});

instead of

res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
8
  • try res.json({app}); Commented Feb 20, 2018 at 17:47
  • Unfortunately didn't work. Getting 'TypeError: res.json is not a function' and nodemon says 'app crashed' Commented Feb 20, 2018 at 17:50
  • 1
    wait, you are not using express? Commented Feb 20, 2018 at 17:51
  • Yes, I am using express ... Commented Feb 20, 2018 at 17:52
  • looks like you are doing using only HTTP module. app is your express object ? Commented Feb 20, 2018 at 17:52

1 Answer 1

0

Booth for setHeader and .json is not supported in same response. You need use only .json() for json rest api outputs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.