Получение 3 выходных данных для одного и того же запроса на вход

#node.js #express #mongoose #passport.js #passport-local

Вопрос:

Я пытаюсь использовать passport, но не могу понять, почему мой вывод отображается 3 раза. В пользовательском маршрутизаторе, приведенном ниже, строка console.log('USER POST FOR SIGNIN', user); дает вывод 3 раза для одного и того же запроса на вход, и хотя postman показывает StatusCode = 200, консоль показывает, что 500 POST /users/signin 500 304.743 ms - 57 Может мне помочь .

 const passport = require('passport');
const LocalStratergy = require('passport-local').Strategy;
const User = require('./models/UserSchema');
const isValidPassword = require('./lib/passwordsUtils').isValidPassword;

const customFields ={
    usernameField:'email',
    passwordField:'password'
};

const verifyCallback = (username,password,done) => {
    // console.log('USERNAME',username,'PASSWORD',password);
    User.findOne({email:username})
    .then((user) =>{
        // console.log('verifyCallback',user);
        if(!user) return done(null,false);  

        const isValid = isValidPassword(password,user.password.hash,user.password.salt);
        // console.log('IsValid ',isValid);
        if(isValid) done(null,true);
        done(null,false);
    })
    .catch(err => done(err))
};

const stratergy = new LocalStratergy(customFields,verifyCallback);
passport.use(stratergy);

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
  
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
});
});
 

мой пользовательский маршрутизатор

 
userRouter.post('/signin',(req,res,next)  =>{
 passport.authenticate('local',(err,user,info) =>{
  console.log('USER POST FOR SIGNIN',user);
  if(err) return next(err);

  if(!user){
    res.statusCode = 401;
    res.setHeader('Content-Type','application/json');
    res.json({success:false,status:'Login Unsuccessful!',err:info });   
  }
  res.statusCode = 200;
  res.setHeader('Content-Type','application/json');
  res.json({success:true,status:'Login Successful!',user:user });   
})(req, res, next);
});

 

мой вывод

 Connected to database
USER POST FOR SIGNIN true
USER POST FOR SIGNIN false    
USER POST FOR SIGNIN undefined

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibresponse.js:767:10)       
    at ServerResponse.send (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibresponse.js:170:12)
    at done (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibresponse.js:1004:10)
    at Object.exports.renderFile (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesjadelibindex.js:374:12)
    at View.exports.__express [as engine] (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesjadelibindex.js:417:11)
    at View.render (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibview.js:135:8)
    at tryRender (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibapplication.js:640:10)
    at Function.render (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibapplication.js:592:3)
    at ServerResponse.render (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibresponse.js:1008:7)       
    at D:ProjectsWeb_developmentMERN__PROJECTStinder-backendapp.js:74:7
    at Layer.handle_error (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibrouterlayer.js:71:5)        
    at trim_prefix (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibrouterindex.js:315:13)
    at D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibrouterindex.js:284:7
    at Function.process_params (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibrouterindex.js:335:12) 
    at next (D:ProjectsWeb_developmentMERN__PROJECTStinder-backendnode_modulesexpresslibrouterindex.js:275:10)

POST /users/signin 500 304.743 ms - 57

[nodemon] restarting due to changes...
^C[nodemon] starting `node ./bin/www`
(node:16316) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
Connected to database
 

Ответ №1:

Я думаю, ты неправильно понял свою /signin структуру. Я всегда ставлю passport.authenticate в качестве промежуточного программного обеспечения на маршрут. Может быть, попробуем так:

 userRouter.post('/signin', passport.authenticate('local'), (req, res) => {
    // use req.user to retrieve your userdata

    console.log('USER POST FOR SIGNIN', req.user);
    ...
})