上海古都建筑设计集团,上海办公室装修设计公司,上海装修公司高质量的内容分享社区,上海装修公司我们不是内容生产者,我们只是上海办公室装修设计公司内容的搬运工平台

Angular:跨域请求携带 cookie

guduadmin463月前

新建拦截器,设置 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, next: HttpHandler): Observable> {
        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 { }

网友评论

搜索
最新文章
热门文章
热门标签
 
 梦见耳屎  梦见门关不上是什么意思  周公解梦全解大全