【问题标题】:Getting [jwt is not defined] while fetching data from MongoDB backend -从 MongoDB 后端获取数据时获取 [jwt is not defined] -
【发布时间】:2020-02-20 21:48:55
【问题描述】:

这个问题不言自明。我正在 mongoDB 数据库中注册/注册用户。它们的注册很好,并且还生成了一个访问令牌 [基于 jwt]。 现在,当我去查询数据库以获取用户列表时,我得到了那个错误 - jwt 未定义。

值得一提的是,我的后端用户也可以有两种类型的角色——基本和管理员。并且只有管理员用户可以通过在 header 中发送 accessToken 作为 Bearer 授权参数来获取所有用户的列表。

我的后端项目结构中有 2 个主要文件,它们使用 jwt.access 方法,例如 jwt.verify 或 jwt.signIn;这些是 server.js 和 userController.js [一个单独的文件,我在其中编写了所有单独的 db 相关方法]。

就我而言,所有必要的包都在我的项目中——express、node、jwa、jws、jsonwebtoken、mongo、mongoose、bcrypt、cors 等。那么有什么问题呢?

我的 route.js -->

const User = require('../models/user.model');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

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


const JWT_SECRET = "$#GR24T4344$#$@#%ETWWTEME%$6";

async function hashPassword(password) {
    return await bcrypt.hash(password, 10);
}


async function validatePassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
}


exports.grantAccess = function (action, resource) {
    return async (req, res, next) => {
        try {
            const permission = roles.can(req.user.role)[action](resource);
            if (!permission.granted) {
                return res.status(401).json({
                    error: "You don't have enough permission to perform this action"
                });
            }
            next();
        } catch (error) {
            next(error);
        }
    }
}


exports.allowIfLoggedin = async (req, res, next) => {
    try {
        const user = res.locals.loggedInUser;
        if (!user)
            return res.status(401).json({
                error: "You need to be logged in to access this route"
            });
        req.user = user;
        next();
    } catch (error) {
        next(error);
    }
}


exports.signup = async (req, res, next) => {
    try {
        const { role, email, password } = req.body;
        const hashedPassword = await hashPassword(password);
        const newUser = new User({ email, password: hashedPassword, role: role || "basic" });
        const accessToken = jwt.sign({ userId: newUser._id }, JWT_SECRET, {
            expiresIn: "1d"
        });
        newUser.accessToken = accessToken;
        await newUser.save();
        res.json({
            data: newUser,
            message: "You have signed up successfully"
        });
    } catch (error) {
        next(error);
    }
}


exports.login = async (req, res, next) => {
    try {
        const { email, password } = req.body;
        const user = await User.findOne({ email });
        if (!user)
            return next(new Error('Email does not exist'));
        const validPassword = await validatePassword(password, user.password);
        if (!validPassword)
            return next(new Error('Password is not correct'));
        const accessToken = jwt.sign({ userId: user._id }, JWT_SECRET, {
            expiresIn: "1d"
        });
        await User.findByIdAndUpdate(user._id, { accessToken });
        res.status(200).json({
            data: { email: user.email, role: user.role },
            accessToken
        });
    } catch (error) {
        next(error);
    }
}


exports.getUsers = async (req, res, next) => {
    const users = await User.find({});
    res.status(200).json({
        data: users
    });
}


exports.getUser = async (req, res, next) => {
    try {
        const userId = req.params.userId;
        const user = await User.findById(userId);
        if (!user)
            return next(new Error('User does not exist'));
        res.status(200).json({
            data: user
        });
    } catch (error) {
        next(error);
    }
}


exports.updateUser = async (req, res, next) => {
    try {
        const { role } = req.body;
        const userId = req.params.userId;
        await User.findByIdAndUpdate(userId, { role });
        const user = await User.findById(userId);
        res.status(200).json({
            data: user
        });
    } catch (error) {
        next(error);
    }
}


exports.deleteUser = async (req, res, next) => {
    try {
        const userId = req.params.userId;
        await User.findByIdAndDelete(userId);
        res.status(200).json({
            data: null,
            message: 'User has been deleted'
        });
    } catch (error) {
        next(error);
    }
}

我的 server.js -->

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 4000;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const playerRoutes = express.Router();
const userRoutes = express.Router();
const userController = require('./controllers/userController');
const user_routes = require('./apiroutes/route');
const app = express();

const JWT_SECRET = "$#GR24T4344$#$@#%ETWWTEME%$6";


const users = "users";

require("dotenv").config({path: __dirname+ '../.env'});



let Player = require('./models/player.model');
let User = require('./models/user.model');

app.use(cors());
app.use(bodyParser.json());

app.use(
    bodyParser.urlencoded({
        extended: false
    })
);

mongoose.connect('mongodb://127.0.0.1:27017/playerDB', function (err, db) {
    if (err)
        throw err;
    db.createCollection(users, function (err, resp) {
        if (err)
            throw err;
        console.log("Collection created!");

    });
}, { useNewUrlParser: true });


const connection = mongoose.connection;

connection.once('open', function () {
    console.log("MongoDB database connection established successfully");
});

..... blablablaaaa


app.use('/playerDB', playerRoutes);


app.use(async (req, res, next) => {

    res.header("Access-Control-Allow-Origin", "*");

    if (req.headers["x-access-token"]) {
        try {
            const accessToken = req.headers["x-access-token"];
            const { userId, exp } = await jwt.verify(accessToken, JWT_SECRET);
            // If token has expired
            if (exp < Date.now().valueOf() / 1000) {
                return res.status(401).json({
                    error: "JWT token has expired, please login to obtain a new one"
                });
            }
            res.locals.loggedInUser = await User.findById(userId);
            next();
        } catch (error) {
            next(error);
        }
    } else {
        next();
    }


});


app.use('/users', user_routes);


app.listen(PORT, function () {
    console.log("Server is running on Port: " + PORT);
});

我希望你能理解我的方法和场景?你能猜到,它可能哪里出错了吗?任何想法? 缺少 npm 包或更重要的东西?

期待关于这个问题的一些提示!好像没办法!

【问题讨论】:

    标签: node.js mongodb express jwt mern


    【解决方案1】:

    您似乎忘记在 server.js 中添加这一行

    const jwt = require('jsonwebtoken');
    

    在注册和登录时,这并没有导致问题,因为对于这些请求,req.headers["x-access-token"] 为空,并且代码没有到达您使用 jwt 的 if 块,但是一个带有此标头的请求(如 getUsers)来了,代码尝试使用 jwt.verify,但由于未导入 jwt,因此出错。

    【讨论】:

    • 嗨@suleymanshah - 让我根据您的建议尝试此编辑。是的,我想这是有道理的,因为在注册期间,不会发送任何标头或令牌。它只是以普通 x-www.-form-urlencoded 格式发送的一些数据......同时,这是我的整个后端源代码的链接 ---> 1drv.ms/u/s!AqxwD_-HSbSQgR3hvA9p0U_voGvS?e=hBY4bg 。您能否看一下,并提出一些可能的编辑或改进建议,以使其更加简化。实际上我打算从前端 ReactJS 应用程序使用/调用这个后端。 CORS 的问题等等......
    • 您好@PrabirChoudhury 不建议在stackoverflow 中将其他问题与原始问题混合,如果我的答案有效,您可以考虑接受它作为答案。如果您在其他帖子中提出其他问题,我会尽力回答。
    • @PrabirChoudhury 这个答案是否解决了您的问题?对于代码审查,您可以使用codereview.stackexchange.com
    • 嗨@suleymanshah 请给我一点时间。我肯定会赞成并“标记为答案”您的评论。我忙于其他一些工作,明天我将尝试您的解决方案;我会回复反馈,
    • @PrabirChoudhury 这是关于此问题的最后一条评论,您需要使用此网址获取用户localhost:4000/users/users
    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-03-17
    • 2021-08-17
    相关资源
    最近更新 更多