Cross domain request with header authentication

倖福魔咒の 提交于 2019-12-04 14:03:12

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/

Pritish Vaidya

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].

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.

use getJSON

$.getJSON("url",function (data) {/*code here*/});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!