Skip to content

Commit 33f7354

Browse files
committed
405 not allowed method
1 parent 809e0ac commit 33f7354

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lib/create-app.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,33 @@ function createApp (argv = {}) {
117117
// Attach the LDP middleware
118118
app.use('/', LdpMiddleware(corsSettings))
119119

120+
// https://stackoverflow.com/questions/51741383/nodejs-express-return-405-for-un-supported-method
121+
app.use(function (req, res, next) {
122+
const AllLayers = app._router.stack
123+
const Layers = AllLayers.filter(x => x.name === 'bound dispatch' && x.regexp.test(req.path))
124+
125+
const Methods = []
126+
Layers.forEach(layer => {
127+
for (const method in layer.route.methods) {
128+
if (layer.route.methods[method] === true) {
129+
Methods.push(method.toUpperCase())
130+
}
131+
}
132+
})
133+
134+
if (Layers.length !== 0 && !Methods.includes(req.method)) {
135+
// res.setHeader('Allow', Methods.join(','))
136+
137+
if (req.method === 'OPTIONS') {
138+
return res.send(Methods.join(', '))
139+
} else {
140+
return res.status(405).send()
141+
}
142+
} else {
143+
next()
144+
}
145+
})
146+
120147
// Errors
121148
app.use(errorPages.handler)
122149

test/integration/http-test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,21 @@ describe('HTTP APIs', function () {
197197
})
198198
})
199199

200+
describe('Not allowed method should return 405 and allow header', function (done) {
201+
it('TRACE should return 405', function (done) {
202+
server.trace('/sampleContainer2/')
203+
// .expect(hasHeader('allow', 'OPTIONS, HEAD, GET, PATCH, POST, PUT, DELETE'))
204+
.expect(405)
205+
.end((err, res) => {
206+
if (err) done(err)
207+
const allow = res.headers.allow
208+
console.log(allow)
209+
if (allow === 'OPTIONS, HEAD, GET, PATCH, POST, PUT, DELETE') done()
210+
else done(new Error('no allow header'))
211+
})
212+
})
213+
})
214+
200215
describe('GET API', function () {
201216
it('should have the same size of the file on disk', function (done) {
202217
server.get('/sampleContainer/solid.png')

0 commit comments

Comments
 (0)