我正在学习并为我的博客网站应用身份验证!
我正在使用
express-session
来处理登录。浏览器和服务器会话上的 Cookie 工作正常。
但是,我在服务器端 Express 应用程序上检索 Cookie 时遇到问题。我尝试了以下方法:
[Object: null prototype]
。undefined
我的代码/设置如下:
function auth (req, res, next) {
// Problem: Cannot read browser cookie of HTTP requests.
console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
next();
}
router.get('/', auth, async (req, res) => { // ... }
中间件
app.use(cors({
origin: ['http://localhost:3000'],
credentials: true
}));
app.use(cookieParser()) // Also tried with secret option.
app.use(session({
secret: 'top-secret',
resave: true,
rolling: true,
saveUninitialized: false,
store: store, // this is working
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 14,
httpOnly: true,
secure: process.env.NODE_ENV !== 'Development',
sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
}
}))
提前谢谢您:)
如果您仅使用 http,您应该考虑两件事:
客户端请求时的第1步: 你应该像这样发送请求:
const req = await fetch("http://localhost:7000/api/auth/login", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
});
const data = await req.json();
快速步骤2:
const allowedOrigins = ["http://localhost:8000"];
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
var msg =
"The CORS policy for this site does not " +
"allow access from the specified Origin.";
callback(new Error(msg), false);
}
},
optionsSuccessStatus: 200,
credentials: true,
};
app.use(cors(corsOptions));
现在您可以使用 req.cookies.nameOfCookiesWhichYouSendThroughCoockieParser
快速获取 cookie我在 Node-js 上使用 axios (React) + Express-js
在客户端 - 为了从服务器获取 cookie:
只需在 axios 请求中设置
withCredentials: true
,即可使用此配置示例:
const config = {
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
};
在服务器端 - 为了从客户端获取 cookie:
还需要在axios请求中设置
withCredentials: true
,cookie-parser
库:
npm i cookie-parser
导入此库:
const cookieParser = require("cookie-parser");
并使用 cookieParser 中间件:
app.use(cookieParser());
最后,
req.cookies
应该返回您的cookie列表。
你有没有得到任何解决方案我现在整个月都陷入这个位置,请告诉解决方案...谢谢你