gpt4 book ai didi

node.js - 获取 API 无法加载...没有 'Access-Control-Allow-Origin' header

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:45 25 4
gpt4 key购买 nike

我得到了

  • 部署在 heroku 上的 rest api
  • 部署在 heroku 上的 React 应用

React 应用尝试使用 whatwg-fetch 从 rest api 获取数据。

var header = {"Content-Type": "multipart/form-data", 'Origin': 'https://foo.bar', 'Access-Control-Request-Method': 'GET', 'Access-Control-Request-Headers': 'X-Requested-With'};
var options = {method: 'GET', credentials: 'include', headers: header};
fetch('https://myrest.api/foo', options)...

但是我无法得到任何数据,它说是

Fetch API cannot load https://foo.bar. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://foo.bar' is therefore not allowed access.
The response had HTTP status code 403.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

当我尝试使用 curl 获取数据时,它起作用了

curl -H "Origin: https://foo.bar" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X GET --verbose https://myrest.api/foo -D header.txt

和响应 header (来自 curl 命令)

HTTP/1.1 200 
Server: Cowboy
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar
Vary: Origin
Access-Control-Allow-Credentials: true
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 09 Dec 2016 23:52:57 GMT
Via: 1.1 vegur

通过 @CrossOrigin 在 spring boot 应用程序中启用了 Cors

提前致谢最好的问候

最佳答案

您似乎正试图从一个域访问 https://foo.bar进入另一个域 https://myrest.api这就是该错误的原因。

你有两个选择:

1) 将这 2 个应用程序合并到 Heruko 上的一个域中,React 和 Api 应用程序将在 https://foo.bar 下例如域名,这将适合您。

2) 允许位于 https://foo.bar 的客户端应用域在 https://myrest.api 访问您的 api 域通过将“Access-Control-Allow-Origin” header 添加到 api 应用程序中:

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});

关于node.js - 获取 API 无法加载...没有 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41070674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com