Friday 9 June 2017

Handling POST request on a GET route (express.js)

I am new to express and node together and seem to be stuck, with what seems to be, a simple issue. I have an API route that uses GET. Route:

app.get('/api/v1/all', getAllWords);

Then inside of the getAllWords callback function, I want to check if the request that was sent was of GET or POST. This is the code I have to check the request method:

function getAllWords(request, response) {
   let reply;
   if (request.method === 'GET') {
      console.log('This was a GET request');
      // handle GET here...
   }
   if (request.method === 'POST') {
      console.log('This was a POST request');
      reply = {
          "msg": "HTTP Method not allowed"
      };
      response.send(reply)
   }
}

When I use Postman to send off a GET request it works just fine. But when sending a POST request I get the generic express.js "Cannot POST /api/v1/all".

Postman screenshot

Why did it the response.send(reply) not work for the POST method?



via kstullich

No comments:

Post a Comment