IROC
IROC

Reputation: 97

Express server communicating with React App

I am trying to redirect to my React App after authenticating the login. But its not working, don't know why.

React App at port 3000

Server at port 3001

I am routing to server on login submit -> server authenticate using passport -> it should redirect to React App route '/secured'. Instead it is showing GET http://localhost:3001/secured 404 (Not Found) It is routing to the server address. How to resolve this?

Authentication is working fine. I have checked it all using postman.

EXPRESS SERVER


//middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.use(cors({
    origin: 'http://localhost:3000', //location of frontend app (react app here)
    credentials: true,
}))

app.use(expressSession({
    secret: 'secret',
    resave: true,
    saveUninitialized: true,
}))

app.use(cookieParser('secret'))
app.use(passport.initialize())
app.use(passport.session())
require('./models/passport-config')(passport)

// routes
app.get('/', (req, res) => {
    res.send('Home route')
})

app.post('/login', (req, res, next) => {
    passport.authenticate('local', (err, user, info) => {
        if (err) { return next(err) }
        if (!user) { return res.redirect('/') }

        req.logIn(user, (err) => {
            if (err) { return next(err) }
            return res.redirect('/secured')
        })

    })(req, res, next)
})

app.post('/register', (req, res) => {
    console.log(req.body)
})
app.get('/user', (req, res) => {
    res.send(req.user)
})

// server init
app.listen(3001, () => {
    console.log('serving at http://localhost:3001...')
})

"REACT APP - App.js

import './App.css';
import Register from './components/Register';
import Login from './components/Login';
import {BrowserRouter, Route} from 'react-router-dom'

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <div>
          <Route exact path="/" component={Login} />
          <Route path="/secured" component={Register} />
        </div>
      </BrowserRouter>
    </div>
  );
}

export default App;

REACT APP - Login.js

import React, { Component } from 'react'
import "./login.css"
import axios from 'axios'

class Login extends Component {
    constructor(props) {
        super(props)

        this.state = {
            username: null,
            password: null,
        }
    }

    handleChange = (event) => {
        event.preventDefault()
        this.setState({
            ...this.state,
            [event.target.name]: event.target.value,
        })
    }


    handleSubmit = (event) => {
        event.preventDefault()

        axios({
            method: "post",
            data: this.state,
            withCredentials: true,
            url: 'http://localhost:3001/login'
        })
        // .then(this.getData())

    }

    getData = () => {
        axios({
            method: "get",
            data: this.state,
            withCredentials: true,
            url: 'http://localhost:3001/user'
        }).then(res => {
            this.setState({
                username: res.data['0'].username,
                email: res.data['0'].email,
                password: null
            });
        })
    }

    render() {
        return (
            <div >
                <div>
                    <form id='login' onSubmit={this.handleSubmit}>
                        <div>
                            <h3>Login</h3>
                        </div>
                        <div >
                            <div >
                               
                                <input onChange={this.handleChange} id="icon_prefix" type="text" name='username' />
                                <label htmlFor="icon_prefix">Username</label>
                            </div>
                        </div>
                        <div>
                            <div >
                              
                                <input onChange={this.handleChange} id="icon_prefix" type="password"  name='password' />
                                <label htmlFor="icon_prefix2">Password</label>
                            </div>
                        </div>
                        <div >
                            <div >
                                <input type='submit' />
                            </div>
                        </div>
                    </form>
                    <div>
                        Already a member? <a href="/secured">Register here</a>
                    </div>
                </div>
            </div>

        )
    }

}

export default Login

Upvotes: 0

Views: 261

Answers (1)

andersryanc
andersryanc

Reputation: 979

Inside your handleSubmit function in your <Login /> component, you should add the .then() callback, check the response for error/success and then either show an error to the user in the UI or use React Router History to push or replace the current route.

Another option would maybe be to store a state variable in your <Login /> component, like this.state.isAuthenticated which you could then check in your render() method and choose to return a React Router Redirect like:

render() {
  if (this.state.isAuthenticated) {
    return <Redirect to="/somewhere/else" />
  }
  
  return (
    <div>
      ...
    </div>
  )
}

Upvotes: 1

Related Questions