wegry
wegry

Reputation: 8147

react-router 1.0 routes being picked up by express.js server

I've been trying to get client side routes to only be handled by the client. I assume this is possible with the HTML5 History API. My problem is express picks up routes like '/details/55' (and both react-router and express do nothing when I try doing '/#details/55'). What am I missing.

app.js

import React from 'react'
import { render } from 'react-dom'
import { IndexRoute, Route, Router, Link } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'

class App extends React.Component {
  render () {
    return (
            <div>
              <h1>
              Shared Header
              </h1>
              {this.props.children}
            </div>
      )
  }
}

const history = createBrowserHistory()

render((
  <Router history={history}>
    <Route path='/' component={App}>
      <IndexRoute component={Index} />
      <Route path='/details/:id' component={Details} />
      <Route path='*' component={NoMatch} />
    </Route>
  </Router>
  ), document.getElementById('app'))

server.js

import express from 'express'


app.use(express.static('public'))

app.get('/', (req, res) => {
  res.sendFile('index.html')
})

// Hack to get react-router to not interfere with express.
app.get('/details/:id', (req, res) => {
  res.sendFile('index.html')
})

Upvotes: 0

Views: 491

Answers (2)

quborg
quborg

Reputation: 171

When using sendFile(), server can print a TypeError: path must be absolute or specify root to res.sendFile

you should add __dirname

app.get('/*', function(req,res){
  res.sendFile(__dirname + '/index.html')
  // or
  // res.sendFile('/index.html', { root: __dirname })
})

Upvotes: 0

Kyeotic
Kyeotic

Reputation: 19847

Use a wildcard in express

app.get('/*', (req, res) => {
  res.sendFile('index.html')
});

This will force all server requests to be handled by returning the index page, where react-router will take over by looking at the full URL.

Upvotes: 1

Related Questions