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

标签 javascript jquery cors postman same-origin-policy

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/40335759/

相关文章:

javascript - 如何将数据从 Spring Controller 发送到 AngularJS Controller 并响应数据

javascript - 图像 slider 悬停停止和动画过渡

javascript - 我想知道如何将 iMacros 发送到某行

javascript - 请求刷新页面

javascript - 匹配字符串中模式的多个实例

javascript - IE 不对单引号/撇号进行 url 编码

php - 使用 PHP 生成嵌套 ul 列表的问题

javascript - 在 Werkzeug 异常上设置标题

Angular 2 : Response to preflight request doesn't pass access control check

ruby-on-rails - 在 Ruby on Rails 中允许 CORS