具有标头身份验证的跨域请求 [英] Cross domain request with header authentication

查看:85
本文介绍了具有标头身份验证的跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要发送一个带有跨域来源的获取请求并使用标头身份验证。

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

它的工作正常Chrome和Firefox,但我在Safari和IE中遇到问题。同样在随机的情况下,它返回401。

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?

推荐答案

如果我已正确理解了问题,您可以使用beforeSend回调在请求中添加基本身份验证。这与jsonp或cross-origin无关。

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/

这篇关于具有标头身份验证的跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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