这是代码
createcar
我正在尝试在nodejs和猫鼬中进行认证
当用户按下登录时,当控件进入登录功能时,将使用电子邮件和密码的主体来调用api,它将检查数据库中是否存在电子邮件,并检查密码是否正确>
在这里我得到的错误是 TypeError:无法读取未定义的属性'0'
显示错误消息
const {validationResult} = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
exports.login = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
let loadedUser;
User.findOne({email:email})
.then(user => {
if(user){
loadedUser = user;
return bcrypt.compare(password, user.password);
} else{
const error = new Error('EMAILID_NOT_FOUND');
error.statusCode = 401;
throw error;
}
})
.then(
isEqual => {
console.log(isEqual);
if(!isEqual){
const error = new Error('WRONG_PASSWORD');
console.log(error)
error.statusCode = 401;
throw error;
}
const token = jwt.sign({
email: loadedUser.email,
userId: loadedUser._id.toString()
},'somesecrekey',{expiresIn:'7d'}
);
res.status(200).json({
token: token,
userId: loadedUser._id.toString()
});
})
.catch(err => {
if(!err.statusCode){
err.statusCode =500;
}
next(err);
});
};
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const eventRoutes = require('./routes/eventRouter');
const companyRoutes = require('./routes/companyRouter');
const authrouter = require('./routes/authrouter');
const app = express();
// app.use(bodyparser.urlencoded());
app.use(bodyparser.json()); //application/json
app.use('/images',express.static(path.join(__dirname, 'images')));
app.use((req, res, next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH,
DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
})
app.use('/auth', authrouter);
app.use('/event', eventRoutes);
app.use('/company',companyRoutes);
app.use((error, req, res, next)=>{
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
const errmsg = data[0].msg;
res.status(status).json({ error: message, errmsg: errmsg, data: data });
});
mongoose.connect('mongodb://localhost:27017/scope').then(result=>{
app.listen(8080)
}).catch(err => console.log(err));
请帮助 谢谢