How can I set response header on express.js assets

前端 未结 8 1914
孤独总比滥情好
孤独总比滥情好 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 05:22

    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)=> {...});
    
    0 讨论(0)
  • 2020-11-28 05:22

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