简体   繁体   中英

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

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}!`))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM