如何使用邮递员在nodejs中测试快速会话类型的会话?

How to test express-session type sessions in nodejs using postman?

我有一个 nodejs 后端,其中包含使用 express-session npm 模块创建的会话。我想使用邮递员测试会话。

我想要的是,只有当用户当前在会话中时,才允许他通过 /getUsers 路由访问用户列表。但是发生的事情是当我使用邮递员测试后端时,即使在用户登录后也无法使用 /getUsers 路由访问用户。这跟邮递员有关吗?

这是我的 app.js

const express = require("express");
const app = express();
const authRoutes=require('./routes/auth');
const mongoose=require('mongoose');
const bodyParser = require("body-parser");
require("dotenv").config();
const nodemailer = require("nodemailer");
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const cors = require('cors');

app.use(cors({
    origin:['http://localhost:8080'],
    methods:['GET','POST'],
    credentials: true // enable set cookie
}));

app.use(
  // Creates a session middleware with given options.
  session({
    name: 'sid',
    saveUninitialized: false,
    resave: false,
    secret: 'sssh, quiet! it\'s a secret!',
    cookie: {
      httpOnly: true,
      maxAge: 1000 * 60 * 60 * 2,      
      sameSite: true,
      secure: true
    }
  })
);


mongoose.connect(process.env.LOCAL_MONGO_URI,{useNewUrlParser:true},function (err) {

  if (err) throw err
  console.log("Connected to local mongo db database");

});

app.get("/",(req,res)=> {console.log("A request was made to /")
    console.log("/GET called"); 
});

app.use(bodyParser.json());

app.use("/",authRoutes);

const port = process.env.PORT||8080
app.listen(port,()=> {
    console.log("Hello world");
})

这是我的 routes/auth.js:

const express = require("express");
const {
    signup,login,verifyemail,requiresLogin,getUsers,logout
} = require("../handler/auth")

const router = express.Router();

router.post("/signup",signup);

router.post("/login",login);

router.get("/verifyemail/:token",verifyemail);

router.get("/getUsers",requiresLogin,getUsers);

router.get("/getUsers",requiresLogin,getUsers);

router.get("/logout",requiresLogin,logout);

module.exports=router;

这是我的 handler/auth.js

const User =  require("../models/user");
const bcrypt = require('bcrypt');
const crypto = require('crypto');

exports.signup = async (req, res) => {

    const email = req.body.email;

    User.findOne({email},function(err,user){    
        if(err) return res.status(500).json({message:err.message});
        else if(user) return res.status(403).json({"message":"User exists"});

        const password = req.body.password;
        const name = req.body.name;

        bcrypt.hash(password, 10)
        .then(async function(hashed_password) {

            const user = await new User({email,name,hashed_password});
            user.emailVerificationToken = crypto.randomBytes(20).toString('hex');
            user.emailVerificationTokenExpires = Date.now() + 3600000*24; 
            await user.save(function(err) {

            if(!err) {

                const resetURL = `http://${req.headers.host}/verifyemail/${user.emailVerificationToken}`;
                const sgMail = require('@sendgrid/mail');

                sgMail.setApiKey(process.env.SENDGRID_API_KEY); 
                const msg = {
                    from: 'admin@pinclone.com',
                    to: email,
                    subject: 'Email verification link',
                    html: `Verify your email <a href="${resetURL}">here</a> to login to your account`,
                };
                sgMail.send(msg);

                return res.json({message:"verify email address to login"}); 
            } 
                return res.status(500).send({ message: err.message });
            });
        })
        .catch(function(error){
            res.status(500).send({message:error.message});
        });
    }); 
};

exports.login = (req,res) => {
    const email = req.body.email;
    const password = req.body.password;

    User.findOne({email},function(err,user) {
        if(err) return res.status(500).json({message:err.message});

        if(!user) return res.status(403).json({"message":"User does not exists"});

        bcrypt.compare(password,user.hashed_password,(err,result) => {
            if(result) {
                if(user.isVerified)
                    return res.status(200).json({"message":"successfully logged in"});
                else
                    return res.status(403).json({"message":"user is not verified"});
            }
            else return res.status(403).json({message: "email address password do not match"});
        });

    });
};

exports.verifyemail = async (req,res) => {

    User.findOneAndUpdate({emailVerificationToken: req.params.token,emailVerificationTokenExpires: { $gt: Date.now() }}, {$set:{isVerified:true}}, {new: true}, (err, user) => {
    if (err) {
        res.status(403).send({message:"Link invalid or expired"});
        // res.status(500).send({message:"Something wrong when updating data!"});
    }
    if(user) {
        res.status(200).send({"message":"email verification successful you can login now!"});
    }
    }); 
};  

exports.requiresLogin = (req, res, next) => {
  if (req.cookies.sid) {
    return next();
  } else {
    var err = new Error('You must be logged in to view this page.');
    err.status = 401;
    return next(err);
  }
};

exports.logout = (req, res) => {
    res.clearCookie('sid');
    res.send("logout success");
};

exports.getUsers = (req,res) => {
    User.find({},function(err,users){
        res.send(users);
    });
};

您可以使用密钥在选项卡 Header 中设置 session。 您可以阅读 https://www.toolsqa.com/postman/sessions-in-postman/ 了解更多详情。

您应该阅读 How to use Sessions in Postman? 部分。