我有
react应用程序尝试使用whatwg-fetch从其余的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)...
Run Code Online (Sandbox Code Playgroud)
但我说不能得到任何数据
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.
Run Code Online (Sandbox Code Playgroud)
当我尝试使用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
Run Code Online (Sandbox Code Playgroud)
和响应头(来自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
Run Code Online (Sandbox Code Playgroud)
通过@CrossOrigin在弹簧启动应用程序中启用Cors
在此先感谢最好的问候
您似乎正在尝试从一个域https://foo.bar访问另一个域https://myrest.api,这就是该错误的原因。
您有 2 个选择:
1) 将这 2 个应用程序合并到 Heruko 上的一个域中,例如,React 和 Api 应用程序将位于https://foo.bar域下,这将适合您。
2)通过将“Access-Control-Allow-Origin”标头添加到api 应用程序中,允许https://foo.bar的客户端应用程序域访问https://myrest.api 的api 域:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4885 次 |
| 最近记录: |