express-subroute
Sub routes for express, with support for automatic OPTIONS response and 405 Method Not Allowed.
Installation
Install via npm:
$ npm install express-subroute
Example
A tiny in-memory blog app. There's also a JavaScript version at USAGE.js.
express = require 'express'subroute = require 'express-subroute' expressconfigure -> subrouteinstall this # or require('express-subroute').install() to enable globally posts = @param 'post' if req.post = postsreqparamspostthen do next else ressend 404 # or `subroute app, '/blog', ->` without `install()`ing @subroute '/blog'-> @get resend 'welcome!' @get '/about' resend 'an example app' @subroute '/post'-> @get resjson posts @post postspush reqbody; ressend 204 @get '/:post' resjson reqpost @put '/:post' postsreqparamspost=reqbody; ressend 204 @del '/:post' delete postsreqparamspost; ressend 204 @subroute '/:post/comment'-> @get resjson reqpostcomments or @post reqpostcomments ||= push reqbody; ressend 204 # Adds handlers to the following methods/paths: # - GET|OPTIONS /blog # - GET /blog/about # - GET|POST|OPTIONS /blog/post # - GET|PUT|DELETE /blog/post/:post # - GET|POST|OPTIONS /blog/post/:post/comment # you can also require() the function from another file @soubroute '/forum'require './forum' # forum.coffee exports a function: = -> @get # ... @post # ... # ...
If you don't setup an OPTIONS handler, one is automatically created for you with all the methods used in the route. In addition, if none of the handlers you register handle the request, an 405 Method not allowed response is sent.
For more info, see the code (~30 lines) and the tests.
Related: