简体   繁体   中英

Cannot find module 'jsonwebtoken' Node.js

i am trying to set up an user level authentication using node.js, so i go and do npm install -g jsonwebtoken --save. However, i run into problems when i use require('jsonwebtoken');and try to compile my code, it gives me the error described above in the title. Now, for some reason, when i uninstall the JWT and try to run my code without it, it compiles, but obviously it doesn't work. I tried re-installing it, still no success. My npm --version 6.3.0

node --version v11.1.0

npm install -g jsonwebtoken --save + jsonwebtoken@8.4.0

code:

'use strict';

require('jsonwebtoken');

exports.generateToken = async (data) => {
    return jwt.sign(data, global.SALT_KEY, { expiresIn: '1d' });
}

exports.decodeToken = async (token) => {
    var data = await jwt.verify(token, global.SALT_KEY);
    return data;
}

exports.authorize = function (req, res, next) {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (!token) {
        res.status(401).json({
            message: 'Acesso Restrito'
        });
    } else {
        jwt.verify(token, global.SALT_KEY, function (error, decoded) {
            if (error) {
                res.status(401).json({
                    message: 'Token Inválido'
                });
            } else {
                next();
            }
        });
    }
};

exports.isAdmin = function (req, res, next) {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (!token) {
        res.status(401).json({
            message: 'Token Inválido'
        });
    } else {
        jwt.verify(token, global.SALT_KEY, function (error, decoded) {
            if (error) {
                res.status(401).json({
                    message: 'Token Inválido'
                });
            } else {
                if (decoded.roles.includes('admin')) {
                    next();
                } else {
                    res.status(403).json({
                        message: 'Esta funcionalidade é restrita para administradores'
                    });
                }
            }
        });
    }
};

在此处输入图像描述

Instead of installing it globally with the -g tag, just install it locally in your current working directory. Just do:

npm install jsonwebtoken --save

This is because you can not directly require a globally installed package in your code.

Just Do Simple:

npm install jsonwebtoken

You are installing it system level node_modules folder. So it is not available in project level node_modules folder. Please remove - g from npm install command

npm install - - save jsonwebtoken

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM