为一个请求设置 HTTP 标头 [英] Set HTTP header for one request

查看:38
本文介绍了为一个请求设置 HTTP 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有一个需要基本身份验证的特定请求,因此我需要为该请求设置 Authorization 标头.我阅读了 设置 HTTP 请求标头,但据我所知,它会设置该方法的所有请求的标头.我的代码中有这样的东西:

I have one particular request in my app that requires Basic authentication, so I need to set the Authorization header for that request. I read about setting HTTP request headers, but from what I can tell, it will set that header for all requests of that method. I have something like this in my code:

$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";

但我不希望我的每个帖子请求都发送此标头.有什么办法可以只为我想要的一个请求发送标头吗?还是必须在我提出要求后将其删除?

But I don't want every one of my post requests sending this header. Is there any way to send the header just for the one request I want? Or do I have to remove it after my request?

推荐答案

您传递给 $http 的配置对象中有一个 headers 参数,用于每个调用的标头:

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

或者使用快捷方式:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

有效参数列表在 $http 服务中可用文档.

The list of the valid parameters is available in the $http service documentation.

这篇关于为一个请求设置 HTTP 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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