code_dude
code_dude

Reputation: 1111

How can I make the /api/logout actually log out and redirect in express with passport.js?

I have created and end point /logout, in express, and I instructed the route handler function to first log out and then redirect to the root page.

index.js

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');
const apiRoutes = require('./routes/apiRoutes');
const authRoutes = require('./routes/authRoutes');

mongoose.connect(keys.mongoUri, { useNewUrlParser: true, useUnifiedTopology: true });

const app = express();

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey],
    })
);

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

app.use('/auth', authRoutes);
app.use('/api', apiRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));

apiRoutes.js

> const router = require('express').Router();
> 
> router.get('/logout', (req, res) => {
>     req.logout();
>     res.redirect('/'); });
> 
> router.get('/current_user', (req, res) => res.send(req.user));
> 
> module.exports = router;

When I am clicking on the logout button the url becomes http://localhost:8080/api/logout, but it doesn't do anything else.

I have checked other resources as well and it looks like this is the way to do it, but it doesn't work.

I want to logout and redirect to the root url anytime I click on the Logout button.

Upvotes: 1

Views: 812

Answers (1)

Zachary Blumstein
Zachary Blumstein

Reputation: 325

on redirect in React - Node

f for your index pages

import { BrowserRouter } from 'react-router-dom';

for your api routes set your page up so it looks more like this

import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import './App.css';
import Home from './pages/Home';
import List from './pages/List';

class App extends Component {
  render() {
    const App = () => (
      <div>
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route path='/logout' component={List}/>
        </Switch>
      </div>
    )
    return (
      <Switch>
        <App/>
      </Switch>
    );
  }
}

export default App;

routes and switches are what will help you switch to the logout section.

https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3

Upvotes: 1

Related Questions