Using express middleware only for a GET request - node.js

The way I understand it, if I do something like:
app.use('/something', function(req, res, next) {
// some content here
});
This basically means that if there's a request to 'something', then the middleware (my function) is executed before the next function.
So if I have something like this to handle a GET request,
app.get('/something', function(req, res, next) {
console.log('hello');
});
Then 'hello' is going to be printed out after my original function has finished executing.
But how do I make it so that my middleware function is just executed when I ONLY make a GET request and not a POST request?

For a GET only middleware, just do the following
// Get middleware
app.get('/something', function(req, res, next) {
console.log('get hello middleware');
next();
});
// GET request handler
app.get('/something', function(req, res) {
console.log('get hello');
res.end();
});
// POST request handler
app.post('/something', function(req, res) {
console.log('post hello');
res.end();
});

app.post('/something', your_middleware, function(req, res, next) {
console.log('hello');
});
Only during the post request your_middleware will be executed.
your_middleware should be a function as follows:
function(req, res, next){
....
next()
}
you can pipe in as many middlewares you want in this way for a specific route and request type

Related

Express trigger not found route for each route

I am using express with a pattern like this :
app = express();
router = express.Router();
router.use((req, res, next) => {
console.log("my middleware before");
next();
});
router.get('/foo', (req, res, next) => {
console.log("My route");
res.send("<h1>Hello</h1>")
next();
});
router.use((req, res, next) => {
console.log("my middleware after");
});
app.use("/", router);
app.get("*", (req, res, next) => {
console.log("page not found");
throw new Error("Not Found");
});
app.use((err, req, res, next) => {
console.log("Error occure");
res.send("<h1>Error</h1>");
});
app.listen(3000);
When I request '/foo' I would like to have
> my middleware before
> My route
> my middleware after
<h1>Hello</h1>
And when I request anything else :
> page not found
> Error occure
<h1>Error</h1>
But the page not found route is executed in each case, even if route '/foo' is done.
How can I get it working ?
When I run your code, I do not get the output you show, so something about your real code is apparently different than what you show in your question.
I do get a slightly confusing output and that happens because the browser sends both the /foo request and a /favicon.ico request. When I run it, the /foo request generates the desired output. The /favicon.ico request generates some middleware output and then gets stuck in the router.
If you filter out the /favicon.ico route (so that it doesn't confuse things) by adding this as the first route:
app.get("/favicon.ico", (req, res) => {
res.sendStatus(404);
});
Then, I get exactly this output in the server logs when I request /foo:
my middleware before
My route
my middleware after
Which is exactly what you asked for.
There is, however, a general problem with this:
router.use((req, res, next) => {
console.log("my middleware after");
});
Because it will catch and hang any legit requests that haven't yet had a response sent. You can't really code it that way unless you only don't call next() if a response has already been sent.
As a bit of a hack, you could do this:
router.use((req, res, next) => {
console.log("my middleware after");
// if response hasn't yet been sent, continue routing
if (!res.headersSent) {
next();
}
});
But, there is probably a better way to solve whatever problem you're actually trying to solve. If, in the future, you describe your real problem rather than a problem you have with your solution, then you allow people to offer a wider range of solutions to your real problem including things you haven't even thought of to try. As your question is written right now, we're stuck down the solution path you followed and don't know what the original problem was. That is, by the way, referred to as an XY Problem.
Do this
app = express();
router = express.Router();
router.use((req, res, next) => {
console.log("my middleware before");
next();
});
router.get('/foo', (req, res, next) => {
// use locals to record the fact we have a match
res.locals.hasMatch = true
console.log("My route");
res.send("<h1>Hello</h1>")
next();
});
router.use((req, res, next) => {
console.log("my middleware after");
});
app.use("/", router);
app.get("*", (req, res, next) => {
console.log("page not found");
throw new Error("Not Found");
});
app.use((err, req, res, next) => {
// check locals to see if we have a match
if (!res.locals.hasMatch) {
console.log("Error occure");
res.send("<h1>Error</h1>");
}
});
app.listen(3000);
You can utilize middlewares and even nest them.
You can implement it like this:
Middlewares
const before = (req, res, next) => {
console.log("my middleware before");
next(); // Supply next() so that it will proceed to the next call,
// in our case, since this is supplied inside the router /foo, after this runs, it will proceed to the next middleware
};
const after = (req, res, next) => {
console.log("my middleware after");
};
Route
// Supply "before" middleware on 2nd argument to run it first when this route is called
router.get('/foo', before, (req, res, next) => {
console.log("My route");
res.send("<h1>Hello</h1>");
next(); // Call next() to proceed to the next middleware, or in "after" middleware
}, after); // Supply the "after" middleware
Once ran, it will proceed with this desired result sequence:
> my middleware before
> My route
> my middleware after
Unmatched Routes Handler
Instead of this
app.get("*", (req, res, next) => {
console.log("page not found");
throw new Error("Not Found");
});
You can implement it like this instead, this is after your app.use("/", router); -- This will handle your unmatched routes:
Sources:
https://stackoverflow.com/a/44540743/6891406
https://stackoverflow.com/a/16637812/6891406
app.use((req, res, next) => {
console.log("page not found");
res.json({ error: 'Page not Found' })
});

NodeJS Express: How to interrupt the routing from outside the middleware/router?

I implemented a very simple middleware to check the permissions for the user:
app.js
...
var security = require('./lib/security');
app.use(security.init);
...
lib/security.js
var session;
var request;
var response;
function init(req, res, next) {
request = req;
response = res;
session = req.session;
next();
}
function adminRequired(){
if (!isAdmin()){
response.redirect('/login');
response.end();
return true;
}
return false;
}
...
The best way I found to interrupt the flow is the following:
routes/mycontroller.js
router.get('/', function(req, res, next) {
if(security.adminRequiredHtml()){return;} // now it actually interrupt the execution
res.render('admin',{});
res.end();
});
However, I would like to use it like this:
routes/mycontroller.js
router.get('/', function(req, res, next) {
security.adminRequiredHtml(); // <- interrupt the request
res.render('admin',{});
res.end();
});
It correctly perform the redirect, but the execution continues :(
I've tried a few solutions like but it doesn't really work:
response.end() -> close the output but continues the execution
process.end() -> it's too radical, terminates the execution but it also kill the server :(
I've been thinking about using a throw but I don't know where to catch it and make it terminate gracefully (no stacktrace)
You could create a custom Router that is secured and add your secure Routes to that:
var secureRouter = express.Router();
// every request on this router goes throug this
secureRouter.use('*', function (req, res, next) {
if(isAdmin()) next();
// if you don't call next() you interrupt the request automaticly
res.end();
});
// protected routes
secureRouter.get('/user', function(req, res){/* whatever */});
secureRouter.post('/user', function(req, res){/* whatever */});
app.use(secureRouter);
// not protected
app.get('/api', function(req, res){/* whatever */});
Express doc for using middlewares
You're actually looking for middleware, I think.
function myMiddleware (req, req, next) {
if (!isAdmin()) {
res.redirect('/login');
res.end();
} else {
//Proceed!
next()
}
}
router.get('/', myMiddleware, function(req, res, next) {
res.render('admin',{});
res.end();
});
You can chain as many of those as you'd like to handle whatever logic you need. Just make sure you call next() if you're supposed to move on!

how to group api in express

Here is the example:
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
//code
});
app.post('/user/register', function(req, res) {
//code
})
app.put('/user/register', validateToken, function(req, res) {
//code
})
app.delete('/user/delete', validateToken, function(req, res) {
//code
})
If I have 10 api that need validToken, I should add validToken middleware 10 times, like:
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
....
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
How can I group api by using the same middleware?
Here's how to re-use the same callback function for multiple routes (like middleware):
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
// code
});
app.post('/user/register', function(req, res) {
// code
});
// Be sure to specify the 'next' object when using more than one callback function.
app.put('/user/register', validateToken, function(req, res, next) {
// code
next();
});
app.delete('/user/delete', validateToken, function(req, res, next) {
// code
next();
});
Also, you can replace app.METHOD (e.g. .post, .get, .put, etc.) with app.all and your callback will be executed for any request type.
Just wrong, so do not put into mass participation of the (Google translated from: 刚才看错了,改成这样就不用放进传参了)
var group = {url:true,url:true,url:true};
app.use(function(req,res,next){
if(group[req.url]){
// Do something with request here
next();
} else {
next();
}
})

