为什么 get/post 方法会抛出未授权 (401) 错误?
Why get/post methods throws Unauthorized (401) ERR?
我有一个用于登录和注册的项目,注册部分我在其中使用了 Express-Validator,而登录部分我使用的是 Passport.JS 但是,但是当我在 app.js 中添加护照 js 减速时,它会抛出未经授权的错误 401。
Postman (Body)
app.js(导致问题的行)
These two lines of code causes this poblem, when i Comment Them it works but in this case i will not able to using Passport.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;
index.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;
package.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"
}
}
您只需要将授权中间件应用到您的私有路由。
Thank you all, answer :
app.js ( Two lines causes the problem) have to be:
来自
//passport
app.use(passport.authorize());
app.use(passport.session());
到
//passport
app.use(passport.initialize());
app.use(passport.session());
我有一个用于登录和注册的项目,注册部分我在其中使用了 Express-Validator,而登录部分我使用的是 Passport.JS 但是,但是当我在 app.js 中添加护照 js 减速时,它会抛出未经授权的错误 401。
Postman (Body)
app.js(导致问题的行)
These two lines of code causes this poblem, when i Comment Them it works but in this case i will not able to using Passport.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;
index.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;
package.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"
}
}
您只需要将授权中间件应用到您的私有路由。
Thank you all, answer :
app.js ( Two lines causes the problem) have to be:
来自
//passport
app.use(passport.authorize());
app.use(passport.session());
到
//passport
app.use(passport.initialize());
app.use(passport.session());