From 33f73543c0cd60d7003af867c9a21e788f82e964 Mon Sep 17 00:00:00 2001 From: bourgeoa Date: Tue, 16 Jan 2024 19:28:23 +0100 Subject: [PATCH] 405 not allowed method --- lib/create-app.js | 27 +++++++++++++++++++++++++++ test/integration/http-test.js | 15 +++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/create-app.js b/lib/create-app.js index 34b9e17eb..b2c36bfcb 100644 --- a/lib/create-app.js +++ b/lib/create-app.js @@ -117,6 +117,33 @@ function createApp (argv = {}) { // Attach the LDP middleware app.use('/', LdpMiddleware(corsSettings)) + // https://stackoverflow.com/questions/51741383/nodejs-express-return-405-for-un-supported-method + app.use(function (req, res, next) { + const AllLayers = app._router.stack + const Layers = AllLayers.filter(x => x.name === 'bound dispatch' && x.regexp.test(req.path)) + + const Methods = [] + Layers.forEach(layer => { + for (const method in layer.route.methods) { + if (layer.route.methods[method] === true) { + Methods.push(method.toUpperCase()) + } + } + }) + + if (Layers.length !== 0 && !Methods.includes(req.method)) { + // res.setHeader('Allow', Methods.join(',')) + + if (req.method === 'OPTIONS') { + return res.send(Methods.join(', ')) + } else { + return res.status(405).send() + } + } else { + next() + } + }) + // Errors app.use(errorPages.handler) diff --git a/test/integration/http-test.js b/test/integration/http-test.js index df04029bc..e2a4cfa98 100644 --- a/test/integration/http-test.js +++ b/test/integration/http-test.js @@ -197,6 +197,21 @@ describe('HTTP APIs', function () { }) }) + describe('Not allowed method should return 405 and allow header', function (done) { + it('TRACE should return 405', function (done) { + server.trace('/sampleContainer2/') + // .expect(hasHeader('allow', 'OPTIONS, HEAD, GET, PATCH, POST, PUT, DELETE')) + .expect(405) + .end((err, res) => { + if (err) done(err) + const allow = res.headers.allow + console.log(allow) + if (allow === 'OPTIONS, HEAD, GET, PATCH, POST, PUT, DELETE') done() + else done(new Error('no allow header')) + }) + }) + }) + describe('GET API', function () { it('should have the same size of the file on disk', function (done) { server.get('/sampleContainer/solid.png')