React Router / Express - Refreshing dynamic URL parameters

Viewed 991

My React router works fine when navigating to '/Article/1/' via a link, though when I refresh my browser, it no longer detects my Article component.

Root.js

import React from 'react';
import { BrowserRouter as Router, Route, Link, browserHistory } from 'react-router-dom';
import Home from '../page/Home/Index';
import Article from '../page/Article/Index';

const Root = () => {
  return (
    <Router history={browserHistory}>
      <div>
        <ul>
          <li><Link to={'/'}>Home</Link></li>
          <li><Link to={'/About'}>About</Link></li>
        </ul>
        <hr />
        <Route exact path={'/'} component={Home} />
        <Route path={'/Article/:id'} component={Article} />
      </div>
    </Router>
  );
};

export default Root;

Server.js

var express = require('express');
var app = express();

app.use('/', express.static(__dirname + '/dist'));

app.listen(9000, function() {
  console.log('listening on 9000.')
});

I read online that it may be related to me not having a wildcard in my server.js - could anyone point me in the right direction? thank you in advance!

EDIT - this is what I tried (still not rendering):

app.use(express.static(__dirname + '/dist'))

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname + '/dist/index.html'));
});
1 Answers

I read online that it may be related to me not having a wildcard in my server.js

Yep, that'll be it. The goal here is to have your client handle the routing and not the server, for that to work you need the server to return the client app regardless of what URL it gets.

Simple fix - change / to /* on your server route.

Related