jsonwebtoken错误未指定默认引擎且未提供扩展名

时间:2018-08-09 11:22:06

标签: node.js express jwt passport.js react-native-android

嗨,我正在尝试使用通行证js和jsonwebtoken进行我的android应用程序的身份验证,但是当我尝试生成令牌作为用户登录名并使用邮递员测试api时,响应错误:

  

未指定默认引擎,也未提供扩展名。       在新视图(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ view.js:61:11)       在Function.render(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ application.js:570:12)       在ServerResponse.render(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ response.js:1008:7)       在C:\ newApp \ awesomeProject \ server \ app.js:68:9       在Layer.handle_error(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ layer.js:71:5)       在trim_prefix(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:315:13)       在C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:284:7       在Function.process_params(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:335:12)       在下一个(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:275:10)       在Layer.handle_error(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ layer.js:67:12)       在trim_prefix(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:315:13)       在C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:284:7       在Function.process_params(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:335:12)       在下一个(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:275:10)       在Layer.handle_error(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ layer.js:67:12)       在trim_prefix(C:\ newApp \ awesomeProject \ node_modules \ express \ lib \ router \ index.js:315:13)

这是我的代码:

routes.js

var express  = require('express'),
    router   = express.Router(),
    passport = require('passport');
    todo     = require('./controller/todo.js'),
    user     = require('./controller/user.js');

router.get('/', user.isLoggedIn, user.userLogin);

router.get('/loginFailure', function(req, res, next){
	res.send("Invalid username or password");
})

router.get('/login', user.isLoggedOut);

//AUTH routes
router.post('/registration', user.userRegister);
router.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/loginFailure' }));
router.get('/logout', user.userLogout)

//Application routes
router.post('/createUser', user.createUser);
router.get('/getUsers', user.getUsers);
router.get('/getUser/:id', user.getUser)
router.put('/updateUser/:id', user.updateUser);
router.delete('/deleteUser/:id', user.deleteUser);

router.get('/todoList', todo.getTodoList);
router.get('/detail/:id', todo.getTodo);
router.post('/createTodo', todo.createTodo);
router.put('/updateTodo/:id', todo.updateTodo);
router.delete('/deleteTodo/:id', todo.deleteTodo);

module.exports = router;

以及控制器中的user.js:

const bodyParser = require('body-parser'),
      userModel  = require('../model/User.js'),
      provider   = require('../provider/provider');

var passport              = require('passport');
    // localStrategy         = require('passport-local'),
    // passportLocalMongoose = require('passport-local-mongoose'),
    // expressSession        = require('express-session');


module.exports.userRegister = function(req, res, next){
  var Content = {
      "username": req.body.username,
      "password": req.body.password
   }

  var validate = provider.validateParam(Content);

  if (!validate.status){
    var objReturns = provider.setDataReturn(false, 'parram is null', validate.message);
        res.json(objReturns);
  } else {
      userModel.register(new userModel({ "username": req.body.username }), req.body.password, (err, contentCreated) => {
      if (err) {
                  var objReturns = provider.setDataReturn(false, 'registered failed', err);
                  res.json(objReturns);
          } else {
                  passport.authenticate("local")(req, res, function(){
                    console.log("authenticate works");
                  })
                  var objReturns = provider.setDataReturn(true, 'registered successful', contentCreated);
                  res.json(objReturns);
          }
      })
  }
}

module.exports.userLogin = function(req, res, next){
  if(req.user){
    var objReturns = provider.setDataReturn(true, 'login successful', req.user);
    res.json(objReturns);
  } else {
    var objReturns = provider.setDataReturn(false, 'log in failed', req.user);
    res.json(objReturns);
  }
}
  
module.exports.userLogout = function(req, res, next){
  req.logout();
  res.redirect('/login');
}

