如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:33:13  来源:igfitidea点击:

How to pass authorization header in $.post() method using Javascript?

javascriptrestjqueryjquery-post

提问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 dataand contentTypemixed up.

您可能已经得到了datacontentType混淆。

  • contentTypeis the Content-typeheader you send.

  • datachanges how jQuery treats the data you receive.

  • contentTypeContent-type您发送的标题。

  • data改变 jQuery 处理您收到的数据的方式。

回答by Croot

The jQuery $.ajax() method accepts a headersvalue 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 参数中传入一个新的设置对象。我不知道这个,所以谢谢你提出这个问题:)