要在跨域请求中携带 Cookie,需要在服务器的响应头中进行特定配置,主要涉及以下几个关键响应头:
Access-Control-Allow-Origin
:必须指定具体的源(不能使用通配符*
)Access-Control-Allow-Credentials
:需要设置为true
- (可选)
Access-Control-Allow-Headers
:如果有自定义请求头,需要包含在内
以下是不同服务器环境下的配置示例:
对于 Node.js (Express):
const express = require('express');
const app = express();
// 跨域配置
app.use((req, res, next) => {
// 允许特定源的请求(不能用*)
res.setHeader('Access-Control-Allow-Origin', 'https://your-client-domain.com');
// 允许携带凭证(如Cookie)
res.setHeader('Access-Control-Allow-Credentials', 'true');
// 允许的请求方法
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
// 允许的请求头
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// 预检请求的缓存时间(秒)
res.setHeader('Access-Control-Max-Age', '86400');
// 处理预检请求
if (req.method === 'OPTIONS') {
return res.status(204).end();
}
next();
});
对于 Nginx 服务器:
location / {
# 允许特定源的请求
add_header Access-Control-Allow-Origin "https://your-client-domain.com";
# 允许携带凭证
add_header Access-Control-Allow-Credentials "true";
# 允许的请求方法
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
# 允许的请求头
add_header Access-Control-Allow-Headers "Content-Type, Authorization";
# 预检请求的缓存时间
add_header Access-Control-Max-Age "86400";
# 处理预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
}
同时,客户端在发送请求时也需要设置 withCredentials: true
(以 JavaScript 的 fetch 为例):
fetch('https://your-server-domain.com/api/data', {
method: 'GET',
credentials: 'include' // 关键配置,允许携带Cookie
})
.then(response => response.json())
.then(data => console.log(data));
注意事项:
Access-Control-Allow-Origin
不能使用*
,必须指定具体的客户端域名- 客户端和服务器端必须同时配置才能生效
- 如果使用了 HTTPS,需要确保 Cookie 的
Secure
属性设置正确 - 可能还需要配置 Cookie 的
SameSite
属性为None
(视具体场景而定)