req.session不存储数据

我试图实现一个login系统,用户可以注册到一个网站,然后用他的帐户login。 一旦用户login,他可以编辑他的个人信息。

要检查用户是否login,我试图将req.session.isLoggedIn设置为true ,然后检查该值是否为true以访问网站的某些区域。 问题是,刚刚login之后,我打印了req.session的值,并看到刚设置的值,但在此之后,当我尝试在另一个路由中检查req.session.isLoggedIn的值时,我得不到值。

这是我的代码:

 const express = require('express'); const app = express(); var { Client } = require('pg'); var bcrypt = require('bcrypt'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var cors = require('cors'); var path = require('path'); var session = require('express-session'); var url = require("url"); app.use(cors()); app.use(express.static(path.join(__dirname, 'client/build'))); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 600000000 }})) const client = new Client({ user: 'xxxxxxxxxxxxx', host: 'xxxxxxxxxxxxx', password: 'xxxxxxxxxxxxxxx', database: 'xxxxxxxxxxxxxx', port: 5432, ssl: true }) client.connect(); /*Rutas*/ /*Seleccionar huellas pertenecientas a una cierta categoria*/ app.get('/api/huellas/:categoria', (req, res) => { client.query('SELECT * FROM huellas WHERE categoria = $1 AND activo = TRUE', [req.params.categoria], (err, query) => { if (err) { console.log(err.stack); } else { res.json(query.rows); } }); }); /*Listar todas las huellas*/ app.get('/api/mostrarHuellas', function(req, res, next) { client.query('SELECT * FROM huellas', (err, query) => { if (err) { console.log(err.stack); } else { res.json(query.rows); } }); }); app.get('/api/buscarHuellas/', function(req, res) { console.log(req); console.log("nombre: " + req.query.nombre + " categoria: " + req.query.categoria + " estado: " + req.query.estado); client.query('SELECT * FROM huellas WHERE (nombre = $1 AND categoria = $2 AND estado = $3) AND activo = TRUE', [req.query.nombre, req.query.categoria, req.query.estado], (err, query) => { if (err) { console.log(err.stack); } else { res.json(query.rows); } }); }); app.post("/api/registro", function(req, res) { var email = req.body.email; var password = bcrypt.hashSync(req.body.password, 10); client.query('INSERT INTO usuarios(email, password, huella) VALUES ($1, $2, $3)', [email, password, req.body.huella], function(err, result) { if(err) { //console.log(err.stack); res.json(err); } else { console.log('row inserted'); res.json("ok"); } }); }); app.post("/api/login", function(req, res) { client.query('SELECT * FROM usuarios WHERE email = $1', [req.body.email], (err, query) => { if (err) { console.log(err.stack); } else { if(bcrypt.compareSync(req.body.password, query.rows[0].password)){ req.session.isLoggedIn = true; console.log(req.session); res.json("ok"); } else{ res.json("clave invalida"); } res.end(); } }); }); app.get("/api/logout", function(req, res) { req.session.destroy(); }); app.get("/api/sessions", function(req, res){ console.log(req.session); if(req.session.isLoggedIn) { console.log("logged in!"); } }); const port = process.env.PORT || 5000; app.listen(port); 

当我访问/api/login/我在terminal接收到这个输出时,我可以看到isLoggedIn:

  Session { cookie: { path: '/', _expires: 2017-09-05T00:29:19.786Z, originalMaxAge: 600000000, httpOnly: true }, isLoggedIn: true } 

但是之后,当我访问/api/sessions/我收到这个输出:

 Session { cookie: { path: '/', _expires: 2017-09-05T00:29:21.451Z, originalMaxAge: 599999999, httpOnly: true } } 

我正在使用Nodejs和Expressjs。 此外,我正在服务一些静态文件存储在/client/build ,他们工作正常。

提前致谢!

编辑:

以下是我的句柄login方法,我正在使用react和react-router 4:

 handleSubmit(event){ event.preventDefault(); fetch('/api/login', { method: 'post', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ "email": document.getElementById("email").value, "password": document.getElementById("pwd").value }) }) .then(response => response.json()) .then(res => { switch (res) { case "clave invalida": alert("clave invalida"); break; case "ok": alert("sesion iniciada"); this.props.history.push("/"); break; default: alert("Error. Contacte a un administrador"); break; } }) .catch(err => console.log(err)); }; 

Solutions Collecting From Web of "req.session不存储数据"

那么,我只是find了我的问题的解决scheme。 我使用@ytibrewala发布的解决scheme和@nlawson 在这里发表的评论。 这就是我所做的:

显然, 默认情况下, fetch方法不会发送cookie ,因此您需要在AJAX调用中设置credentials参数,我这样做:

AJAX调用

  handleSubmit(event){ event.preventDefault(); fetch('http://localhost:5000/api/login', { method: 'post', credentials: 'include', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ "email": document.getElementById("email").value, "password": document.getElementById("pwd").value }) }) .then(response => response.json()) .then(res => { console.log(res); if(res.isLoggedIn){ alert("Signed in"); this.props.history.push("/hueprint"); } else{ alert("Invalid user or password"); } }) .catch(err => console.log(err)); }; 

您需要随时发送与res对象的cookie,只要你想保存它们。 这是我的代码,它的工作原理。 一探究竟。

 app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: true, })) app.get("/", function(req, res){ if(req.session.views){ req.session.views++; }else{ req.session.views = 1; } res.status(200).send(req.session); }) app.get("/checkerPage", function(req, res){ console.log(req.session); //it logs the correct data. res.send("whatever"); }) //post req app.post("/post", function(req, res){ req.session.user = "myname"; res.send(req.session); console.log(req.session); }); 

我的索引的HTML

 <form action="/post" method="post"> <input type="text" name="myName" value=""> <input type="submit" name="" value="submit"> </form>