Angular自定义Cookie未在头部发送?
创始人
2024-11-01 11:00:12
0

在Angular应用中发送自定义cookie,需要将自定义cookie作为HttpHeaders传递给HttpClient的方法中。以下是具体实现步骤:

  1. 在服务中,将自定义cookie存储在local storage中,以便在需要时获取。
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CookieService {
  setCookie(name: string, value: string, expireDays: number) {
    const d = new Date();
    d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
    const expires = 'expires=' + d.toUTCString();
    document.cookie = name + '=' + value + '; ' + expires;
  }

  getCookie(name: string) {
    const cookies = document.cookie.split('; ');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].split('=');
      if (cookie[0] === name) {
        return cookie[1];
      }
    }
    return '';
  }
}
  1. 在需要发送请求的组件中获取cookie,并将其包含在http header中发送。
import { Component } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { CookieService } from '../cookie.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'my-app';

  constructor(private http: HttpClient, private cookieService: CookieService) { }

  sendRequest() {
    const token = this.cookieService.getCookie('token');
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    const url = 'https://api.example.com/data';
    this.http.get(url, { headers }).subscribe((response) => {
      console.log(response);
    });
  }
}

以上代码示例演示了如何获取自定义cookie并将其包含在http header中发送。简而言之,需要使用Angular HttpInterceptor机制,在intercept()函数中处理请求头中加入已存储自定义cookie。

相关内容

热门资讯

透视详细"wepok... 透视详细"wepoker俱乐部辅助"切实真的是有辅助器(哔哩哔哩)1、操作简单,无需wepoker俱...
透视普及"wepok... 透视普及"wepoker轻量版透视"都是存在有辅助挂(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略技...
透视开挂"hhpok... 透视开挂"hhpoker万能辅助器"切实存在有辅助技巧(哔哩哔哩)1、hhpoker万能辅助器有没有...
透视解密"hhpok... 您好,hhpoker辅助软件下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...
透视详细"wepok... 透视详细"wepokerplus到底是挂了吗"都是是真的辅助技巧(哔哩哔哩)1、每一步都需要思考,不...
透视总结"竞技联盟辅... 透视总结"竞技联盟辅助插件"其实是真的辅助攻略(哔哩哔哩)1、该软件可以轻松地帮助玩家将竞技联盟辅助...
透视曝光"wpk俱乐... 透视曝光"wpk俱乐部是真的吗"本来真的有辅助神器(哔哩哔哩)wpk俱乐部是真的吗破解侠是真的助透视...
透视开挂"拱趴大菠萝... 透视开挂"拱趴大菠萝有挂吗"好像存在有辅助器(哔哩哔哩);1、玩家可以在拱趴大菠萝有挂吗透视最简单三...
透视解密"佛手大菠萝... 透视解密"佛手大菠萝有挂吗"本来存在有辅助app(哔哩哔哩)1、实时佛手大菠萝有挂吗透视辅助更新:用...
透视揭露"约局吧是否... 透视揭露"约局吧是否有挂"好像是真的辅助插件(哔哩哔哩)1)约局吧是否有挂辅助插件:进一步探索约局吧...