在Express路由器上,Req.Cookie为[Object:Null Prototype]{} [英] req.cookies is [Object: null prototype] {} on express router
本文介绍了在Express路由器上,Req.Cookie为[Object:Null Prototype]{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前正在尝试获取一些Cookie用于身份验证。我正在使用一个后端API和一个反应前端,让网站工作。但是,当我尝试在后端使用Express获取cookie时,我得到的唯一响应是:[Object: null prototype] {}
Cookie存储correctly,但无法访问。你知道为什么会发生这种事吗?以下是我的代码:
const { Router } = require("express");
const route = Router();
var cookieParser = require('cookie-parser');
route.use(cookieParser());
route.get("/", async (req, res) => {
console.log(req.cookies)
})
知道为什么它一直这样做吗?感谢您的帮助:d
编辑
我刚刚注意到当我使用FETCH时,它返回未定义的,如果我手动访问地址,它会给我正确的Cookie。参见here
我正在使用此代码获取:
fetch(`${config.hosts.INTERNAL_API}/`, {
method: "GET",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}).then(res => res.json()).then(data => this.setState(data))
推荐答案
尝试将credentials: 'include'
添加到Fetch调用,如下所示:
fetch(`${config.hosts.INTERNAL_API}/`, {
method: "GET",
credentials: "include",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}).then(res => res.json()).then(data => this.setState(data))
当您手动访问地址时它起作用的原因是,默认情况下,浏览器发出的HTTP请求在Header中发送Cookie。回迁不起作用。
这篇关于在Express路由器上,Req.Cookie为[Object:Null Prototype]{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文