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

相关文章:

javascript - 如何使用QWebEngineView和qtwebchannel.js一步步加载javascript?

javascript - 为什么我的代码在间隔完成之前没有运行?

javascript - 更改选定链接的颜色

javascript - AngularJS withCredentials 不发送

java - 与 Servlet Filter 和 FilterRegistrationBean 一起使用时,跨源资源共享不起作用

javascript - CORS:访问控制允许来源不等于提供的来源

javascript - 是否有任何 Javascript 功能可以让您检查元素是否已关闭?

javascript - 提交表单数据时设置标题

javascript - 对每条条件语句进行分组

jquery - 等待 JSON 数据被解析