Angular在用户登录后设置授权请求头headers.append('Authorization', 'token');
方案1. 使用Angular http
import {Injectable} from '@angular/core'; import {Http, Headers} from '@angular/http'; @Injectable() export class HttpClient { constructor(private http: Http) {} createAuthorizationHeader(headers: Headers) { headers.append('Authorization', 'Basic ' + btoa('username:password')); } get(url) { let headers = new Headers(); this.createAuthorizationHeader(headers); return this.http.get(url, { headers: headers }); } post(url, data) { let headers = new Headers(); this.createAuthorizationHeader(headers); return this.http.post(url, data, { headers: headers }); } }
方案2.Angular 4.3.x及更高版本可以执行如下操作来添加请求头
2.1拦截器设置
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, } from '@angular/common/http'; export class AddHeaderInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer 123') }); // Pass the cloned request instead of the original request to the next handle return next.handle(clonedRequest); } }
2.2创建拦截器后,您应该使用HTTP_INTERCEPTORS
提供的注册。
import { HTTP_INTERCEPTORS } from '@angular/common/http'; @NgModule({ providers: [{ provide: HTTP_INTERCEPTORS, useClass: AddHeaderInterceptor, multi: true, }], }) export class AppModule {}
方案3.配置扩展BaseRequestOptions
3.1配置代码如下
import {provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http'; import {AppCmp} from './components/app/app'; class MyRequestOptions extends BaseRequestOptions { constructor () { super(); this.headers.append('My-Custom-Header','MyCustomHeaderValue'); } } bootstrap(AppCmp, [ ROUTER_PROVIDERS, HTTP_PROVIDERS, provide(RequestOptions, { useClass: MyRequestOptions }) ]);
3.2添加请求头
this.http._defaultOptions.headers.append('Authorization', 'token'); 或者 this.http._defaultOptions.headers.set('Authorization', 'token');
3.3删除请求头
this.http._defaultOptions.headers.delete('Authorization');
参考来源:https://www.itranslater.com/qa/details/2112366855208829952
标签:
angular
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决