Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js - How to set a header to all responses

I am using Express for web services and I need the responses to be encoded in utf-8.

I know I can do the following to each response:

response.setHeader('charset', 'utf-8'); 

Is there a clean way to set a header or a charset for all responses sent by the express application?

like image 228
znat Avatar asked Jul 27 '15 19:07

znat


People also ask

Which node JS method set a header to the response?

setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced.

Can Express handle multiple requests?

Express. js use different kinds of middleware functions in order to complete the different requests made by the client for e.g. client can make get, put, post, and delete requests these requests can easily handle by these middleware functions.


1 Answers

Just use a middleware statement that executes for all routes:

// a middleware with no mount path; gets executed for every request to the app app.use(function(req, res, next) {   res.setHeader('charset', 'utf-8')   next(); }); 

And, make sure this is registered before any routes that you want it to apply to:

app.use(...); app.get('/index.html', ...); 

Express middleware documentation here.

like image 74
jfriend00 Avatar answered Sep 26 '22 00:09

jfriend00