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 {
    }

相关推荐

  1. Angular:请求携带 cookie

    2024-01-23 09:52:02       48 阅读
  2. Ajax请求

    2024-01-23 09:52:02       36 阅读
  3. Angular: 配置 proxy 解决

    2024-01-23 09:52:02       53 阅读
  4. python爬虫,发送请求需要携带cookies

    2024-01-23 09:52:02       70 阅读
  5. 前端怎么实现请求

    2024-01-23 09:52:02       42 阅读
  6. 前后端分离项目请求

    2024-01-23 09:52:02       55 阅读
  7. Backend - Django CSRF 请求伪造

    2024-01-23 09:52:02       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-23 09:52:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-23 09:52:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-23 09:52:02       87 阅读
  4. Python语言-面向对象

    2024-01-23 09:52:02       96 阅读

热门阅读

  1. 502. IPO(贪心算法+优先队列/堆)

    2024-01-23 09:52:02       53 阅读
  2. LeetCode-题目整理【4】:跳跃游戏

    2024-01-23 09:52:02       50 阅读
  3. VirtualBox的Centos上安装GNOME桌面完整教程

    2024-01-23 09:52:02       61 阅读
  4. RK3568 Ubuntu关于rootfs大小问题

    2024-01-23 09:52:02       45 阅读
  5. 单例模式分享

    2024-01-23 09:52:02       57 阅读