How can I add CORS-Headers to a static connect server?

前端 未结 4 826
庸人自扰
庸人自扰 2020-12-03 17:15

I am writing a little demo web server delivering static html,css and javascript. The server looks like

(function () {
    \"use strict\";

    var http = req         


        
4条回答
  •  清歌不尽
    2020-12-03 17:45

    express.static takes a configuration object. You can provide the property setHeaders and from that function you can set headers for the response:

        app.use(express.static('public', {
          setHeaders: function setHeaders(res, path, stat) {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Methods', 'GET');
            res.header('Access-Control-Allow-Headers', 'Content-Type');
          }
        }))
    

    The parameters to this function are:

    • res, the response object.
    • path, the file path that is being sent.
    • stat, the stat object of the file that is being sent.

    I wish that the request were available here so that I could conditionally set the CORS headers based upon the Origin header.

提交回复
热议问题