新建拦截器,设置 XMLHttpRequest:withCredentials 属性
1. 新建文件夹 http-interceptors
该文件夹下可有多个不同用途的拦截器
2. 新建拦截器 common.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable()
export class CommonInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req.clone({
withCredentials: true
}));
}
3. 用一个数组汇总起来,统一引入: index.ts (后续需要添加拦截器,只需加入到该数组即可)
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { CommonInterceptor } from "./common.interceptor";
export const httpInterceptorProvides = [
{
provide: HTTP_INTERCEPTORS,
useClass: CommonInterceptor, //指定使用哪个拦截器
multi: true //表示可设置多个拦截器
}
]
4. 引入拦截器使用: service.module.ts
import { isPlatformBrowser } from '@angular/common';
import { InjectionToken, NgModule, PLATFORM_ID } from '@angular/core';
import { httpInterceptorProvides } from './http-interceptors';
export const API_CONFIG = new InjectionToken('ApiConfigToken');
export const WINDOW = new InjectionToken('WindowToken');
@NgModule({
declarations: [],
imports: [],
providers: [
{
provide: API_CONFIG,
useValue: 'http://localhost:3000/'
},
{
provide: WINDOW,
useFactory(platformId: Object): Window | Object {
return isPlatformBrowser(platformId) ? window : {};
},
deps: [PLATFORM_ID]
},
httpInterceptorProvides
]
})
export class ServicesModule { }
文章来源地址https://www.toymoban.com/news/detail-817366.html
文章来源:https://www.toymoban.com/news/detail-817366.html
到了这里,关于Angular:跨域请求携带 cookie的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!