问题是,当我使用端点登录时,它在响应标头中返回一个set-cookie,这是一个仅http的cookie,但当我对其他端点执行其他请求时,我在请求标头中看不到set-cookie,我已try 修复此问题

下面是一个service.ts中的Angular 代码,

private apiUrl = environment.baseUrl +  '/api/v1/login';
private apiUrl2 = environment.baseUrl + '/api/v1/anotherRequest';
login(req: Login): Observable<string> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
    return this.httpClient.post<string>(this.apiUrl,JSON.stringify(req),{ headers })
  }
anotherRequestBeingMade(): Observable<any]> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
   
    return this.httpClient.get<any>(this.apiUrl2,{withCredentials:true})
  }

这就是我如何使用Golang在光纤中设置我的http only cookie

cookie := fiber.Cookie{
        Name:     "my_cookie",
        Value:    *thereisavaluehere,
        Expires:  time.Now().Add(time.Hour * 24),
        HTTPOnly: true,
        Secure:   true,
        SameSite: "None",
        Path:     "/",
    }

    c.Cookie(&cookie)

我在Postman上测试了它,它在响应头为Set-Cookie的登录端点上设置了cookie.当执行后续请求时,它显示在请求头Cookie上,但当我在Angular客户端上测试时,Set cookies在执行登录端点时仍然存在,但Cookie头在后续请求中不可用.

我try 了以下几点:

  • 我已经在get httpClient中包含了{withCredentials:true}

  • 我试着在我的后端修复cors的问题,这是写在golang

  app.Use(cors.New(cors.Config{
       AllowOrigins:     "http://localhost:4200",
       AllowHeaders:     "Origin, Content-Type, Accept",
       AllowMethods:     "GET, POST, PUT, DELETE, OPTIONS",
       ExposeHeaders:    "Set-Cookie",
       AllowCredentials: true,
   }))
  • try 绕过代理,方法是在与Package.json相同的级别创建proxy.conf.json,并配置Package.json脚本对象,一节从
"start": "ng serve --proxy-config proxy.conf.json",
{
"/api/*": {
  "target": "http://localhost:8080",
  "secure": false,
  "logLevel": "debug"
}
}

然后,我在Angular 应用程序的src文件夹中添加了一个enviroment.ts文件,该文件具有

export const environment = {
    production: false,
    baseUrl: 'http://localhost:8080' // Adjust this to match your backend server URL
  };

先谢谢你

推荐答案

我忽略了一个事实,即我在登录API中遗漏了httpclient的withcredentials:true

login(req: Login): Observable<string> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
    return this.httpClient.post<string>(this.apiUrl,JSON.stringify(req),{headers,withCredentials:true})
  }

Typescript相关问答推荐

为什么缩小封闭内部不适用于属性对象,但适用于声明的变量?

TypeScript类型不匹配:在返回类型中处理已经声明的Promise Wrapper

在Angular中注入多个BrowserModules,但在我的代码中只有一个

具有动态键的泛型类型

如何使用类型谓词将类型限制为不可赋值的类型?

对未到达受保护路由的路由环境做出react

ANGLE独立组件布线错误:没有ActivatedRouting提供程序

为什么我的查询钩子返回的结果与浏览器的网络选项卡中看到的结果不同?

TypeScrip错误:为循环中的对象属性赋值

界面中数组中的混合类型导致打字错误

TS2739将接口类型变量赋值给具体变量

基于闭包类型缩小泛型类型脚本函数的范围

仅当类型为联合类型时映射属性类型

TypeScript:如何使用泛型和子类型创建泛型默认函数?

可以';t使用t正确地索引对象;联合;索引类型

确保财产存在

如何将元素推入对象中的类型化数组

为什么 Typescript 无法正确推断数组元素的类型?

基于泛型类型的条件类型,具有条目属性判断

为什么我们在条件语句中使用方括号[]?