sradha
sradha

Reputation: 2244

How to combine app.post and app.get to one in node js

I am trying to make one router for login page post and get request.

below is my code :

  app.get('/login', getLoginPage);
  app.post('/login', doLogin);

Here I am using app.all to combine both , but I am not getting any idea how to handle it in all.

What I have tried so far .

app.all('/login', handler); 
var handler = function(req, res){
   console.log(req);
   if(req.method=="POST")
   {
   getLoginPage;
   }
   if(req.method=="GET")
   {
   doLogin
   }
}

const {getLoginPage,doLogin} = require('./controller/login');

Here app.get and app.post working fine for me except app.all. Here I am using express js. Please suggest .

Upvotes: 0

Views: 2435

Answers (5)

aldyadk
aldyadk

Reputation: 41

Tried invoking the functions and pass the req and res parameters to those functions

app.all('/login', handler); 
function handler(req, res){
  if(req.method=="POST"){
    getLoginPage(req, res);
  } else if(req.method=="GET"){
    doLogin(req, res);
  }
}

edit: change to function declaration instead of function expression to avoid hoisting issues

Upvotes: 0

einacio
einacio

Reputation: 92

HOISTING!!!

It's really just scope. You have a function expression, not a declaration. Declarations get hoisted but definitions do NOT. So when you call handler, handler is not defined yet since it's function expression comes bellow it.

So no need to change your code, except the order of things. Do this and it will work

var handler = function(req, res) {
  if (req.method == "POST") {
    console.log("POST");
  }
  if (req.method == "GET") {
    console.log("GET");
  }
};

app.all("/login", handler);

Read about scopes in function declaration vs expression

Upvotes: 1

Yuva
Yuva

Reputation: 141

Try following use method. It will accept all types of methods and you can apply conditions there:

app.use('/login', function (req, res, next) {
  console.log('Request Type:', req.method)
  if(req.method=="POST")
  {
    getLoginPage;
  }
  else if(req.method=="GET")
  {
    doLogin;
  }
});

Upvotes: 0

David Joos
David Joos

Reputation: 946

I would do it like so (full working example):

var express = require('express');
var app = express();


app.route('/test')
  .get((req, res) => getLoginPage(req, res))
  .post((req, res) => doLogin(req, res))

doLogin = (req, res) => {
  res.send('doLogin');
}

getLoginPage = (req, res) => {
  res.send('getLoginPage');
}

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Upvotes: 3

ROAL
ROAL

Reputation: 1779

You need to invoke the functions in your app.all handler.

app.all('/login', handler);
var handler = function (req, res) {
    console.log(req);
    if (req.method == "POST") {
        getLoginPage(req, res);
    }
    if (req.method == "GET") {
        doLogin(req, res);
    }
}

Upvotes: 0

Related Questions