module.exports.isLoggedOut = function(req, res, next){
  if(!req.user){
    var objReturns = provider.setDataReturn(true, 'logout successful', req.user);
    res.json(objReturns);
  } else {
    var objReturns = provider.setDataReturn(false, 'logout failed', req.user);
    res.json(objReturns);
  }
}

module.exports.isLoggedIn = function(req, res, next){
  if(req.isAuthenticated()){
    return next();
  } 
  console.log("isLoggedIn triggered, did not authenticate");
    res.redirect('/login');
}

module.exports.createUser = function(req, res, next){
	var Content = {
   	  "username": req.body.username,
      "password": req.body.password
   }

   //console.log(Content);
  var validate = provider.validateParam(Content);

 	if (!validate.status){
 		var objReturns = provider.setDataReturn(false, 'parram is null', validate.message);
       	res.json(objReturns);
	} else {
  		userModel.createUser(Content, (err, contentCreated) => {
			if (err) {
	                var objReturns = provider.setDataReturn(false, 'created failed', err);
	                res.json(objReturns);
	        } else {
	                var objReturns = provider.setDataReturn(true, 'created successful', contentCreated);
	                res.json(objReturns);
	        }
  		})
	}
}

module.exports.getUsers = function(req, res, next) {
    
	userModel.getUsers((err, userFound) => {
  		if (err) {
            var objReturns = provider.setDataReturn(false, err + '', err);
            res.json(objReturns);
        } else {
            var objReturns = provider.setDataReturn(true, 'successful', userFound);
            res.json(objReturns);
        }
    });
}

//Get todo by Id
module.exports.getUser = function(req, res, next) {
  var Content = {
      "_id": req.params.id
   };

   
  var validate = provider.validateParam(Content);

  if (!validate.status){
    var objReturns = provider.setDataReturn(false, 'parram is null', validate.message);
        res.json(objReturns);
  } else {
      userModel.getUserById(Content, (err, userFound) => {
      if (err) {
                  var objReturns = provider.setDataReturn(false, err+ '', err);
                  res.json(objReturns);
          } else {
                  var objReturns = provider.setDataReturn(true, 'successful', userFound);
                  res.json(objReturns);
          }
      })
  }
}

...
   //Update User and delete User code below

这是provider.js文件:

const config = require('../config.js'); //ket noi db
const jwt = require('jsonwebtoken');

module.exports.deletePropertyOBject = function(myObject, property) {
    var obj = myObject;
    delete obj[property];
    // console.log(obj);
    return obj;
}

module.exports.setDataReturn = function(status = '', message = '', data = {}) {


    *// const token = jwt.sign(data, 'superSecret', { expiresIn: config.tokenTime });*
     
    IF I UNCOMMENTED THIS IT WOULD REPORT THE ERROR

    var objReturn = {
        "success": status,
        "message": message,
        'data': data,
    };
    return objReturn;
}

module.exports.createToken = function(user) {
        var token = jwt.sign(user, 'superSecret', { expiresIn: config.tokenTime });
        return token;
}
    //xac thuc token
module.exports.verifyToken = function(req, res, next) {
    next();
    // var bearerHeader = req.headers['authorization'];;

    // if (typeof(bearerHeader) !== 'undefined') {
    //     var bearer = bearerHeader.split(' ');
    //     var bearerToken = bearer[0];
    //     jwt.verify(bearerToken, 'superSecret', function(err, authData) {
    //         if (err) {
    //             res.sendStatus(403);
    //         } else {
    //             next();
    //         }
    //     });
    // } else {
    //     res.sendStatus(403);
    // }
}

module.exports.validateParam = function(obj) {
    var output = {
        status: true,
        message: []
    };

    for (let [key, value] of Object.entries(obj)) {

        if (typeof value === "undefined") {
            output.message.push(key);
            output.status = false;
        }
    }
    return output;
}

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

req.user是一个猫鼬对象,因此当在jwt.sign()中使用它时,显然会引起问题,我们必须将该对象转换为json,用use.toJSON(替换jwt.sign(user)中的用户)。这样可以解决问题