How can I set response header on express.js assets

I need to set CORS to be enabled on scripts served by express. How can I set the headers in these returned responses for public/assets?


Solution 1:

There is at least one middleware on npm for handling CORS in Express: cors. [see @mscdex answer]

This is how to set custom response headers, from the ExpressJS DOC

res.set(field, [value])

Set header field to value

res.set('Content-Type', 'text/plain');

or pass an object to set multiple fields at once.

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  'ETag': '12345'
})

Aliased as

res.header(field, [value])

Solution 2:

This is so annoying.

Okay if anyone is still having issues or just doesn't want to add another library. All you have to do is place this middle ware line of code before your routes.

Cors Example

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', ['*']);
    res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.append('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// Express routes
app.get('/api/examples', (req, res)=> {...});

Solution 3:

You can do this by using cors. cors will handle your CORS response

var cors = require('cors')

app.use(cors());

Solution 4:

Short Answer:

  • res.setHeaders - calls the native Node.js method

  • res.set - sets headers

  • res.headers - an alias to res.set