没有"Access-Control-Allow-Origin"客户端修复 [英] No 'Access-Control-Allow-Origin' client side fix

查看:135
本文介绍了没有"Access-Control-Allow-Origin"客户端修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过suredbits从 API中获取免费的NFL数据.不幸的是,他们没有在标题中添加Access-Control-Allow-Origin,这会导致CORS问题.当我尝试运行这样的代码时...

I am trying to get free NFL data from an API by suredbits. Unfortunately, in their header, they have not added Access-Control-Allow-Origin, which creates a CORS issue. When I try and run code like this...

$.getJSON("http://api.suredbits.com/nfl/v0/stats/jones/julio", function(playerData) {
      alert(playerdata); 
}

我不断收到此错误No 'Access-Control-Allow-Origin' header is present on the requested resource.

因此,从根本上说,他们有什么办法可以通过客户端来纠正错误?

So basically, is their any way to fix their mistake through the client side?

推荐答案

实际上有一种从客户端进行修复的方法:将请求URL更改为https://cors-anywhere.herokuapp.com/http://api.suredbits.com/nfl/v0/stats/jones/julio:

There is actually a way to fix it from client side: by changing the request URL to https://cors-anywhere.herokuapp.com/http://api.suredbits.com/nfl/v0/stats/jones/julio:

const proxyURL = "https://cors-anywhere.herokuapp.com/";
const requestURL = "http://api.suredbits.com/nfl/v0/stats/jones/julio";
$.getJSON(proxyURL + requestURL, function(playerData) {
  console.log(playerData);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

是的,并不是完全从客户端修复它-因为它的实际作用是,导致请求通过

Yeah, that’s not exactly fixing it from the client side—since what it’s actually doing is, causing the request to get made through https://cors-anywhere.herokuapp.com/, which is an open CORS proxy that just adds the Access-Control-Allow-Origin response header so that browsers will allow your frontend JavaScript code to access the response.

但是正如答案中的代码段所示,它绝对不需要对托管您要从中获取数据的API终结点的服务器进行任何更改.相反,所有这些都需要对您自己的前端代码进行小改动.

But as demonstrated in the code snippet in the answer, it definitely doesn’t require any changes to the server hosting the API endpoint you want to get data from. Instead all it requires a trivial change to your own frontend code.

当然,在所有情况下,依靠这样的公共开放代理并不是正确的解决方案.但是,至少在API提供程序尚未启用CORS启用其API以便您可以直接向其发送请求并获得可以使用的响应的情况下,这是一个很好的解决方案.

Of course relying on a public open proxy like this is not the right solution in all cases. But at least it’s a good solution in the case where the API provider just hasn’t gotten around to CORS-enabling their API so that you could send requests to it directly and get responses you can use.

如何使用CORS代理解决 有更多详细信息.

The How to use a CORS proxy to get around "No Access-Control-Allow-Origin header" problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API has a few more details.

这篇关于没有"Access-Control-Allow-Origin"客户端修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