Из-за недостатка опыта, а также из-за того, что я получаю биты и кусочки кода из разных источников, я не могу точно определить, почему я получаю Reference Error: User is not defined.
. Ошибка возникает при вводе / отправке информации о новом пользователе, поэтому БД никогда не заполняется, и я получаю ошибку ниже.
Ошибка
ReferenceError: users is not defined
at /Desktop/REST API/server.js:50:17
at Layer.handle [as handle_request] (/Desktop/REST API/node_modules/express/lib/router/layer.js:95:5)
at next (/REST API/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/REST API/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Desktop/REST API/node_modules/express/lib/router/layer.js:95:5)
at /Desktop/REST API/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Desktop/REST API/node_modules/express/lib/router/index.js:335:12)
at next (/Desktop/REST API/node_modules/express/lib/router/index.js:275:10)
at /Desktop/REST API/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Desktop/REST API/node_modules/raw-body/index.js:224:16)
at done (/Desktop/REST API/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Desktop/REST API/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1201:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Вот мой код
маршруты пользователей. js
const express = require('express')
const router = express.Router()
const Users = require('../models/users')
router.get('/register', (req, res) => {
res.render('register.hbs', {
pageTitle: 'register'
});
});
router.get('/login', (req, res) => {
res.render('login.hbs', {
pageTitle: 'login'
});
});
router.post('/register', (req, res) => {
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var password = req.body.password;
//validations
req.checkBody('firstName', 'Your First Name is Required').notEmpty();
req.checkBody('lastName', 'Your Last Name is Required').notEmpty();
req.checkBody('email', 'A valide email is required').notEmpty();
req.checkBody('password', 'An Account Passowrd Is Required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('register', {
errors:errors
});
} else {
var newUser = new newUser({
firstName: firstName,
lastName: lastName,
email: email,
password: password,
});
newUser.createUser(newUser, function(err, user) {
if(err) throw(err);
console.log(user);
});
req.flash('success_message', "You are now registered!");
res.redirect('/login');
}
});
passport.use(new LocalStrategy({
email: 'email'
},
function(email, password, done){
User.getUserByEmail(email, function(err, user){
if(err) throw err;
if(!user){
return done(null, false {message: 'Unknown Email Address'});
}
User.comparePassword(password, user.password, function(err, ismatch){
if(err) throw err:
if(ismatch){
return done (null, user);
} else {
return done(null, false, {message: 'Invalid Passowrd'});
}
});
});
}));
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(funtion(id, done){
User.getUserByID(id, function(err, user) {
done(err, user)
});
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
successFlash: 'Welcome'
failureFlash: 'Invalid Email or Passowrd!'
}), function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res) {
req.logout();
req.flash('Success_message', 'You are now logged out!')
res.redirect('/');
});
module.exports = router
модель: пользователи. js
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
var articlesSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
password: String,
permissionLevel: Number,
created: Date},
{ collection: 'Users'});
const User = module.exports = mongoose.model('Users', userSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByEmail = function(email, callback){
var query = {email: email};
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback){
user.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback) {
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch)
});
}
Наконец-то мой сервер. js, где, как я полагаю, находятся проблемы:
require('dotenv').config()
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true , useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const articlesRouter = require('./routes/articles')
app.use('/articles', articlesRouter)
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/login', (req, res) => {
res.render('login.ejs')
})
app.post('/login', (req, res) => {
})
app.get('/register', (req, res) => {
res.render('register.ejs')
})
app.post('/register',(req, res) => {
try{
const hashedPassword = bcrypt.hash(req.body.password, 10)
users.push({
firstName:req.body.firstName,
lastName:req.body.lastName,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
} catch {
res.redirect('/register')
}
console.log(users)
})
app.listen(3000, () => console.log('Server Started'))
Любая помощь, будет принята с благодарностью.