Angular:跨域请求携带 cookie

发布时间:2024年01月22日

新建拦截器,设置 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
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。