3

I'm building a React application using an Express Server on the backend , and have used Create React App for the frontend. I'm using Concurrently to run both the back (http://localhost:5000) and frontend (http://localhost:3000) servers during development. I have setup React-Router for frontend routing.

I've implemented local authentication, which is functioning well. However, when I try to redirect after the successful login, I get a 404 not found error for http://localhost3000/student/dashboard. So React-Router is not handling this Route. When I type this address directly into the address bar, I arrive at the correct page served up by React-Router.

Here is my post route (inside authRoutes.js):

app.post(
    '/auth/student',
    passport.authenticate('local', {
      failureRedirect: '/login'
    }),
    (req, res) => {
      res.redirect('/student/dashboard');
    }
  );

  app.get('/auth/logout', (req, res) => {
    req.logout();
    res.redirect('/');
  });

My React-Router setup:

const App = () => {
  return (
    <div>
      <BrowserRouter>
        <div>
          <Route path="/" component={Header} />
          <Route exact path="/" component={Landing} />
          <Route path="/login" component={LoginPage} />
          <Route exact path="/student/dashboard" component={StudentDashboard} />
          <Route path="/teacher/dashboard" component={TeacherDashboard} />
        </div>
      </BrowserRouter>
    </div>
  );
};

I've setup the proxy for Routing calls through the Express server:

module.exports = app => {
  app.use(proxy('/auth/*', { target: 'http://localhost:5000' }));
};

The lower half of my index.js file in the server directory

require('./routes/authRoutes')(app);

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build')); // Serves up production assets

  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

// Initialise PORT
const PORT = process.env.PORT || 5000;
app.listen(PORT);

I'm not sure what else I need to include, let me know if more. Here is the error:

xhr.js:173 GET http://localhost:3000/student/dashboard 404 (Not Found)
dispatchXhrRequest @ xhr.js:173
xhrAdapter @ xhr.js:18
dispatchRequest @ dispatchRequest.js:49
Promise.then (async)
request @ Axios.js:55
wrap @ bind.js:11
handleSubmit @ LoginForm.js:21
C._this.handleSubmit @ formik.esm.js:837
Formik._this.executeSubmit @ formik.esm.js:390
(anonymous) @ formik.esm.js:380
Promise.then (async)
Formik._this.submitForm @ formik.esm.js:376
Formik._this.handleSubmit @ formik.esm.js:364
callCallback @ react-dom.development.js:146
invokeGuardedCallbackDev @ react-dom.development.js:195
invokeGuardedCallback @ react-dom.development.js:245
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:260
executeDispatch @ react-dom.development.js:617
executeDispatchesInOrder @ react-dom.development.js:642
executeDispatchesAndRelease @ react-dom.development.js:742
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:755
forEachAccumulated @ react-dom.development.js:722
runEventsInBatch @ react-dom.development.js:898
runExtractedEventsInBatch @ react-dom.development.js:908
handleTopLevel @ react-dom.development.js:5076
batchedUpdates$1 @ react-dom.development.js:18376
batchedUpdates @ react-dom.development.js:2301
dispatchEvent @ react-dom.development.js:5156
interactiveUpdates$1 @ react-dom.development.js:18438
interactiveUpdates @ react-dom.development.js:2322
dispatchInteractiveEvent @ react-dom.development.js:5132
createError.js:17 Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)

Thank you in advance for any help

  • 1
    I think you should redirect inside the frontend, not the backend. Basically, you are logging in from the frontend using an ajax / fetch call right ? Having that in mind, if you redirect in the backend that will have no effect on the frontend as the call was made from the javascript and not the browser itself. Maybe try something like this [Redirect](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md) – Goran.it Oct 18 '18 at 07:56
  • Thanks for the reply. I suspected something like this was the problem. Not sure how I can implement implement this. Maybe in the then function of the ajax promise? – Patrick Robertson Oct 18 '18 at 22:11
  • I've given you the link above, it shows an example with React router. You can not implement redirection in the backend, what you can do is wait for the response in the frontend, and when authentication passed redirect the user to some route. – Goran.it Oct 19 '18 at 07:56
  • i have some issue , i think a catch all is needed in express to redirect to frontend index.html – nick Aug 08 '20 at 10:10

0 Answers0