molecule
molecule

Reputation: 1121

Can't set headers after they are sent. in express js

I am using express package of nodejs and I have written this function to send response for any generic API. Although it keeps giving error and I can't figure out why. status function sets response status so I don't know why this should happen

function ResponseHandler(response, respObj, resData) {

  var resp = {
    "message" : respObj.message,
    "data" : resData
  }

  response.status(respObj.code);
  response.json(resp);
}

Upvotes: 2

Views: 4265

Answers (3)

Jay Thakkar
Jay Thakkar

Reputation: 51

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Upvotes: 1

Pankaj kumar Panigrahi
Pankaj kumar Panigrahi

Reputation: 761

You should use the below format:

res.status(500).json({ error: 'message' });

Check the following link to know more details: https://expressjs.com/en/api.html

Upvotes: 1

R. Gulbrandsen
R. Gulbrandsen

Reputation: 3778

This is because you're sending the request back with the .status(number) and then try to send the status again with .json(string). Chain your functions and only one response will be sent.

response.status(respObj.code).json(resp);

Upvotes: 2

Related Questions