Search code examples
node.jshttphttp-method

disable http method in express js


im doing nessus testing on my express app and here what i get

Based on tests of each method :

  • HTTP methods ACL CHECKOUT COPY DELETE GET HEAD LOCK MERGE MKACTIVITY MKCOL MOVE NOTIFY OPTIONS PATCH POST PROPFIND PROPPATCH PUT REPORT SEARCH SUBSCRIBE TRACE UNLOCK UNSUBSCRIBE are allowed on :

    / /login /styles

i done some search and actually end up here. disable HTTP methods, TRACK TRACE etc

the solution

const allowedMethods = ['GET','HEAD','POST'];

function onrequest(req, res) {
  if (!allowedMethods.includes(req.method))
    return res.end(405, 'Method Not Allowed');
  // ...
}

however i do not understand how to use the solution, @kiksy comment that: This method would sit in your front controller. eg from here: expressjs.com/en/starter/hello-world.html You would add it to line 3

but line 3 was "const port = 3000" it makes me confused

could someone help me on that

FYI, i could not comment becoz i dont have 50 rep


Solution

  • The comment is essentially saying that you can add this to any of your routes and you're checking the incoming method from each request to see if it is one of the whitelisted HTTP methods, and if not, you're going to return a 405 to let the user know that the method they've tried to hit is unsupported.

    You could use a middleware to blanket this for all requests.

    const allowedMethods = ['GET', 'HEAD', 'POST']
    
    app.use((req, res, next) => {
        if (!allowedMethods.includes(req.method)) return res.end(405, 'Method Not Allowed')
        return next()
    })