2
votes

i am creating an react application and have some problems. My routes work well in the client side (dev-server) , but when i serve static files through express, it only works '/' route . '/dashboard' doesn't work.But when i add this line

app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));

routing starts to work well , but i am getting another error trying to SIGN IN

Uncaught SyntaxError: Unexpected token <

This is my express server code `

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const EventbriteStrategy = require('passport-eventbrite-oauth').OAuth2Strategy;
const path = require('path');
const bodyParser = require('body-parser');
const keys = require('./config/keys');

const port = process.env.PORT || 5000;

const app = express();

app.use(express.static(path.join(__dirname, '../../dist')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));


app.use(passport.initialize());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: 'login',
  resave: false,
  saveUninitialized: true
}));

const strategy = new EventbriteStrategy({
  clientID: keys.eventbriteClientID,
  clientSecret: keys.eventbriteClientSecret,
  callbackURL: 'http://localhost:5000/auth/eventbrite/callback'
},
((accessToken, refreshToken, extraParams, profile) => {
  console.log(profile, 'profile');
  console.log(accessToken, 'accessToken');
  console.log(accessToken, 'accessToken');
  console.log(extraParams, 'extraParams');
}
));

passport.use(strategy);

app.get('/auth/eventbrite',
  passport.authenticate('eventbrite', {}), (req, res) => {
    console.log(res, 'rees');
  });

app.get('/auth/eventbrite/callback',
  passport.authenticate('eventbrite', { failureRedirect: '/' }),
  (req, res) => {
    if (!req.user) {
      throw new Error('user null');
    }
    res.redirect('/dashboard');
  });

app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});

And this is my routers `

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import DashboardPage from '../components/pages/DashboardPage';
import LoginPage from '../components/pages/LoginPage';
import NotFoundPage from '../components/pages/NotFoundPage';

const AppRouter = () => (
  <BrowserRouter>
    <React.Fragment>
      <Switch>
        <Route path="/" component={LoginPage} exact />
        <Route path="/dashboard" component={DashboardPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </React.Fragment>
  </BrowserRouter>
);

export default AppRouter;

And here is the login page `

import React from 'react';
import { NavLink } from 'react-router-dom';

const logo = require('../../../../public/images/react.png');

const config = {
  logo,
  authUrl: ''
};

const LoginPage = props => (
  <React.Fragment>
    <header file={props} className="login-header">
      <div className="row">
        <div className="login-header__wrapper">
          <div className="login-header__logo-box">
            <NavLink to="/" role="link"><img src={config.logo} alt="logo" width="190" height="80" className="navbar__logo" /></NavLink>
          </div>
          <h1 className="login-header__heading">Welcome to Events</h1>
        </div>
      </div>
    </header>
    <main>
      <section className="register">
        <div className="row">
          <div className="register-wrapper">
            <section className="register__description">
              <h2>Events</h2>
              <p>Here you can search your favourite events and get the location on map</p>
            </section>
            <section className="register__sign-in">
              <h2>Sign in with facebook</h2>
              <div>
                <a href="/auth/eventbrite" className="btn btn_sign-in">Sign in</a>
              </div>
            </section>
          </div>
        </div>
      </section>

    </main>

What should i do to make all the routes work properly ?

1

1 Answers

3
votes

The wildcard route, *, is required for react with React Router so that the server doesn't go looking for a get with a route that matches /dashboard when React Router changes the location and instead React Router can continue to handle the routes. So you're on the right track there.

However the issue is that your wildcard route is checked first so it's catching every single route—including your /auth routes. To fix this, you can simply put the controller for the wildcard route after all other routes have been defined in the server. This works because Express will check routes moving from the top to bottom of the app.js (or whatever you've named it) file and stops as soon as it finds one that matches the requested route.

So just move this:

app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));

so that it's below any other app.get or app.post, etc. Basically it should go right above:

app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});