1
votes

I'm working on my first express backend React frontend app. Currently working on the user register/login/logout section.

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./config/keys')
const passport = require('passport');
const session = require('express-session');
const LocalStrategy = require('passport-local');
// const passportLocalMongoose = require('passport-local-mongoose');
const User = require('./models/User');

const app = express();

// Use BodyParser
app.use(bodyParser.urlencoded({ extended: true }));

// Passport
app.use(passport.initialize());
app.use(passport.session());

app.use(session({
  secret: 'Rusty is the best',
  saveUninitialized: false,
  resave: false
}));

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Connect to the Database
const db = keys.mongoURI
mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log(`MongoDB connected...`))
  .catch(err => console.log(err));

// Routes
const items = require('./routes/api/items')
app.use('/api/items', items);

// Auth Routes
app.post('/register', function(req, res) {
  User.register(new User({ username: req.body.username }), req.body.password, function(err, user) {
    if (err) {
      console.log(err);
      return res.render('/register');
    }
    passport.authenticate('local')(req, res, function() {
      res.redirect('/secret');
    })
  })
});

app.post('/login', passport.authenticate('local', {
    successRedirect: '/secret',
    failureRedirect: '/login'
  }), function(req, res) {
});

app.get('/logout', function(req, res) {
  req.logout();
  res.redirect('/');
})

// Port and Listen
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on ${port}...`));

The post routes at the end of my express server.js file work fine, but I have problems when I get to app.get('/logout'). My server is running on 5000 and client is on 3000. I have "proxy": "http://localhost:5000" inside my client project.json. localhost:3000/logout returns a blank page while localhost:5000/logout returns the res.send message "You have hit the logout page".

Anyone know how I can fix this?

edit: Here is my react router to show how the client routes

import React, { Component } from 'react';
import { Route, BrowserRouter } from 'react-router-dom';

import Input from './components/Input';
import SignUp from './components/SignUp';
import Form from './components/Form';
import LogIn from './components/LogIn';
import SignUp2 from './components/SignUp2';
import Profile from './components/Profile';
import Home from './components/Home';
import LogOut from './components/LogOut';


class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Route exact path='/' component={ Home } />
          <Route path='/register' component={ SignUp2 } />
          <Route path='/changeThisBackToRegister' component={ SignUp } />
          <Route path='/form' component={ Form } />
          <Route path='/login' component= { LogIn } />
          <Route path='/profile' component = { Profile } />
          <Route path='/secret' component = { Input } />
          <Route path='/logout' component = { LogOut } />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;
1
can you put the how you make this GET on the frontend?Miguel Angel
@MiguelAngel Yep, I edited the original postoolongloop
How are you calling '/logout' from your React app?Dinesh Pandiyan
@DineshPandiyan Okay great point, so I added a LogOut Component with a simple header <h1>Log Out</h1> and made a react route to '/logout'. I am able to hit the LogOut page now which shows the header Log Out. However the server's app.get('/logout') still doesn't trigger the logout() and redirect('/'). Any ideas?oolongloop
You need to call the api in from Logout component once it is mounted. I will add the code as an answer.Dinesh Pandiyan

1 Answers

0
votes

Change your /logout api response to send json response.

app.get('/logout', function(req, res) {
  req.logout();
  res.json({success: true});
})

In your Logout component, make /logout call when the component mounts.

import React, { Component } from 'react';

export default class Logout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      logoutSuccess: false
    };

  }
  componentDidMount() {
    fetch('/logout')
    .then((response) => response.json())
    .then(() => {
      this.setState({logoutSuccess: true});
    });
  }
  render() {
    const { logoutSuccess } = this.state;
    return (
      <div>
        { logoutSuccess && (<div>Logout Success</div>)}
      </div>
    );
  }
}