我使用 axios 从 ReactJS 客户端向 Node.js 服务器发送请求,如下所示。
import axios from 'axios';
const apiClient = axios.create({
withCredentials: true,
baseURL: 'http://localhost:8080'
});
async function(payload) {
try {
debugger;
let result = await apiClient.post('/auth/signup/', payload);
debugger;
return result;
} catch (error) {
debugger;
throw error;
}
}
node.js 端点在响应中设置一个 cookie,如下所示。
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const cors = require('cors');
const jwt = require('jsonwebtoken');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.use(cors({ origin: 'http://localhost:3000', credentials: true, exposedHeaders: ['Set-Cookie', 'Date', 'ETag']} ));
router.use(cookieParser());
router.post('/signup', async (req, res, next) => {
debugger;
let database = req.app.locals.database;
try {
let user = await database.findByUsername(req.body.username);
let token = await jwt.sign({username: user.username}, config.secret, {expiresIn: "15m"});
res.cookie('jwt', token, {
maxAge: 900,
});
} catch (error) {
debugger;
return res.status(503).send({ auth: false, message: 'Database error.' });
}
});
响应的 Set-Cookie header 包含预期的 cookie。
但是,Chrome 似乎没有设置 cookie,因为我在开发者控制台的应用程序窗口中看不到 cookie。
我查看了以下问题的答案,其中提到在 axios 配置中设置 { withCredentials: true }
并且不在 node.js 中使用 cors 通配符来源,但我是已经在做这两件事了。
Set-Cookie header not setting cookie in Chrome
Set cookies for cross origin requests
关于为什么未设置 cookie 以及如何解决此问题有什么想法吗?
最佳答案
这是我对类似问题的回答的转发 https://stackoverflow.com/a/62821342/8479303
<小时/>就我而言,网络面板显示响应具有“Set-Cookie” header ,但在 axios 中 header 不会显示,并且正在设置 cookie。
对我来说,解决方案是设置 Access-Control-Expose-Headers
header 。
解释,来自this comment关于 axios 存储库中的一个问题,我被定向到此 person's notes这导致我设置了 Access-Control-Expose-Headers
header -- 现在 cookie 已在客户端中正确设置。
因此,在 Express.js 中,我必须向我的 cors 中间件添加 exposedHeaders
选项:
const corsOptions = {
//To allow requests from client
origin: [
"http://localhost:3001",
"http://127.0.0.1",
"http://104.142.122.231",
],
credentials: true,
exposedHeaders: ["set-cookie"],
};
...
app.use("/", cors(corsOptions), router);
<小时/>
同样重要的是,在 axios 方面,我在以下我想要包含 cookie 的 axios 请求中使用 withCredentials
配置。
例如/
const { data } = await api.get("/workouts", { withCredentials: true });
关于node.js - Set-Cookie header 中的 Cookie 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555100/