微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