本地护照将用户序列化,但req对象为空

时间:2019-06-13 18:32:24

标签: javascript node.js express http-status-code-404 passport-local

我正在尝试使用护照本地策略来验证用户身份。我有两个可能关联的rporblems:

  1. serializeUser()记录正确的用户
  2. 浏览器中出现“未捕获(承诺)错误:请求失败,状态码为404”

我已经查看了多个答案(为此在google的第一页),但尚未弄清楚。

Passportjs doesn't populate req.user after successful login Node + Express + Passport: req.user Undefined [Passport-Local]Authenticate OK but callback fails - req.user is empty ...还有更多

user.js 

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const bcrypt = require('bcryptjs');


// Load User Model
const User = require('../models/User')

  router.post('/login', (req, res, next)=>{
    passport.authenticate('local')(req, res, next)
  })




module.exports = router;

//Login.js 
import React, {Component} from 'react'
// import { Redirect } from 'react-router-dom'
import axios from 'axios'
import '../style/Login.css'

const config = require('../config/api')

class Login extends Component{


  state={
      email: '',
      password: ''
  }

  onSubmit = (e) =>{
    e.preventDefault()
    let {email, password} = this.state
    axios.post(`${config.api}/user/login`, {email, password})

  }
  onInputChange = (e)=>{
    this.setState({[e.target.name]: e.target.value})
  }
  render(){
    return(
      <div className='login-container'>
        <div className='login'>
            <h1>Log in</h1>
            <form className='login-form' onSubmit={this.onSubmit}>
              <label className='login-form-label'>Email</label>
              <input name='email' onChange={this.onInputChange} value={this.state.email}className='form-text-input' type="email"/>
              <label className='login-form-label'>Password</label>
              <input name='password' onChange={this.onInputChange} value={this.state.password} className='form-text-input' type="password"/>
              <div className='flex-end'><button type='submit' className='btn-green mt-2 progress-btn'>Sign in</button></div>
            </form>
        </div>
      </div>
    )
  }
}

export default Login

//index.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const passport = require('passport');
const cookieSession = require('cookie-session');
const session = require('express-session');
const cookieParser = require('cookie-parser');

const sessionKey = require('./util/config').session

const app = express()

// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Express session midleware
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}));

//Passport
require('./util/passport')(passport)
app.use(passport.initialize());
app.use(passport.session());

//GLOBALS
//I should be able to assign req.user here !
app.use(function (req, res, next){
  res.locals.user = req.user || null
  next()
})



//app.use(cors());
app.use(cors({credentials: true, origin: 'http://localhost:3000'}))

//connect to DB
const db = require('./util/config').mongoURI || require('./config/keys').mongoURI
mongoose.connect(db,  { useNewUrlParser: true })
  .then(() => console.log('MongoDB connected'))
  .catch((err) => console.log(err))


//Load Routes
const user = require('./routes/user')
app.use('/api/user/', user)



const PORT = process.env.PORT || 5000

app.listen(PORT, ()=>{
  console.log(`App running on ${PORT}`)
})

//passport.js

const LocalStrategy = require('passport-local').Strategy
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');


const User = require('../models/User')




module.exports = function(passport){
  passport.use(new LocalStrategy({
  usernameField: 'email'},
      (email, password,done)=>{
        User.findOne({email: email})
        .then(user =>{
        if(!user){
          return done(null, false)
        }
        bcrypt.compare(password, user.password, (err, isMatch)=>{
          if(err) throw error
          if(!isMatch){
            return done(null, false)
          }else{
            return done(null, user)
          }
        })
      })

    }))

    passport.serializeUser(function(user, done) {
      done(null, user.id)
      //This logs the correct user
      console.log(user)

  });

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

//api
api: 'http://localhost:5000/api'

0 个答案:

没有答案