baseprime / grapnel

The smallest JavaScript router with named parameters, HTML5 pushState, and middleware support
http://grapnel.js.org
468 stars 40 forks source link

Support for More HTTP verbs? #25

Closed TylerBre closed 9 years ago

TylerBre commented 9 years ago

Seems like Grapnel only responds to GET, can we support the full gamut? I'd like to see at least POST request support. Thanks.

baseprime commented 9 years ago

Yes, currently just Grapnel works as a basic server-side router. Extending functionality into supporting HTTP verbs is definitely in the future. Implementing basic HTTP verb functionality in the time being would be pretty easy using middleware:

var http = require('http'),
    Grapnel = require('grapnel'),
    router = new Grapnel();

// Adds middleware to each router.verb() method
['GET', 'POST', 'PUT', 'DELETE'].forEach(function(verb){
    router[verb.toLowerCase()] = function(){
        var args = Array.prototype.slice.call(arguments);

        args.splice(1, 0, function(req, res, next){
            if(req.method === verb) next();
        });

        return this.add.apply(this, args);
    }
});

router.post('/', function(req, event){
    req.response.end('Hello world!');
});

http.createServer(function(req, res){
    router.bind('match', function(event, _req){
        _req.response = res;
        for(var prop in req){
            _req[prop] = req[prop];
        }
    }).navigate(req.url);
}).listen(3000);
baseprime commented 9 years ago

I also added this explanation to README.md in b308297e55

TylerBre commented 9 years ago

You're the man!

baseprime commented 9 years ago

@TylerBre :+1:

TylerBre commented 9 years ago

Actually, not only did this not work, but before I was running 0.5.2 (which was working with at least hashchange), and when I updated to 0.5.6, nothing worked. Here's how I've implemented it using browserify:

  var Grapnel = require('grapnel');
  var router = new Grapnel({root: "#"});

    router.get('/foo', function (req) {
      console.log('/foo')
    });

    router.get('/', function (req) {
      console.log('/')
    })

In the browser, it does not log either of those routes using links with href="#/" and href="#/foo"

Tested in current chrome and current safari on OS X Yosemite

Finally, can you clarify why you included http to use in the browser?

baseprime commented 9 years ago

My example above is meant for server-side routers.

Your example above will not work because the root cannot be a hash, it's already implied. The root is the relative path of your app.