Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express: Execute hook on every HTTP request, before app.get() and app.post()?

I don't want to put an authentication function at the top of every app.get(), how can I execute code on every request, before app.get()?

like image 366
Farzher Avatar asked Oct 28 '12 04:10

Farzher


People also ask

What is POST () in Express?

js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.

What is difference between GET and POST method in Express?

Both GET and POST method is used to transfer data from client to server in HTTP protocol but Main difference between POST and GET method is that GET carries request parameter appended in URL string while POST carries request parameter in message body which makes it more secure way of transferring data from client to ...

What is get and post method in node JS?

Note: If you are going to make GET, POST request frequently in NodeJS, then use Postman , Simplify each step of building an API. In this syntax, the route is where you have to post your data that is fetched from the HTML. For fetching data you can use bodyparser package. Web Server: Create app.

What does APP POST () do?

The app. post() method routes all the HTTP POST requests to the specified path with the specified callback functions.


1 Answers

Set up a middleware before your routes:

function myMiddleware (req, res, next) {    if (req.method === 'GET') {       // Do some code    }     // keep executing the router middleware    next() }  app.use(myMiddleware)  // ... Then you load the routes 
like image 56
Herman Junge Avatar answered Oct 14 '22 22:10

Herman Junge