From 8dba514dcbd191b7ff58e98d205bb073c4b6bc51 Mon Sep 17 00:00:00 2001 From: Jason Mulligan Date: Tue, 7 Mar 2017 22:24:39 -0500 Subject: [PATCH] Adding support for OPTIONS routes --- lib/woodland.js | 14 ++++++++++++-- package.json | 2 +- test/test.js | 10 +--------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/woodland.js b/lib/woodland.js index d204886..f7c001d 100644 --- a/lib/woodland.js +++ b/lib/woodland.js @@ -16,7 +16,8 @@ const coerce = require("tiny-coerce"), endSlash = /\/$/, isParam = /^:/, hasParam = /\/:(\w*)/, - head = /^(HEAD)$/, + head = /^HEAD$/, + options = /^OPTIONS$/, methods = http.METHODS; class Woodland { @@ -139,7 +140,7 @@ class Woodland { route (req, res) { let deferred = defer(), - method = [head.test(req.method) ? "GET" : req.method], // @todo support implicit GET & explicit OPTIONS + method = head.test(req.method) ? "GET" : req.method, middleware, result; let last = err => { @@ -216,6 +217,11 @@ class Woodland { }); this.decorate(req, res); + + if (options.test(method) && !this.allowed(method, req.parsed.pathname, req.host)) { + method = "GET"; + } + result = this.routes(req.parsed.pathname, req.host, method); if (result.params) { @@ -321,6 +327,10 @@ class Woodland { throw new Error("Invalid HTTP method"); } + if (head.test(method)) { + throw new Error("Cannot set HEAD route, use GET"); + } + if (!this.middleware.has(lhost)) { this.middleware.set(lhost, new Map()); } diff --git a/package.json b/package.json index 8ceb3de..d8e51ac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "woodland", - "version": "1.1.22", + "version": "1.2.0", "description": "Lightweight HTTP/HTTPS router with virtual hosts & automatic Allow header", "main": "index.js", "scripts": { diff --git a/test/test.js b/test/test.js index 9143625..edc7505 100644 --- a/test/test.js +++ b/test/test.js @@ -5,14 +5,6 @@ const http = require("http"), tinyhttptest = require("tiny-httptest"), router = require(path.join(__dirname, "..", "index.js"))({defaultHeaders: {"Cache-Control": "no-cache"}, defaultHost: "localhost", hosts: ["localhost", "noresponse"]}); -function bound (req, res, next) { - next(); -} - -let boundd = bound.bind(bound); - -router.use(boundd).blacklist(boundd); - router.use("/", (req, res) => { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(req.method !== "OPTIONS" ? "Hello World!" : ""); @@ -66,7 +58,7 @@ describe("Valid Requests", function () { .end(); }); - it("GET /echo/hello (200 / 'Success')", function () { + it("OPTIONS /echo/hello (200 / 'Success')", function () { return tinyhttptest({url: "http://localhost:8001/echo/hello", method: "OPTIONS"}) .expectStatus(200) .expectHeader("allow", "GET, HEAD, OPTIONS")