会话不保存在快速会话中

Session Doesn't be saved in express-session

我正在研究 HTTPS。 我正在尝试使 login/logout 发挥作用。对于此功能,我在通过 POST 方法登录时将 userId 保存在会话中。之后,我尝试使用 GET 方法获取下一个组件的用户信息。但是会话中没有userId。 我完全不知道。我尝试使用 session.save()。如何在会话中保存一些东西?

//login.js
const { Users } = require('../../models');

module.exports = {
  post: async (req, res) => {
 
    const userInfo = await Users.findOne({
      where: { userId: req.body.userId, password: req.body.password },
    });
    
    if (!userInfo) {
      // your code here
      res.send({ message : `not authorized` })
      
    } else {
      
      req.session.userId= userInfo.userId
      res.send({ message :`ok` })
    
      
    }
  }
}

//userinfo.js

const { Users } = require('../../models');

module.exports = {
  get: async (req, res) => {

    console.log(req.session) // I can't read userId here.
    if (!req.session.userId) {
     
      res.status(400).send({ message : `not authorized` })
    } else {
      
      let result = await Users.findOne({
        where: { userId: req.session.userId },
      })

      res.status(200).send({userId : result.userId, email : result.email, message : 'ok'})
    }
  },
};

//index.js
const express = require('express');
const cors = require('cors');
const session = require('express-session');
const logger = require('morgan');
const fs = require('fs');
const https = require('https');
const usersRouter = require('./routes/user');

const app = express();

const FILL_ME_IN = 'FILL_ME_IN';

const PORT = process.env.PORT || 4000;

app.use(
  session({
    secret: 'practice',
    resave: false,
    saveUninitialized: true,
    cookie: {
      domain: 'localhost',
      path: '/',
      maxAge: 24 * 6 * 60 * 10000,
      sameSite: 'none',
      httpOnly: true,
      secure: true,
    },
  })
);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cors());
/**
 * POST https://localhost:4000/users/login,
 * POST https://localhost:4000/users/logout,
 * GET https://localhost:4000/users/userinfo
 */
app.use('/users', usersRouter);

let server;

if (fs.existsSync("./key.pem") && fs.existsSync("./cert.pem")) {
  server = https
    .createServer(
      {
        key: fs.readFileSync(__dirname + `/` + 'key.pem', 'utf-8'),
        cert: fs.readFileSync(__dirname + `/` + 'cert.pem', 'utf-8'),
      },
      app
    )
    .listen(PORT);
} else {
  server = app.listen(PORT)
}
module.exports = server;

//components/login.js
import axios from 'axios';
import React, { Component } from 'react';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
    };
    this.inputHandler = this.inputHandler.bind(this);
    this.loginRequestHandler = this.loginRequestHandler.bind(this);
  }

  inputHandler(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

  loginRequestHandler() {
  
    let data = { userId : this.state.username, password : this.state.password }

    axios.post('https://localhost:4000/users/login', {
      userId : data.userId,
      password : data.password
    })
    .then(res => {
      
      console.log(res.config.data)
      if (res.data.message === 'ok') {
        this.props.loginHandler()
        
        axios.get('https://localhost:4000/users/userinfo', {
          session : {
            userId : res.config.data.userId
          }    
        })
        .then(res => {
          console.log(res)
          if (res.data.message === 'ok') {
            this.props.setUserInfo(res.data)
          }
        })
        
      }
      
    })

  }
    

  render() {
    return (
      <div className='loginContainer'>
        <div className='inputField'>
          <div>Username</div>
          <input
            name='username'
            onChange={(e) => this.inputHandler(e)}
            value={this.state.username}
            type='text'
          />
        </div>
        <div className='inputField'>
          <div>Password</div>
          <input
            name='password'
            onChange={(e) => this.inputHandler(e)}
            value={this.state.password}
            type='password'
          />
        </div>
        <div className='passwordField'>
          <button onClick={this.loginRequestHandler} className='loginBtn'>
            Login
          </button>
        </div>
      </div>
    );
  }
}

export default Login;

你说“我试过使用session.save()”...是的,你应该在修改后保存会话。

除此之外,您应该在发送结果之前等待会话被保存(即,您应该确保在执行 res.send({ message :"ok" }) 之前会话已经保存)。

最后,回答你的问题:

How to save something in session?

你应该像下面这样:

req.session.userId= userInfo.userId;
        return req.session.save((err) => {
          console.log(err);
          res.send({ message :`ok` })
        });