收到错误“抛出新的TypeError('JwtStrategy需要密钥或密钥');”

时间:2018-08-07 12:30:51

标签: node.js express npm jwt passport.js

我正在尝试制作Web应用程序,但是在尝试运行几个文件时却出现此错误:

throw new TypeError('JwtStrategy requires a secret or key');
        ^

TypeError: JwtStrategy requires a secret or key
    at new JwtStrategy (/Users/smitsanghvi/Desktop/project/node_modules/passport-jwt/lib/strategy.js:45:15)
    at module.exports.passport (/Users/smitsanghvi/Desktop/project/config/passport.js:12:18)
    at Object.<anonymous> (/Users/smitsanghvi/Desktop/project/index.js:27:29)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
[nodemon] app crashed - waiting for file changes before starting...

我确实将密钥传递给JWS策略,但是仍然出现错误。

passport.js

const jwtStrategy=require('passport-jwt').Strategy;
const ExtractJwt=require('passport-jwt').ExtractJwt;
const mongoose=require('mongoose');
const User=mongoose.model('User');
const key=require('../config/key');

const options={};
options.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey=key.secretOrKey;

module.exports=passport=>{
    passport.use(new jwtStrategy(options,(jwt_checking, done)=>{
        console.log(jwt_checking);
        User.findById(jwt_checking.id).then(user=>{
            if(user){
                return done(null, user);
            }
            return done(null,false);
        })
        .catch(err=>console.log(err))
    }))
}

这是应用程序的主文件。 index.js

const express= require('express');
const mongoose=require('mongoose');
const bodyParser=require('body-parser');
const user=require('./route/api/user');
const userprofile=require('./route/api/userprofile');
const passport=require('passport');
const key=require('./config/key');


const app=express();
//body parser middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//database confid into variable using variable name that I used in key.js of config folder
const database=require('./config/key').mongoURI;

//connecting to mongodb
//.then will print connected if successful
//catch will print error if not
mongoose.connect(database).then(()=>console.log("connected")).catch(err=>console.log(err));

//passport middleware
app.use(passport.initialize());

//passport config
require('./config/passport')(passport);

//gave port number 3000 input to run
//using route to check the output of user.js and userprofile.sj
app.use('/api/user',user);
app.use('/api/userprofile',userprofile);
//will run at 3000 port on localhost
const port=process.env.PORT || 3000;

//it will print this in the terminal after npm start or npm run server 
//this will print the consr port in conlsole
app.listen(port,()=> console.log('port is:: ${port}'));

user.js

const express=require('express');
const router=express.Router();
const bcrypt=require('bcryptjs');
const user=require('../../model/User');
const jwt=require('jsonwebtoken');
const key=require('../../config/key');
const passport=require('passport');


router.get('/demo',(req,res)=>res.json({output:"user"}));

//creating route for regsiteration
//using postman it will get this 
router.post('/register',(req,res)=>{
    //find if email exists or not.
    user.findOne({email: req.body.email}).then(user=>{
        if(user){
            return res.status(400).json({email:"email is already registered"});
        }
        else{
            //else will creaete new user
            const newUser=new User({
                name: req.body.name,
                email:req.body.email,
                password:req.body.password
            })

            //generate salt and hash pass with salt
            bcrypt.genSalt(10,(err,salt)=>{
                //hashing password
                bcrypt.hash(newUser.password, salt, (err,hash)=>{
                    if(err) throw err;
                    //after setting hash password will save it
                    newUser.password=hash;
                    newUser.save()
                    //then will return through json
                    .then(user=>res.json(user))

                })
            })
        }
    })
});

//returning jason web token
router.post('/login',(req,res)=>{
    const email=req.body.email;
    const password=req.body.password;
    //will find user by email
    //will check if email and pass is present in mlab db
    User.findOne({email}).then(user=>{
        if(!user){
            return res.status(404).json({email:"user doesnt exist"});
    }
    //
            bcrypt.compare(password,user.password).then(isMatch=>{
                if(isMatch){
                    //user matched
                    //checking will check the details of user
                    const checking={id: user.id,name:user.name}
                    //
                    jwt.sign(checking,key.key1,(err,token)=>{
                        res.json({
                            access:true,
                            token:token
                        })
                    });

            }
                    else{
                    return res.status(400).json({password:"password incorrect"});
        }

            })

    })
})

router.get(
    '/current',
    passport.authenticate('jwt',{session:false}), 
    (req,res)=>{
    res.json({
        id:req.user.id,
        name:req.user.name,
        email:req.user.email


})
    }
)


module.exports=router;

所有软件包均已正确安装。我无法解决此问题,最终应用程序崩溃了。

1 个答案:

答案 0 :(得分:0)

const options={}; options.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken(); options.secretOrKey=key.secretOrKey;

您可以将“ 选项”变量名称更改为新的变量名称,因为“ 选项”是由您的编辑器定义的。只需更改名称,它就会起作用。我也遇到了同样的问题。我希望这种方式可以帮助您解决问题。