为什么邮递员没有收到“所请求的资源上没有'Access-Control-Allow-Origin'标头”我的JavaScript代码出现错误? [英] Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does?

查看:192
本文介绍了为什么邮递员没有收到“所请求的资源上没有'Access-Control-Allow-Origin'标头”我的JavaScript代码出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


修改说明:这个问题是关于为什么Postman不受XMLHttpRequest一样的CORS限制。此问题不是,有关如何解决无'Access-Control-Allow-Origin'...错误。

Mod note: This question is about why Postman is not subject to CORS restrictions in the same way an XMLHttpRequest is. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error.

请停止发布


  • 在阳光下每种语言/框架的CORS配置。而是查找有关语言/框架的问题
  • >
  • 允许请求绕过CORS的第三方服务

  • 用于关闭各种浏览器的CORS的命令行选项






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


I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:


XMLHttpRequest无法加载 http:// myApiUrl / login 。所请求的资源上没有 Access-Control-Allow-Origin标头。因此不允许访问原始'null'。

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或远程资源必须设置标头,但为什么这样做通过Chrome扩展程序邮递员

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension 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 到与您的页面所在的域不同的域。因此,由于安全原因,浏览器通常会阻止来自同一来源的请求,因此阻止了它。当您想进行跨域请求时,需要做一些不同的事情。有关如何实现此目标的教程是 使用CORS

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

使用邮递员时,它们不受此政策的限制。引用自 跨域XMLHttpRequest

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:


常规网页可以使用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.

这篇关于为什么邮递员没有收到“所请求的资源上没有'Access-Control-Allow-Origin'标头”我的JavaScript代码出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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