javascriptnode.jsexpress

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

  • There is at least one middleware on npm for handling CORS in Express: cors (see mscdex's answer).

    This is how to set custom response headers, from the Express docs:

    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])