gpt4 book ai didi

jquery - XmlHttpRequest 无法加载,因为它被 CORS 策略阻止 : No 'Access-Control-Allow-Origin' header is present on the requested resource

转载 作者:行者123 更新时间:2023-12-01 04:38:41 29 4
gpt4 key购买 nike

如何创建原始 header ,使其适用于所有设备上的所有域和浏览器?我是否使用某种回调?我应该把它放在我的代码中的什么位置?

var characters = [

"http://www.anapioficeandfire.com/api/characters/148",
"http://www.anapioficeandfire.com/api/characters/823",
"http://www.anapioficeandfire.com/api/characters/1052",
"http://www.anapioficeandfire.com/api/characters/1303",
"http://www.anapioficeandfire.com/api/characters/208",

];



$(".btn").click(clickButton);


function clickButton(e) {

e.preventDefault();

var i = $(this).attr("data-id");
console.log(characters[i]);

var data;

$.getJSON(characters[i], function(json) {
data = json;

)};

最佳答案

如果您尝试通过 HTTPS 而不是 HTTP 调用 API,它将起作用(我现在就尝试过)。

您收到该错误消息是因为服务器正在发送重定向响应(HTTP/1.1 301 .. 请参阅Location header ),而没有 CORS header 。正如您在这里看到的:

 $ curl -v http://www.anapioficeandfire.com/api/characters/148 *   Trying 104.27.137.190... * TCP_NODELAY set * Connected to www.anapioficeandfire.com (104.27.137.190) port 80 (#0) GET /api/characters/148 HTTP/1.1 Host: www.anapioficeandfire.com User-Agent: curl/7.51.0 Accept: */*  HTTP/1.1 301 Moved Permanently Date: Sun, 21 May 2017 21:43:13 GMT Transfer-Encoding: chunked Connection: keep-alive Set-Cookie: __cfduid=d59cc58d4e217f93147944a7f5ae1b6231495402993; expires=Mon, 21-May-18 21:43:13 GMT; path=/; domain=.anapioficeandfire.com; HttpOnly Cache-Control: max-age=3600 Expires: Sun, 21 May 2017 22:43:13 GMT Location: https://www.anapioficeandfire.com/api/characters/148 Server: cloudflare-nginx CF-RAY: 362ab5c495ec42fe-MXP

The browser is then blocking the second request ( the one that would actually follow the redirect ) for that reason.

You can dig a little bit deeper into what CORS actually is here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Code Example

$.getJSON('https://www.anapioficeandfire.com/api/characters/148', function (json) {
$('#api-response').text(JSON.stringify(json,null,4));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre id="api-response"></pre>

我建议您阅读更多有关 HTTP、Ajax 和 Javascript 的内容,以便更好地了解正在发生的事情。这是非常基本的东西。

关于jquery - XmlHttpRequest 无法加载,因为它被 CORS 策略阻止 : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101798/

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