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

走远了吗. 提交于 2020-03-16 07:04:47

问题


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 a call to a different server and I have to allow this in my server.

Since I was getting preflight I read that I needed to implement app.option to allow it to work but this still doesn't work.

I tried a) Setting a cors middleware b) using npm cors library c) setting app.options(), as answered in here

I know that when using Fetch you have to be explicit about every option you choose but I seem to be missing all of them.

I ended up just calling the url in my server than fetching my server /data rout but I would appreciate some help configuring it correctly for future use.

Thank you!

Access to fetch at 'http://services.runescape.com/m=itemdb_oldschool/api/graph/4151.json' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

Using on client //index.html

    <script>
      fetch('http://services.runescape.com/m=itemdb_oldschool/api/graph/4151.json')
      .then(response => response.json())
      .then(res => console.log(res))
    </script>

//server.js

const express = require('express')
const app = express()
const path = require('path');
const rp = require('request-promise')


const port = 3002
var cors = require('cors')
app.use(cors())
app.options('*', cors()); 
app.get('/', async (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
});

});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))


回答1:


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'))
    }
  }
}


来源:https://stackoverflow.com/questions/57370253/how-to-correctly-configure-server-and-browser-to-avoid-cors-errors-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!