【发布时间】:2019-12-13 15:58:18
【问题描述】:
我试图从 index.html 进行一个简单的 api 调用,但无论我做什么,我都一直收到错误。
据我了解,发生 cors 错误是因为我正在调用不同的服务器,并且我必须在我的服务器中允许这样做。
自从我进行预检后,我读到我需要实现 app.option 以使其工作,但这仍然不起作用。
我试过 a) 设置一个 cors 中间件 b) 使用 npm cors 库 c) 设置 app.options(),如 here 中所回答的那样
我知道在使用 Fetch 时,您必须明确说明您选择的每个选项,但我似乎错过了所有选项。
我最终只是在我的服务器中调用 url 而不是获取我的服务器 /data rout 但是 我会很感激一些帮助正确配置它以供将来使用。
谢谢!
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.
在客户端使用 //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}!`))
【问题讨论】:
-
必须是
http://services.runescape.com才能通配原点。 -
the cors errors occur because I am making a call to a different server and I have to allow this in my serverNO 服务器被调用需要允许谁可以调用它。
标签: javascript node.js cors fetch