简体   繁体   English

如何正确配置服务器和浏览器以避免cors错误? 获取 API + Node.js

[英]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.我试图从 index.html 进行一个简单的 api 调用,但无论我做什么,我都不断收到错误消息。

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.根据我的理解,cors 错误的发生是因为我正在调用不同的服务器,我必须在我的服务器中允许它。

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.由于我正在进行预检,我读到我需要实现 app.option 以使其工作,但这仍然不起作用。

I tried a) Setting a cors middleware b) using npm cors library c) setting app.options(), as answered in here我试过 a) 设置 cors 中间件 b) 使用 npm cors 库 c) 设置 app.options(),如这里所回答

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.我知道在使用 Fetch 时,您必须明确选择您选择的每个选项,但我似乎错过了所有选项。

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.我最终只是在我的服务器中调用了 url,而不是获取我的服务器 /data 路由,但我希望得到一些帮助以正确配置它以备将来使用。

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在客户端使用 //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 //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.编辑:OP 已根据答案更改了问题 - 但无济于事。

You don't have to set CORS headers manually if you use the cors library.如果您使用 cors 库,则不必手动设置 CORS 标头。

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:如果应为域白名单启用 CORS,请使用以下选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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