Skip to content

Commit 7c2ee89

Browse files
wesleytodddougwilson
authored andcommitted
docs: add example of .route() use and fall-through methods
closes #62 closes #63
1 parent badc3da commit 7c2ee89

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,47 @@ curl http://127.0.0.1:8080/such_path
336336
> such_path
337337
```
338338

339+
### Example of advanced `.route()` usage
340+
341+
This example shows how to implement routes where there is a custom
342+
handler to execute when the path matched, but no methods matched.
343+
Without any special handling, this would be treated as just a
344+
generic non-match by `router` (which typically results in a 404),
345+
but with a custom handler, a `405 Method Not Allowed` can be sent.
346+
347+
```js
348+
var http = require('http')
349+
var finalhandler = require('finalhandler')
350+
var Router = require('router')
351+
352+
// create the router and server
353+
var router = new Router()
354+
var server = http.createServer(function onRequest(req, res) {
355+
router(req, res, finalhandler(req, res))
356+
})
357+
358+
// register a route and add all methods
359+
router.route('/pet/:id')
360+
.get(function (req, res) {
361+
// this is GET /pet/:id
362+
res.setHeader('Content-Type', 'application/json')
363+
res.end(JSON.stringify({ name: 'tobi' }))
364+
})
365+
.delete(function (req, res) {
366+
// this is DELETE /pet/:id
367+
res.end()
368+
})
369+
.all(function (req, res) {
370+
// this is called for all other methods not
371+
// defined above for /pet/:id
372+
res.statusCode = 405
373+
res.end()
374+
})
375+
376+
// make our http server listen to connections
377+
server.listen(8080)
378+
```
379+
339380
## License
340381

341382
[MIT](LICENSE)

0 commit comments

Comments
 (0)