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 {}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章