我正在為我的博客網站學習和應用身份驗證!
我express-session用來處理登錄。瀏覽器和服務器會話上的 Cookie 作業正常。

但是,我無法在 server-side express app 上檢索 cookie。我嘗試了以下方法:
- 使用 cookie-parser,req.cookies 和 req.signedCookies 都回傳
[Object: null prototype]. - 設定 CORS
- req.cookie & req.header.cookie 回傳
undefined - 我可以在瀏覽器網路選項卡中看到來自我的連接的“Cookie”標頭。
我的代碼/設定如下:
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'
}
}))
先感謝您 :)
編輯 1:我的提取代碼:

uj5u.com熱心網友回復:
如果您只使用 http,您應該考慮兩件事:
Step1 在客戶端請求時: 您應該像這樣發送請求:
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在 express 中獲取 coockies
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/398162.html
標籤:javascript 节点.js 表达 饼干 快速会话
上一篇:發生捕獲時運行程式
