millermedeiros / crossroads.js

JavaScript Routes
http://millermedeiros.github.com/crossroads.js/
1.44k stars 156 forks source link

Crossroads only matches Route once #100

Closed webdesserts closed 10 years ago

webdesserts commented 10 years ago

I am attempting to write a Node.js app with crossroads. Unfortunately I've run into a problem where crossroads will only run the function when a route is matched once. This includes the bypassed function as well. I've simplified my code a bit to demonstrate the problem:

app.js

var routes = require('./routes'),
    router = require('crossroads')
    url = require('url'),
    http = require('http');

var app = http.createServer()
app.listen(8080)

app.on('listening', function(){
  console.log('listening on port 8080')
})

app.on('request', function(req, res){
  path = url.parse(req.url).pathname
  console.log(req.method, path)
  router.parse(path, [req, res]);
})

//::ROUTES:://

router.addRoute('/', routes.index )
router.bypassed.add( routes.missing )

routes/index.js

var routes = {}

routes.index = function index (req, res) {
  console.log('route: index')
  res.end('mah index\n')
}

routes.missing = function missing (req, res) {
  console.log('route: missing')
  res.end('four oh four :(\n')
}

module.exports = routes

and here's a quick gif of what's happening: crossroads_error

What am I doing wrong that's causing this? Any help would be appreciated.

millermedeiros commented 10 years ago

crossroads keeps an internal state of previously matched routes and previous request (so it can notify the switched signal and to avoid multiple consecutive matches).

you can toggle the behavior with crossroads.ignoreState = true: http://millermedeiros.github.io/crossroads.js/#crossroads-ignoreState

this was a breaking change introduced on v0.11.0 (semver fail)

millermedeiros commented 10 years ago

PS: this is the default behavior because crossroads was initially designed to be used on the front-end.. and on most client-side apps routes should only be triggered once. sorry for the inconvenience.

webdesserts commented 10 years ago

Ahh that makes sense. I kinda thought it was acting like a client side router, I just didn't know what I needed to do to switch it. I think I saw...

This feature should NOT be needed by most users.

...in the documentation and just skipped over all the state stuff.

Thanks for your help.