Express dynamic route's get added to static routes middleware stack

I am defining static & dynamic routes in Express, and I have built a generic responder to send response to client. The responder is global to all routes and thus added at the end.
However, when I define static routes, matching dynamic routes' middlewares get added to the stack before the responder.
To illustrate:
server.get('/hello/test', function(req, res, next) {
console.log('/hello/test');
next();
});
server.get('/hello/:page', function(req, res, next) {
console.log('/hello/:page');
next();
});
server.use(function(req, res, next) {
res.status(200).send('test');
});
Calling curl localhost:3000/hello/test will console.log both '/hello/test' and '/hello/:page' before the responder middleware gets called. I only want the first matching routes middleware to be called.
Is there anyway to prevent this behaviour?
The method next() is passing the control to the next handler.
You could solve your issue just removing the next() call from your routes, and putting the middleware into a function:
server.get('/hello/test', myMiddleware(req, res, next), function(req, res) {
console.log('/hello/test');
});
server.get('/hello/test_b', myMiddleware(req, res, next), function(req, res) {
console.log('/hello/test_b');
});
server.get('/hello/:page', myMiddleware(req, res, next), function(req, res) {
console.log('/hello/:page');
});
server.get('*', myMiddleware(req, res, next), function (req, res) {
res.type('txt').send('Not found');
});
function myMiddleware(req, res, next) {
console.Log("in midleware")
next();
}

What is ending a route

Supose i have this route code:
app.get('/', function(req, res) {
res.send('Hello world!');
});
app.get('/something', function(req, res) {
// Do something
});
If i visit the / route in my browser, the "Hello world" message will show, and my response will have ended.
Question: Is it the absence of next() in this router, or the res.send() that ENDS the http request?
It's res.end() that actually ends the response, but res.send() calls this.
You can see this in the source here.
Sorry, but if you want to log every request including '/' then you have to reorder using:
app.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
app.get('/', function(req, res) {
res.send('Hello world!');
});

Resources