Node.js and Express – Setting Content-Type for all Responses

If you’re using Express and Node.js to create an API, it’s likely you’ll want all of the responses to be of a single type, probably JSON. This is easily accomplished by adding a few routes that catch every request, set the content type, and then calling next() to pass the request to the next handler.

// GET
app.get(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// POST
app.post(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// PUT
app.put(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// DELETE
app.delete(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

Since Express evaluates routes in the order they are added, these will have to be defined before the more specific ones. In this example, every request made to the application will first be caught by these handlers and then passed on using the next() function.

Another way to accomplish this is by providing some custom middleware. The use function defines a function that will be called in the process of completing a request. This will need to be executed before the routes are defined.

app.use(function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

In this example, every request that comes into Express will pass through this function. We have to the ability to do whatever we want with it before continuing. In this case, setting the content type.

Leave a Reply

Your email address will not be published. Required fields are marked *