Cross domain request with header authentication

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

I need to send a Get request with cross domain origin with header authentication.

Its working fine in Chrome and Firefox, but I'm having issues in Safari and IE. Also in random cases it returns 401.

<script> var url = 'username:password@anotherdomain.com'; $.ajax({     url: url,     dataType: 'jsonp',     jsonpCallback: "callback",     success: function(json) {         alert(json);     } }); </script> 

What would be the best option to solve this?

回答1:

If I have understood the question correctly, you could use the beforeSend callback to add basic authentication on the request. This is irrelevant of jsonp or cross-origin though.

beforeSend: function (xhr) {   xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); } 

https://jsfiddle.net/rn9Lp304/



回答2:

For Internet Explorer 8 and 9 you need to use XDomainRequest Object

Internet Explorer 10+ does the cross domain requests normally like all the other browsers.

As mentioned in the documentation you need to

  • create an object of the XDR using var xdr = new XDomainRequest();
  • open the connection using the get method using xdr.open("get", "username:password@anotherdomain.com");
  • send the data back to the server using xdr.send();

The complete code reference can be shown as on this thread by @Mark Pieszak

as a workaround to set the username and the password in the internet explorer you can set the following

DWORD for iexplore.exe to 0 in: [HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE].



回答3:

I will recommend you to try two things:

In ajaxSetup, do this:

$.ajaxSetup({     ....,     xhrFields: {        withCredentials: true     },     crossDomain: true,     .... }); 

In your ajax requests, set the full url like so, in addition to the credentials flag.

'Access-Control-Allow-Origin: https://not-example.com' 'Access-Control-Allow-Credentials: true' 

For servers with authentication, these browsers do not allow "*" in this header. The Access-Control-Allow-Origin header must contain the value of the Origin header passed by the client.



回答4:

use getJSON

$.getJSON("url",function (data) {/*code here*/}); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!