How to correctly configure server and browser to avoid cors errors? Fetch API + Node.js

前端 未结 1 1118
长情又很酷
长情又很酷 2021-01-21 15:34

I was trying to make a simple api call from index.html but I kept getting an error no matter what I did.

From my understanding, the cors errors occur because I am making

相关标签:
1条回答
  • 2021-01-21 16:16

    Edit: OP has changed the question based on the answer - but for no avail.

    You don't have to set CORS headers manually if you use the cors library.

    var cors = require('cors');
    
    
    app.options('*', cors()); // Enable preflight by using this middle ware before any other route. 
    app.use(cors());
    

    And if the CORS should be enabled for a white list of domains, use the following options:

    var whitelist = ['http://example1.com', 'http://example2.com']
    var corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题