如何使用 Javascript 在 $.post() 方法中传递授权标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21276178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass authorization header in $.post() method using Javascript?
提问by Umesh Kadam
I want to pass Authorization header while POSTing data to server. I tried
我想在将数据发布到服务器时传递 Authorization 标头。我试过
$.ajax({
url : <ServiceURL>,
data : JSON.stringify(JSonData),
type : 'POST',
contentType : "text/html",
dataType : 'json',
success : function(Result) {
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', <Authorization Header Value>);
},
error: function (RcvData, error) {
console.log(RcvData);
}
});
But REST service returns error (error code : 500). The same service was working fine with $.post() before adding authorization. could anyone tell me "How to pass authorization header in $.post()??"
但是 REST 服务返回错误(错误代码:500)。在添加授权之前,相同的服务与 $.post() 一起工作正常。谁能告诉我“如何在 $.post() 中传递授权标头??”
回答by Paul Draper
Use
利用
contentType: 'application/json',
You may have gotten data
and contentType
mixed up.
您可能已经得到了data
和contentType
混淆。
contentType
is theContent-type
header you send.data
changes how jQuery treats the data you receive.
contentType
是Content-type
您发送的标题。data
改变 jQuery 处理您收到的数据的方式。
回答by Croot
The jQuery $.ajax() method accepts a headers
value in the settings object.
jQuery $.ajax() 方法接受headers
设置对象中的一个值。
So:
所以:
$.ajax({
// url, data, etc...
headers: {
"Authorization" :"Basic " + myBase64variable,
"Content-Type" :"application/json"
}
});
Source: http://api.jquery.com/jquery.ajax/
来源:http: //api.jquery.com/jquery.ajax/
PS: Seems you can also pass in a new settings object in the beforeSend parameter. I didn't know this, so thanks for asking this question :)
PS:似乎您还可以在 beforeSend 参数中传入一个新的设置对象。我不知道这个,所以谢谢你提出这个问题:)