pittuzzo
pittuzzo

Reputation: 491

When to use express.use, express.get, and express.post

What is the differences betwenn the 3 functions use/get/post with express? In which case is better to use express.use instead of express.get/post?

Upvotes: 0

Views: 173

Answers (3)

Amit
Amit

Reputation: 39

app.use is used to load the middleware functions to add some functionality in the middle before the execution of the next middleware or app.get function which is actually a route derived from HTTP method. enter image description here

Upvotes: 0

Rohit Rai
Rohit Rai

Reputation: 375

app.use is used to load the middleware functions. app.use example:

var myUseFunction = function (req, res, next) {
  console.log('Hello World!');
  next();
}

app.use(myUseFunction);

It does not have limitations for any restful api http verbs like POST, GET, PUT, PATCH, and DELETE.

app.get is route method is derived from one of the HTTP methods, and is attached to an instance of the express class.It serves the pupose of get request of apis.

GET method route

 app.get('/', function (req, res) {
    res.send('GET request to the page');
 });

app.post is route method is derived from of the HTTP methods, and is attached to an instance of the express class. It serves the pupose of post request of apis.

POST method route

app.post('/', function (req, res) {
  res.send('POST request to the page');
});

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160201

use is for middleware, e.g., all requests. It says it right in the docs:

Mounts the specified middleware function or functions at the specified path.

get is... for GET requests. post is for POST requests.

Upvotes: 0

Related Questions