Я кодирую Nodejs и получаю эту проблему с помощью функции аутентификации, такой как эта. Все проблемы происходят из функции User.getUser и происходят из findOne. Но я не знаю, как это исправить. Более того, у меня есть код с Mongoose и JWT. Ошибка: [введите описание изображения здесь] [1] Как я могу исправить с помощью функции findOne. Спасибо.
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const User=require('../models/UserModels');
const bcrypt=require('bcrypt');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
//var passport = require('../server1/database/config/passport');
var passportJWT = require('passport-jwt');
var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;
var jwtOptions = {};
var jwt = require('jsonwebtoken');
var config=require('./config/main');
const randtoken = require('rand-token');
//const database=require('../database/index.js')
//const blockchain = require("../blockchain/index");
// jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
jwtOptions.secretOrKey = 'thisisanexamplesecret';
const PORT = process.env.PORT || 3000;
const db = mongoose.connection;
// app.set("view engine", "ejs");
// app.set("views", "./views");
// app.use(express.static("public"));
// app.use(morgan("dev"));
// app.use(bodyParser.json());
// app.use(cookieParser());
// app.use(bodyParser.urlencoded({ extended: true }));
dotenv.config();
//connect to db
mongoose.set('useCreateIndex', true);
mongoose.connect(process.env.DB_URL,{ useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("Success."));
db.on('error',(err)=>{
console.log("Error: "+ err.message);
});
// function thêm mới 1 user
const createUser = async({email, password,card_name,role}) => {
return await User.create({ email, password,card_name,role });
};
// function lấy ra danh sách users
const Users = async() => {
return await User.find();
};
// function lấy ra 1 users
const getUser = async obj => {
return await User.findOne({
where: obj,
});
};
function Authentication(req,res,onSuccess){
var {email,password}=req.body;
var usermain=User.getUser({email:req.body.email},function(err,result,fields){
if(err){
onSuccess({success:false,error:err});
return;
}
if(!result[0]){
onSuccess({ success: false, error: "Authentication failed. User not found." });
return;
}
else{
if(email&&password){
// we get the user with the name and save the resolved promise returned
var user=User.getUser({email:req.body.email})
if(!user){
res.status(401).json({msg:'No such user found', user});
onSuccess({ success: false, error: "Authentication failed. User not found." });
return;
}
hash=bcrypt.hash(''+password,10);
if(bcrypt.compare(hash,user.password)){
// from now on we’ll identify the user by the id and the id is
// the only personalized value that goes into our token
var payload={email:user.email};
var token=jwt.sign(payload,jwtOptions.secretOrKey);
res.json({msg: 'ok', token: token});
onSuccess({ success: true, token: token});
return;
}else{
res.status(401).json({ msg: 'Password is incorrect' });
onSuccess({ success: false, error: "Authentication failed. User not found." });
return;
}
}
}
})
}
module.exports={
Authentication
};```
[1]: https://i.stack.imgur.com/94EI0.png