Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express, diff between route.use() ,route.all(),route.route()

If router.all() just match all methods,could it be instead by router.use()? and what router.use() diff between router.route()?

like image 221
sinbar Avatar asked Aug 30 '17 02:08

sinbar


People also ask

What does Express router () do?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

What is the difference between adding Middlewares using router use () and app use ()?

In short, app. use('/first', router) mounts the middleware at path /first, then router. get sets the subpath accordingly.

What is the difference between app use and app all?

app. all also accepts a regex as its path parameter. app. use does not accept a regex, but will automatically match all routes that extend the base route.

What is the difference in purpose between a route in react and a route in Express?

Express will handle your backend routes whereas React (with react-router or any front-end routing lib) will handle frontend routes. Your React application will probably be an SPA (single page application), meaning that your server (express or something else) will have to serve the index.


1 Answers

router.all: What this means is, it doesn't matter the method of the request.. (post, get, put), if the url matches, execute the function.

ex- router.all("/abc",fn) will be work for all request to /abc

router.use() : router.use() helps you write modular routes and modules.. You basically define a middle ware for routes.

router.use("/pqr", pqrRoutes)

now for all requests that start with /pqr like /pqr/new or /pqr/xyz can be handles inside the pqrRoutes.

router.route(): this is nice way to define the different Method implementations for a single url end point.

lets just say you have two api end points. router.get("/jkl") and router.post("/jkl"), with router.route() you cam sort of combine these different api handlers..

you can say router.route("/jkl").get(fn1).post(fn2)

like image 103
rootkill Avatar answered Oct 10 '22 16:10

rootkill