[英]how to send error message to client?
I am using passport with local strategy .but I want to send message and status when credential
is not match or ( user is not exit is DB
)我正在使用带有本地策略的护照。但是我想在
credential
不匹配或( user is not exit is DB
)时发送消息和状态
here is code这是代码
router.js路由器.js
const passport = require('passport');
const passportConfig = require('../passport')
const passportSignIn = passport.authenticate('local', { session: false });
router.route('/login',)
.post(passportSignIn,controller.login)
on controller file在控制器文件上
login: async (req, res, next) => {
console.log(req.body);
res.json({status:200})
}
passport.js护照.js
passport.use(new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {
const user = await db.User.findOne({where: {email: email}});
if (!user) {
return done(null, false,{message:"No user exit"});
}
const isMatch = await bcrypt.compare(password, user.dataValues.password);
console.log(isMatch, 'isMatch');
if (!isMatch) {
return done(null, false);
}
// Otherwise, return the user
done(null, user);
}))
Client code客户端代码
when user click on login
button it goes to /login
path first it goes to passportSignIn
function or below function.当用户单击
login
按钮时,它首先转到/login
路径,然后转到passportSignIn
函数或下面的函数。
`new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {`
now if user not found I want to send this message on the client as the response ("No user exit")现在,如果找不到用户,我想在客户端上发送此消息作为响应(“无用户退出”)
return done(null, false,{message:"No user exit"});
You have to update your login controller, like so:您必须更新您的登录控制器,如下所示:
login: (req, res, next) => {
console.log(req.body);
passport.authenticate('yourStrategy', function(err, user, info) {
if (err) {
return res.status(500).json("Internal Server Error");
}
if (!user) {
// This 'info' variable below would be - { message: "No user exit" }
// as you passed in the done() callback as the third param
return res.status(404).json(info.message);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.