У меня есть проект для входа и регистрации, подпишите часть, которую я использовал Express -Validator , в то время как часть входа я использую Паспорт. JS но, но когда я добавляю паспорт js замедление в приложении. js выдает Несанкционированную ошибку 401.
Почтальон (Тело)
приложение. js (строки, вызывающие проблему)
Эти две строки кода вызывают эту проблему, когда i Комментировать это работает, но в этом случае я не смогу использовать Паспорт. js
//passport
app.use(passport.authorize());
app.use(passport.session());
app. js (Все строки кода)
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose = require('mongoose');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//session
app.use(session({
secret : 'Thisis a big secret :-)',
saveUninitialized: false,
resave: false
}));
//flash
app.use(flash())
//passport
app.use(passport.authorize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
////////////////////// DB connecting /////////////////////////////
mongoose.connect('mongodb://localhost/product', { useUnifiedTopology: true, useNewUrlParser: true }, (err, res)=>{
(err)?console.log('ERR While connecting to DB => ' + err):console.log('DB is connected successfully...');
});
//////////////////////////////////////////////////////////////////
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
индекс. js
var express = require('express');
var router = express.Router();
const product = require('../model/product');
const users = require('../model/users');
const { check, validationResult } = require('express-validator');
const passport = require('passport');
/* GET home page. */
router.get('/', function(req, res, next) {
product.find({}, (err, doc)=>{
if(err){
console.log('ERR while searching in DB =>' + err);
}
var grid = 3;
var arr = [];
for(var i = 0; i<doc.length; i+=grid){
arr.push(doc.slice(i , i+grid));
}
console.log(arr)
res.render('index', { title: 'Express', product : arr });
})
});
/* router.post('/', function(req, res, next) {
}); */
//GET login
router.get('/login', (req, res, next)=>{
res.render('login')
});
router.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/',
failureFlash: true,
}));
router.get('/signup', function (req, res, next){
const msg = req.flash('error')
res.render('signup', {messages : msg});
});
router.post('/signup', [
// password must be at least 5 chars long
check('password').isLength({ min: 5 }).withMessage('Please enter Password with more than 5 letters!'),
// username must be an email
check('username').not().isNumeric().withMessage('please fill username with STRING only'),
// password must be at least 5 chars long
check('email').not().isEmpty().withMessage('please fill email with STRING only'),
check('email').not().isEmail().withMessage('please enter valid email'),
// password must be at least 5 chars long
check('password').not().isEmpty().withMessage('Please fill password fie'),
check('repassword').custom((val, {req})=>{
if(val !== req.body.password){
throw new Error('Password is not equal to confirm password');
}
return true;
})
],
function (req, res, next){
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
var validationMessage = [];
for(var i = 0; i<errors.errors.length; i++){
validationMessage.push(errors.errors[i].msg);
}
req.flash('error', validationMessage)
res.redirect('signup')
}
const newUser = new users({
username : req.body.username,
password : new users().hashPassword(req.body.password)
});
users.findOne({username : req.body.username}, (err, doc)=>{
if(err){
console.log('ERR while getting username =>' + err);
return ;
}
if(doc){
console.log('this email is already exist')
}
});
newUser.save((err, doc)=>{
if(!err){
console.log('err')
}else{
console.log('ERR in saving users =>' + err);
}
})
});
module.exports = router;
пакет. json
{
"name": "market",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"bcrypt": "^4.0.0",
"connect-flash": "^0.1.1",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"express-session": "^1.17.0",
"express-validator": "^6.4.0",
"hbs": "~4.0.4",
"http-errors": "~1.6.3",
"mongoose": "^5.9.2",
"morgan": "~1.9.1",
"nodemon": "^2.0.2",
"passport": "^0.4.1",
"passport-local": "^1.0.0"
}
}