How can I set response header on express.js assets

前端 未结 8 1913
孤独总比滥情好
孤独总比滥情好 2020-11-28 04:26

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?

相关标签:
8条回答
  • 2020-11-28 04:56

    Short Answer:

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

    • res.set - sets headers

    • res.headers - an alias to res.set

    0 讨论(0)
  • 2020-11-28 05:01

    There is at least one middleware on npm for handling CORS in Express: cors.

    0 讨论(0)
  • 2020-11-28 05:11

    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])
    
    0 讨论(0)
  • 2020-11-28 05:17

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

    var cors = require('cors')
    
    app.use(cors());
    
    0 讨论(0)
  • 2020-11-28 05:18

    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();
      });

    0 讨论(0)
  • 2020-11-28 05:21

    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();
        }
    };
    
    0 讨论(0)
提交回复
热议问题