要使Angular能够读取后端发送的cookie,需要对Angular应用进行一些配置。以下是解决方法的代码示例:
withCredentials
选项到HTTP请求的头部,以允许发送和接收cookie:import { HttpClient } from '@angular/common/http';
// ...
constructor(private http: HttpClient) {}
// ...
// 在HTTP请求中添加withCredentials选项
this.http.get(url, { withCredentials: true }).subscribe(response => {
// 处理响应
});
Access-Control-Allow-Credentials
为true
,以允许发送cookie。在后端的响应中,可以使用以下代码示例:
// 设置Access-Control-Allow-Credentials响应头
response.setHeader("Access-Control-Allow-Credentials", "true");
const express = require('express');
const app = express();
// 启用CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // 允许访问的源
res.header("Access-Control-Allow-Credentials", "true"); // 允许发送cookie
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// ...
请根据你的后端框架和具体需求,选择适合的解决方法。