angular请求头部加XSRF-TOKEN

1、创建拦截器

import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
  } from '@angular/common/http';
import { Observable } from 'rxjs';
  
  export class AddHeaderInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      // Clone the request to add the new header
        let xsrftoken = ''
        document.cookie.split(';').forEach(it => {
            if (it.split('=')[0]=='XSRF-TOKEN'||it.split('=')[0]==' XSRF-TOKEN') {
            xsrftoken = it.split('=')[1]
            }
        })
      const clonedRequest = req.clone({ headers: req.headers.set('X-XSRF-TOKEN', xsrftoken) });
  
      // Pass the cloned request instead of the original request to the next handle
      return next.handle(clonedRequest);
    }
  }

2、用HTTP_INTERCEPTORS提供的注册

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AddHeaderInterceptor,
    multi: true,
  }],
})
export class AppModule {}

参照:https://www.cnblogs.com/sugartang/p/14338731.html

上一篇:浅析如何利用指针实现一些c语言库函数


下一篇:项目在STS下设置Git提交规则【备忘录】