且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何发送带有标头参数的 HTTP 请求?

更新时间:2021-11-20 06:05:28

如果它说 API 密钥被列为标题,则您很可能需要在您的 headers 选项中设置它http 请求.通常是这样的:

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

这是另一个问题

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

刚刚看到您想将响应存储在一个变量中.在这种情况下,我可能只使用 AJAX.像这样:

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

我从这个问题得到了这个我正在工作,所以我现在无法测试它,但看起来很可靠

I got this from this question and I'm at work so I can't test it at the moment but looks solid

编辑 2:很确定您应该能够使用这一行:

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

而不是第一次编辑中的 beforeSend 行.这对你来说可能更简单

instead of the beforeSend line in the first edit. This may be simpler for you