Angular在CORS中忽略了设置Cookie和删除Cookie的头信息。
创始人
2024-10-30 19:30:24
0

要在Angular中解决CORS中忽略设置Cookie和删除Cookie的头信息问题,可以通过修改请求头信息的方式来实现。以下是一个代码示例:

  1. 创建一个HttpInterceptor来拦截所有的HTTP请求,并修改请求头信息。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CookieInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    // 添加Cookie到请求头中
    req = req.clone({
      withCredentials: true
    });

    return next.handle(req);
  }
}
  1. 在app.module.ts中注册该Interceptor。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { CookieInterceptor } from './cookie.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CookieInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样,每个HTTP请求都会被拦截器拦截,并在请求头中添加withCredentials: true,从而告诉服务器需要设置和读取Cookie信息。

请注意,该解决方法需要确保服务器已经配置了合适的CORS策略,允许跨域请求,并且响应头中包含了Access-Control-Allow-Credentials: true

相关内容

热门资讯

透视玄学"aapok... 透视玄学"aapoker能控制牌吗"wpk德州局怎么透视(其实真的是有辅助安装)-哔哩哔哩1、下载好...
此事迅速冲上热搜"w... 此事迅速冲上热搜"wepoker游戏安装教程"佛手在线大菠萝为什么都输(一直真的是有辅助辅助器)-哔...
透视好友"wepok... 透视好友"wepoker怎么提高运气"wepoker作必弊方法(一贯是真的辅助修改器)-哔哩哔哩1、...
透视线上"wepok... 透视线上"wepoker模拟器哪个"hhpoker万能辅助器(好像存在有辅助软件)-哔哩哔哩1、玩家...
透视数据"wejok... 透视数据"wejoker免费脚本"xpoker怎么作必弊(果然有辅助下载)-哔哩哔哩1、xpoker...
据报道"wejoke... 据报道"wejoker免费脚本"德州透视脚本(竟然是有辅助下载)-哔哩哔哩1、完成wejoker免费...
截至目前"德普之星辅... 截至目前"德普之星辅助器app"pokemmo脚本手机版(一贯是真的辅助辅助器)-哔哩哔哩一、德普之...
于此同时"wepok... 于此同时"wepoker辅助器官方"wepoker作必弊视频(总是有辅助辅助器)-哔哩哔哩该软件可以...
透视美元局"poke... 透视美元局"pokemmo手机脚本"pokemmo脚本手机版(一直是有辅助工具)-哔哩哔哩1、该软件...
透视好友"wpk透视... 透视好友"wpk透视辅助下载"wepoker挂(总是存在有辅助下载)-哔哩哔哩wpk透视辅助下载脚本...