Skip to content

Commit

Permalink
405 not allowed method
Browse files Browse the repository at this point in the history
  • Loading branch information
bourgeoa committed Jan 16, 2024
1 parent 809e0ac commit 33f7354
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/create-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
15 changes: 15 additions & 0 deletions test/integration/http-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit 33f7354

Please sign in to comment.