1

I have a fairly basic login setup (code below) with a few components requiring authentication. When I navigate to http://localhost:8000/, it redirects to http://localhost:8000/login and everything is fine. If I then log in, it goes back to http://localhost:8000/ and displays my main component.

However, when I navigate to http://localhost:8000/login directly, it says "Cannot GET /login". Same thing with my "about" component. It does work when I add a pound symbol: http://localhost:8000/#/login. Can anyone explain what's going on?

var React = require('react');
var Main = require('./components/main');
var Login = require('./components/login');
var About = require('./components/about');
var SessionStore = require('./stores/session-store')
import createBrowserHistory from 'history/lib/createBrowserHistory';

import { Router, Route, Link, History, IndexRoute } from 'react-router';

var App = React.createClass({

    render: function() {
        return <div>
          {this.props.children}
        </div>
      }
});

function requireAuth(nextState, replaceState) {
  if(!SessionStore.isLoggedIn()){
    replaceState({ nextPathname: nextState.location.pathname }, '/login');
  }
}

function redirectIfLoggedIn(nextState, replaceState){
  if(SessionStore.isLoggedIn()){
    replaceState({ nextPathname: nextState.location.pathname }, '/');
  }
}

var routes = (
  <Router history={createBrowserHistory()}>
    <Route path="/" component={App}>
      <IndexRoute component={Main} onEnter={requireAuth}/>
      <Route path="login" component={Login} onEnter={redirectIfLoggedIn} />
      <Route path="about" component={About} onEnter={requireAuth} />
    </Route>
  </Router>
)

React.render(routes, document.querySelector('.container'));

1 Answer 1

1

Quick answer, the http://localhost:8000/#/login is running in the javascript app in your browser, so the app it's being served from / by the express web server, and so the /(app)#/login and /#/about are not requesting anything from the server but are routes in the JS app, (react-routes) to render the various components. when you enter /login directly it's has to querying the express web server, but you don't have anything express server routes set up except the one to serve the app at the root /.

So it's down to react-routes, a related questions asks how to remove it, but please be aware as of Oct '15 react-router changed from version 0.13 to 1.0 which changed the API quite a bit, so be careful when reading examples to be aware of the version How to stop /#/ in browser with react-router?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.