本文介绍: Angular:跨域请求携带 cookie
新建拦截器,设置 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://blog.csdn.net/Lm_choose_live/article/details/135742985
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_60667.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。