“否”访问控制允许原因“报头存在于所请求的资源” [英] "No 'Access-Control-Allow-Origin' header is present on the requested resource"

查看:1519
本文介绍了“否”访问控制允许原因“报头存在于所请求的资源”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 JavaScript 通过连接到可疑 API 内置 Flask

I am trying to do authorization using JavaScript by connecting to the RESTful API built in 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或远程资源必须设置头,但为什么它工作, Chrome扩展程序POSTMAN中的授权?

I know that the API or remote resource must set the header, but why did it work when I tested authorization in 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);
    });


推荐答案

如果我理解它, href =http://en.wikipedia.org/wiki/XMLHttpRequest> 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.

这篇关于“否”访问控制允许原因“报头存在于所请求的资源”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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