gpt4 book ai didi

javascript - 为什么我的 JavaScript 代码收到“"No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?

转载 作者:行者123 更新时间:2023-12-01 01:40:42 30 4
gpt4 key购买 nike

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.

Please stop posting:

  • CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.
  • 3rd party services that allow a request to circumvent CORS
  • Command line options for turning off CORS for various browsers
<小时/>

我正在尝试使用 JavaScript 进行授权通过连接到 RESTful API内置Flask 。但是,当我发出请求时,出现以下错误:

XMLHttpRequest cannot load http://myApiUrl/login. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.

我知道 API 或远程资源必须设置 header ,但为什么当我通过 Chrome 扩展 Postman 发出请求时它会起作用? ?

这是请求代码:

$.ajax({
type: 'POST',
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain: true,
xhrFields: {
withCredentials: true,
},
})
.done(function (data) {
console.log('done');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});

最佳答案

如果我理解正确的话,你正在做 XMLHttpRequest到与您的页面所在的域不同的域。因此,浏览器会阻止它,因为出于安全原因,它通常允许同一来源的请求。当您想要进行跨域请求时,您需要做一些不同的事情。

当您使用 Postman 时,它们不受此政策的限制。引自 Cross-Origin XMLHttpRequest :

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

关于javascript - 为什么我的 JavaScript 代码收到“"No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143995/

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