【发布时间】:2019-05-22 16:59:26
【问题描述】:
我正在为 node.js 和 react.js 使用 express 构建登录系统。在我的后端,当用户登录时,它会创建一个 cookie。当我转到网络 > 登录时,我可以看到:
设置 Cookie:user_id=s%3A1.E%2FWVGXrIgyXaM4crLOoxO%2Fur0tdjeN6ldABcYOgpOPk;路径=/;仅http;安全
但是当我转到应用程序 > Cookies > http://localhost:3000 时,那里什么也没有。我相信这是因为当我从客户端发出发布请求时,我不允许凭据正确通过。我该怎么做?请告诉我是否可以通过任何方式改进我的问题。
//Login back-end
router.post('/login', (req, res, next) => {
if(validUser(req.body)) {
User
.getOneByEmail(req.body.email)
.then(user => {
if(user) {
bcrypt
.compare(req.body.password_digest, user.password_digest)
.then((result) => {
if(result) {
const isSecure = process.env.NODE_ENV != 'development';
res.cookie('user_id', user.id, {
httpOnly: true,
secure: isSecure,
signed: true
})
res.json({
message: 'Logged in'
});
} else {
next(new Error('Invalid Login'))
}
});
} else {
next(new Error('Invalid Login'))
}
});
} else {
next(new Error('Invalid Login'))
}
});
//Allow CORS index.js
app.use(
cors({
origin: "http://localhost:3000",
credentials: true
})
);
//Login client side (React.js)
loginUser(e, loginEmail, password) {
e.preventDefault();
let email = loginEmail;
let password_digest = password;
let body = JSON.stringify({ email, password_digest });
fetch("http://localhost:5656/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
credentials: "include",
body
})
.then(response => response.json())
.then(user => {
console.log(user);
});
}
【问题讨论】:
-
使用 react-cookie 库,然后可以使用 cookies.get('key' ) 和 cookies.set('key', 'value')
-
感谢您对萨米尔的评论。但是,我无法让它工作。我正在使用这样的通用 cookie:从 'universal-cookie' 导入 Cookie; const cookies = new Cookies(); cookies.set('myCat', 'Pacman', { path: '/' }); console.log(cookies.get('myCat')); // Pacman 当我转到 Application > Cookies > localhost:3000 时,我可以在那里看到这个 'myCat' cookie。但我不确定如何将它与我的应用程序集成。 (我正在尝试正确显示代码,但我不能。)
-
您的所有配置似乎都是正确的,除了一件我不确定的事情。当您在登录后路由中设置 cookie 时,请确保
secure标志为 false(仅用于开发)。在生产中,将其设置为true。这是因为 localhost 是 HTTP 而不是 HTTPS。因此,请确保您的isSecure变量为 false。这是唯一对我来说似乎是潜在问题的事情。