在 ALB 规则中添加目标组以保留 Cookie,并在 Express 后端中添加“withCredentials”选项以发送 Cookie。
ALB 会自动将源 IP 放入请求头中,因此可以通过此方法保持会话状态。下面是示例代码:
在 ALB 规则中:
{
"Type": "forward",
"TargetGroupArn": "target-group-arn",
"ForwardConfig": {
"TargetGroups": [
{
"TargetGroupArn": "ecs-target-group-arn",
"Weight": 100
}
],
"TargetGroupStickinessConfig": {
"Enabled": true,
"DurationSeconds": 86400
}
},
"Order": 2,
"Conditions": [
{
"Field": "path-pattern",
"PathPatternConfig": {
"Values": [
"/api/*"
]
}
}
]
}
在 Express 后端中:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'url-of-react-frontend');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/api/cookie', (req, res) => {
res.cookie('myCookie', 'cookieValue', { maxAge: 900000, httpOnly: true });
res.send('Cookie set');
});
app.listen(3000, () => console.log('Server started on port 3000'));
在 React 前端中:
const response = await fetch('/api/cookie', { credentials: 'include' });
const data = await response.text();
console.log(data);