kstullich
kstullich

Reputation: 681

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?

Upvotes: 3

Views: 2157

Answers (2)

nonybrighto
nonybrighto

Reputation: 9581

You can make use of app.all(...) to handle both GET and POST requests but it also accepts other kind of requests such as PUT and DELETE. I prefer separating the GETand POST request though.

Upvotes: 0

Jakub Kutrzeba
Jakub Kutrzeba

Reputation: 1003

app.get(...) define endpoint that only matches with GET method. If you want to handle POST method you must supply seperate middleware in app.post(...)

Upvotes: 1

Related Questions