1

I got a problem with my routes in ReactJS. I defined some routes like this :

...Import / Class...
class App extends Component {
    render() {
        return (
            <div>
                <Header />
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/login" component={Login} />
                    <Route path="/signup" component={Signup} />
                    <ProtectedRoute path="/user/contact" component={Contact} />
                    <ProtectedRoute path="/user/person" component={UserPerson} />
                    <ProtectedRoute path="/user/profile" component={Profile} />
                    <Route component={NotFound} />
                </Switch>
                <Footer />
            </div>
        );
    }
}
...Export...

Below you can see my ProtectedRouteclass

...Import / Class...
const ProtectedRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        AuthGestion.userIsAuthenticated() ? (
            <Component {...props} />
        ) : (
            <Redirect to={{
                pathname: '/login',
                state: { from: props.location }
            }}/>
        )
    )} />
);
...Export...

When I go to my page with a <NavLink to="/user/person"></NavLink>, there is no problem, my component is loaded and I can see my page. But when I go to the url directly /user/person, and recharge my page (CTRL + F5), I got in the Console the error SyntaxError: expected expression, got '<' and a white page. Just the user routes don't work.

I add below my server informations :

import path from 'path';
import bodyParser from 'body-parser';
import express from 'express';
import mongoose from 'mongoose';
import routes from './routes/index.route';
import config from '../../config/config';

import webpack from 'webpack';
import webpackConfig from '../../config/webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

//Connexion MongoDB
mongoose.connect(config.mongodbUri, { useNewUrlParser: true });
mongoose.connection.on('connected', () => { console.log('MongoDB connecté'); });
mongoose.connection.on('error', (error) => { console.log(error); });

//Lancement serveur express
const server = express();

//Express need
server.use(bodyParser.json());
server.use(express.static(config.publicPath));
server.use(express.static(config.distPath));

//Hot reload
if(config.isDevMode) {
    const webpackCompiler = webpack(webpackConfig);
    server.use(webpackDevMiddleware(webpackCompiler, {}));
    server.use(webpackHotMiddleware(webpackCompiler));
}

// Route vers l'API
server.use('/api', routes);

// Landing page
server.get('/*', (req, res) => {
    res.sendFile(path.join(config.publicPath, '/index.html'));
});

//Ecoute du serveur
server.listen(config.port, () => {
    console.log(`App here : http://${config.host}:${config.port}`);
});

export default server;

Can you please help me to understand the problem ? And maybe correct my routing if it's not good.

Cracs
  • 425
  • 1
  • 8
  • 29
  • Sounds like your server returns wrong payload on the internal route, If your app is managing the routes client-side, that means that all the routes that are requested from the server should serve the client code. Can u share regarding your server? – felixmosh Mar 22 '19 at 10:25
  • I added my server informations. It is what you want ? – Cracs Mar 22 '19 at 10:31
  • Do you get this error on the api request or on the html page itself? – felixmosh Mar 22 '19 at 10:34
  • I haven't any errors with my API, I got this error on the front side in the console, on the html page itself. I didn't call my API for the moment in the 3 components `user/contact`, `user/person`, `user/profile` – Cracs Mar 22 '19 at 10:37
  • 1
    maybe the same as https://stackoverflow.com/a/37949474/11129751 – Fraction Mar 22 '19 at 10:41
  • The question is if the error comes from the api call or on page load? – felixmosh Mar 22 '19 at 10:48
  • @Fraction you right, In my `index.html` I had ``. I remove the dot ahead`/dist` and I got no errors anymore now... I don't know how this worked until today... – Cracs Mar 22 '19 at 10:51

2 Answers2

0

for future reference: https://stackoverflow.com/a/37949474/11129751

I've got a react/react-router page without any express and got the same error: SyntaxError: expected expression, got '<' which started to appear as soon as I configured a react route other then just root /.

After some experimenting I've figured out that in my index.html there was a link to js file:

So, the solution was to add / in the source path:

and the error has gone.

Hope that could help a bit.

Fraction
  • 11,668
  • 5
  • 28
  • 48
0

This has changed since React-Router 6.

You CAN use nested routes/components with this syntax below.

import { Routes, Route, Navigate } from "react-router-dom";

function App() {
  return (
    <Routes>
      <Route path="/public" element={<PublicPage />} />
      <Route
        path="/protected"
        element={
          // Good! Do your composition here instead of wrapping <Route>.
          // This is really just inverting the wrapping, but it's a lot
          // more clear which components expect which props.
          <RequireAuth redirectTo="/login">
            <ProtectedPage />
          </RequireAuth>
        }
      />
    </Routes>
  );
}

function RequireAuth({ children, redirectTo }) {
  let isAuthenticated = getAuth();
  return isAuthenticated ? children : <Navigate to={redirectTo} />;
}
Julien Ricard
  • 316
  • 2
  • 11
  • You can't try the same method for nested routes in react-router dom v6. this will end in throttling navigation, for the single route it is okay. – Sabaoon Bedar Apr 24 '22 at 23:17