为何登录后Set-Cookie在Angular后续请求中丢失?
调用登录接口时,后端响应头返回了HttpOnly类型的Set-Cookie,但在Angular客户端发起后续接口请求时,请求头中并未携带该Cookie。Postman中测试一切正常,但Angular里就是不行,已经尝试了几种方法还是没解决,求帮忙。
Angular代码(service.ts)
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}) }
Go Fiber设置HttpOnly 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
- Angular客户端中:登录接口的Set-Cookie在响应头中存在,但后续请求的请求头里没有该Cookie
已尝试的解决方案
- 在HttpClient的GET请求中添加
{withCredentials:true} - 配置Go后端CORS:
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, }))
- 创建proxy.conf.json配置代理,并修改package.json启动脚本:
- 启动脚本:
"start": "ng serve --proxy-config proxy.conf.json",- proxy.conf.json内容:
{ "/api/*": { "target": "http://localhost:8080", "secure": false, "logLevel": "debug" } }- 同时在Angular项目src目录下添加environment.ts:
export const environment = { production: false, baseUrl: 'http://localhost:8080' // Adjust this to match your backend server URL };
内容的提问来源于stack exchange,提问作者JosieGPT
相关产品推荐
相关产品推荐

