Html 使用 HTML5 fetch API 允许 Access-Control-Allow-Origin 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36878255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow Access-Control-Allow-Origin header using HTML5 fetch API
提问by iNikkz
I am using HTML5 fetch API.
我正在使用 HTML5 获取 API。
var request = new Request('https://davidwalsh.name/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
I am able to use normal json but unable to fetch the data of above api url. It throws error:
我可以使用普通的 json 但无法获取上述 api url 的数据。它抛出错误:
Fetch API cannot load https://davidwalsh.name/demo/arsenal.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Fetch API 无法加载https://davidwalsh.name/demo/arsenal.json。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost'。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
回答by David Scales
Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):
就像 epascarello 所说,托管资源的服务器需要启用 CORS。您可以在客户端做的(可能是您正在考虑的)是将获取模式设置为 CORS(尽管这是我认为的默认设置):
fetch(request, {mode: 'cors'});
However this stillrequires the server to enable CORS as well, and allow your domain to request the resource.
但是,这仍然需要服务器也启用 CORS,并允许您的域请求资源。
Check out the CORS documentation, and this awesome Udacity videoexplaining the Same Origin Policy.
查看CORS 文档,以及解释同源政策的精彩 Udacity 视频。
You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>
):
您也可以在客户端使用 no-cors 模式,但这只会给您一个不透明的响应(您无法读取正文,但该响应仍然可以由服务工作者缓存或由某些 API 使用,例如<img>
) :
fetch(request, {mode: 'no-cors'})
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
回答by smsivaprakaash
I had my front-end code running in http://localhost:3000and my API(Backend code) running at http://localhost:5000
我的前端代码在http://localhost:3000 中运行,我的 API(后端代码)在 http://localhost:5000 中运行
Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.
正在使用 fetch API 来调用 API。最初,它抛出“cors”错误。然后在我的后端 API 代码中添加以下代码,允许来自任何地方的源和标头。
let allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Headers', "*");
next();
}
app.use(allowCrossDomain);
However you should restrict the you origins in case of other environments like stage, prod.
但是,在其他环境(如 stage、prod)的情况下,您应该限制您的来源。
回答by VigKam
This worked for me :
这对我有用:
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
我们要请求的具有 CORS 问题的 API 端点:
https://www.yourdomain.com/test/list
Start Proxy:
启动代理:
lcp --proxyUrl https://www.yourdomain.com
Proxy Active
Proxy Url: http://www.yourdomain.com:28080
Proxy Partial: proxy
PORT: 8010
Then in your client code, new API endpoint:
然后在您的客户端代码中,新的 API 端点:
http://localhost:8010/proxy/test/list
End result will be a request to https://www.yourdomain.ie/test/listwithout the CORS issues!
最终结果将是对https://www.yourdomain.ie/test/list的请求,而没有 CORS 问题!
回答by MattG
I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:
我知道这是一篇较旧的帖子,但我发现解决此错误的方法是使用我服务器的 IP 地址,而不是在我的提取请求中使用域名。例如:
#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
回答by Caliari
If you are use nginx try this
如果你使用 nginx 试试这个
#Control-Allow-Origin access
# Authorization headers aren't passed in CORS preflight (OPTIONS) calls. Always return a 200 for options.
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Allow-Origin "https://URL-WHERE-ORIGIN-FROM-HERE " always;
add_header Access-Control-Allow-Methods "GET,OPTIONS" always;
add_header Access-Control-Allow-Headers "x-csrf-token,authorization,content-type,accept,origin,x-requested-with,access-control-allow-origin" always;
if ($request_method = OPTIONS ) {
return 200;
}
回答by Ernersto Pastori
Look at https://expressjs.com/en/resources/middleware/cors.htmlYou have to use cors.
看https://expressjs.com/en/resources/middleware/cors.html你必须使用cors。
Install:
安装:
$ npm install cors
const cors = require('cors');
app.use(cors());
You have to put this code in your node server.
您必须将此代码放在您的节点服务器中。