node.js - req.session 没有存储数据

标签 node.js reactjs session express

我正在尝试实现一个登录系统,用户可以在其中注册一个网站,然后使用他的帐户登录。一旦用户登录,他就可以编辑他的个人信息。

为了检查用户是否登录,我尝试将 req.session.isLoggedIn 设置为 true 然后检查该值是否为 true 以访问一些网站的区域。问题是,就在我登录后,我打印了 req.session 的值,我看到了我刚刚设置的值,但是在那之后,当我尝试检查 req 的值时。 session.isLoggedIn 在另一条路线上,我没有得到任何值(value)。

这是我的代码:

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/ 时,我在终端中收到此输出,我可以看到 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 中的静态文件,它们工作正常。

提前致谢!

编辑:

这是我的句柄登录方法的样子,我正在使用 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));
  };

最佳答案

好吧,我刚刚找到了解决我的问题的方法。我使用了@ytibrewala here 发布的解决方案以及@nlawson here 发表的评论.这就是我所做的:

显然,默认情况下,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));
  };

我使用了 include 因为我不是在同源工作。有关 credentials 参数接受的值的更多信息,请参见 here

然后,我在浏览器中遇到了 CORS 问题,所以我在后端的 index.js 文件中进行了更改:

索引.js

app.use(cors({credentials: true, origin: true}));

现在,每次我在我的网站上使用我的 handleSubmit 方法,并检查打印 req.session 的测试路由时,我都会看到我的 isLoggedIn 参数设置正确。

我留下我的路线,给想看的人:

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)){
        console.log("password matches");
        req.session.isLoggedIn = true;
        req.session.save();
        res.send(req.session);
      }
      else{
        console.log("password doesn't match");
        req.session.isLoggedIn = false;
        req.session.save();
        res.send(req.session);
      }
    }
  });
});

关于node.js - req.session 没有存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929631/

相关文章:

javascript - 如何获得无限滚动,直到所有结果都显示在React中的Elasticsearch JS API中

PHP 超全局变量

python - 类型错误 : Variable to save is not a Variable

javascript - 使用 post 方法到 firebase 数据库的无效或意外 token

javascript - 使用 nodemailer 和 smtp 无需身份验证发送邮件

javascript - 如何修复 "TypeError: Cannot set property ' 已批准“为空”?

laravel - Artisan 命令用于清除 Laravel 中的所有 session 数据

javascript - 带 Twig 的模板 Nordemailer

javascript - node.js express JS文件缓存

javascript - 通过预签名 url 上传 AWS S3 返回 400 错误请求