如何解决authjs上的用户未定义错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何解决authjs上的用户未定义错误相关的知识,希望对你有一定的参考价值。
使用护照LocalStrategy和passport-jwt创建Web令牌,但在auth.js **** 401未经授权的****(if (!user) { return res.json(401, { error: 'message' });}
)如何解决此问题时,卡在用户未定义的错误上
auth.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
var LocalStrategy = require('passport-local').Strategy;
var jwt = require('jsonwebtoken');
var passport = require('passport');
/* User Model*/
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* POST login. */
router.post('/login', function (req, res, next) {
passport.authenticate('local', {session: false}, (err, user, info) => {
if (err) { return next(err) }
if (!user) { return res.json(401, { error: 'message' });}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
const token = jwt.sign(user, 'your_jwt_secret');
return res.json({user, token});
});
})(req, res, next);
});
module.exports = router;
passport.js
var passport = require('passport');
/* User Model*/
var mongoose = require('mongoose');
var User = mongoose.model('User');
var localStrategy = require('passport-local').Strategy;
var passportJWT = require("passport-jwt");
var JWTStrategy = passportJWT.Strategy;
var ExtractJWT = passportJWT.ExtractJwt;
passport.use(new localStrategy(
function (email, password, cb) {
return User.findOne({email, password})
.then(user => {
if (!user) {
return cb(null, false, {message: 'Incorrect email or password.'});
}
return cb(null, user, {
message: 'Logged In Successfully'
});
})
.catch(err => {
return cb(err);
});
}
));
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'your_jwt_secret'
},
function (jwtPayload, cb) {
return User.findById(jwtPayload.id)
.then(user => {
return cb(null, user);
})
.catch(err => {
return cb(err);
});
}
));
答案
假设用户是一个对象:
if (user && Object.keys(user).length) {
return res.json(401, { error: 'message' });
}
以上是关于如何解决authjs上的用户未定义错误的主要内容,如果未能解决你的问题,请参考以下文章
ios - Heroku 和 MongoDb 上的自定义解析服务器错误 3080:JSON 文本没有以数组或对象开头,并且允许未设置片段的选项
错误:E/RecyclerView:未连接适配器;跳过片段上的布局