React App with Express Backend&快递会话

时间:2017-12-05 00:26:52

标签: node.js reactjs express express-session

我目前有一个React App(通过create-react-app)和一个Express服务器用于我的API调用。它们都是单独运行的,并且一直工作正常,直到遇到这个问题:

我还使用express-sessionpassport进行用户身份验证。我能够对用户进行身份验证,但会话不会在API调用之间持续存在。如果我成功登录,则下次进行API调用时,req.sessionID会有所不同,req.isAuthenticated()将返回false

这是我的服务器代码:

'use strict'

var express         = require('express');
var path                = require('path');
var bodyParser      = require('body-parser');
var cookieParser    = require('cookie-parser');
var mongoose      = require('mongoose');
var passport      = require('passport');
var session       = require('express-session');
var cors          = require('cors');
var flash         = require('connect-flash');

var store         = require('./store');
var database      = require('./database');

var app     = express();
var port    = process.env.port || 3001;
var router  = express.Router();

var promise = mongoose.connect('mongodb://localhost:27017/lifeless-db', {useMongoClient: true});

//app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser('lifeless-secret-01890'));
app.use(session({
  secret: 'lifeless-secret-01890',
  saveUninitialized: true,
  cookie: {
    secure: false,
  }
}));
app.use(flash());

app.use(passport.initialize());
app.use(passport.session());
// Initialize Passport
var authinit = require('./auth/init');
authinit(passport);

// For debugging:
app.use(function(req, res, next) {
  console.log("SessionID: " + req.sessionID);
  console.log(req.isAuthenticated() ? "This user is logged in" : "This user is NOT logged in");
  next();
});



// GET

app.get('/items', function(req, res) {
  store.getAllItems((items) => {
    if(!items) return res.send({error: true, message: 'Error loading store :/', items: null});
    else return res.send({error: false, message: 'Success', items: items});
  });
});

app.get('/login', function(req, res) {
  console.log(req.flash());
  console.log("Login fail");
  res.send({error: true, message: 'Unknown error'});
});


// POST

app.post('/message', function(req, res) {
  database.submitMessage(req.body.email, req.body.message, (success) => {
    if (success) return res.send({error: false, message: 'Success'});
    else return res.send({error: true, message: 'Error sending message'});
  });
});


app.post('/login', passport.authenticate('local', {failureRedirect: '/login', failureFlash: true}), function(req, res) {
  console.log(req.flash());
  console.log("Login success");
  return res.send({error: false, message: 'Success'});
});



// SERVER

app.listen(port, function(){
  console.log('Server started.');
  console.log('Listening on port ' + port);
});

以下是来自React App的API调用示例(使用axios):

login(e) {
    e.preventDefault();

    axios({
      method: 'post',
      url: 'http://localhost:3001/login',
      data: {
        username: this.state.username,
        password: this.state.password,
      }
    })
    .then((response) => {
      console.log(response.data);
      if (response.data.error) {
        this.setState({error: true, errmessage: response.data.message});
      } else {
        this.setState({redirect: true});
      }
    })
    .catch((error) => {
      this.setState({error: true, errmessage: 'Error logging in'});
    });
  }

我认为必须有某种方法让React以某种方式存储会话(?)但我对React很新,并且不知道如何将它与快速后端一起使用。

2 个答案:

答案 0 :(得分:1)

您来自React客户端的axios请求需要与凭据一起发送。要解决此问题,请执行axios.defaults.withCredentials = true;或执行axios.get('url', {withCredentials: true})...,也可以在您的expressjs后端中,设置cors选项credentials: true

答案 1 :(得分:0)

以下是使用connect-redis设置快速会话的示例。首先,设置express-session和Redis商店。

var session = require('express-session);
var RedisStore = require('connect-redis')(session);  

然后,您要为您的应用宣布中间件;

app.use(session({
  store: new RedisStore({
    url: process.env.REDIS_URL
  }),
  secret: process.env.REDISSECRET,
  resave: false,
  saveUninitialized: false
}));

现在当你使用req.session。{etc}时,这会写入你的Redis数据库。