Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

javascript - 为什么我的JavaScript代码没有Postman时出现“在请求的资源上没有'Access-Control-Allow-Origin'标头”错误?(Why does my JavaScript code get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?)

I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask .

(我试图通过连接到Flask内置的RESTful API来使用JavaScript进行授权。)

However, when I make the request, I get the following error:

(但是,当我发出请求时,出现以下错误:)

XMLHttpRequest cannot load http://myApiUrl/login .

(XMLHttpRequest无法加载http:// myApiUrl / login 。)

No 'Access-Control-Allow-Origin' header is present on the requested resource.

(所请求的资源上没有“ Access-Control-Allow-Origin”标头。)

Origin 'null' is therefore not allowed access.

(因此,不允许访问原始“空”。)

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 ?

(我知道API或远程资源必须设置标头,但是当我通过Chrome扩展程序Postman发出请求时,为什么它可以工作?)

This is the request code:

(这是请求代码:)

$.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);
    });
  ask by Mr Jedi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on.

(如果我理解正确,那么您正在向页面所在的其他域执行XMLHttpRequest 。)

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 .

(有关如何实现此目标的教程是使用CORS 。)

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.

(常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但是它们受同一原始策略的限制。)

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.

(扩展可以在其起源之外与远程服务器通信,只要它首先请求跨域许可。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...