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?
10 Answers
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])

- 10,821
- 5
- 34
- 49
-
2How can I get these values? Because I set these values in `res` object. When I try to see this content I go undefined using `res.headers`; – Bruno Casali May 05 '16 at 17:33
-
Then I use `res.write('content')`? – George Jul 13 '16 at 20:11
-
1This line be should be used before writing the head. – Virendra Singh Rathore Nov 09 '16 at 16:05
-
For some reason `res.set` didn't work for me, but the `cors` middleware did the trick just right. – Cezar D. Jun 28 '17 at 02:31
-
@BrunoCasali extra headers are blocked by browser by default, see https://stackoverflow.com/a/37931084/1507207 – sbk201 Jan 14 '20 at 06:31
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)=> {...});

- 6,235
- 11
- 49
- 67
-
2Important this point relative to the order. I was wondering if really it was important as I saw different behaviours when changing it. Nice. Thanks – Alejandro Teixeira Muñoz Apr 15 '20 at 09:39
-
3Nice: solved the problem perfectly. Adding an entire dependency to perform these 6 lines of code is not a road that I would recommend for anyone... – Alex Clark Jun 09 '20 at 12:51
You can do this by using cors. cors will handle your CORS response
var cors = require('cors')
app.use(cors());

- 12,158
- 7
- 41
- 68

- 365
- 4
- 7
@klode's answer is right.
However, you are supposed to set another response header to make your header accessible to others.
Example:
First, you add 'page-size' in response header
response.set('page-size', 20);
Then, all you need to do is expose your header
response.set('Access-Control-Expose-Headers', 'page-size')

- 157
- 1
- 5
-
1I was stuck for over an hour trying to figure out why none of my custom headers were making it to the other end. Exposing them was the answer. Thank you so much! Why this header has zero mention in the Express docs (or in any articles I've read thus far about custom headers) is very puzzling. – Devin Spikowski Jan 31 '18 at 12:07
-
2What if you had 2 headers? Like this: ```javascript res.set("...","..."); res.set("...","...."); ``` Now how do you expose those 2 headers? – Cursor Jan 01 '20 at 02:07
-
3I discovered how reading the docs: ```javascript Access-Control-Expose-Headers: * // or Access-Control-Expose-Headers:
, – Cursor Jan 01 '20 at 02:08, ... ```
service.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});

- 111
- 1
- 2
You can also add a middleware to add CORS headers, something like this would work:
/**
* Adds CORS headers to the response
*
* {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
* {@link http://expressjs.com/en/4x/api.html#res.set}
* @param {object} request the Request object
* @param {object} response the Response object
* @param {function} next function to continue execution
* @returns {void}
* @example
* <code>
* const express = require('express');
* const corsHeaders = require('./middleware/cors-headers');
*
* const app = express();
* app.use(corsHeaders);
* </code>
*/
module.exports = (request, response, next) => {
// http://expressjs.com/en/4x/api.html#res.set
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type,Authorization'
});
// intercept OPTIONS method
if(request.method === 'OPTIONS') {
response.send(200);
} else {
next();
}
};

- 4,929
- 1
- 33
- 25
First add 'field' in response header
response.set('field', 'value');
Then you need to do is expose your header
response.set('Access-Control-Expose-Headers', 'field')

- 71
- 1
- 5
With the latest version of the express.js 4.18.2:
If you are using static
middleware, and want to change the response header, you should:
app.use(express.static('./', {
setHeaders: function(res) {
res.set("Content-Security-Policy", "default-src 'self'");
}
}));

- 10,701
- 3
- 19
- 20