So in Express you can do:
app.get('/logo/:version/:name', function (req, res, next) {
// Do something
}
and
app.all('/logo/:version/:name', function (req, res) {
// Do something
}
Is there a way to just have two methods (ie. GET and HEAD)? Such as:
app.get.head('/logo/:version/:name', function (req, res, next) {
// Do something
}
You can use .route() method.
function logo(req, res, next) {
// Do something
}
app.route('/logo/:version/:name').get(logo).head(logo);
Just pull out the anonymous function and give it a name:
function myRouteHandler(req, res, next) {
// Do something
}
app.get('/logo/:version/:name', myRouteHandler);
app.head('/logo/:version/:name', myRouteHandler);
Or use a general middleware function and check the req.method:
app.use('/logo/:version/:name', function(req, res, next) {
if (req.method === 'GET' || req.method === 'HEAD') {
// Do something
} else
next();
});
another version:
['get','head'].forEach(function(method){
app[method]('/logo/:version/:name', function (req, res, next) {
// Do something
});
});
You can also use the array spread operator if your route pattern is the same for multiple methods.
e.g.
const route = [
'/logo/:version/:name',
function handleRequest(req, res) {
// handle request
}
];
app.get(...route);
app.post(...route);
Related
I'm trying to understand how to use an application-level middleware (or at least usually used like this) like cookie-parser on route-level and conditionally.
I tried something like:
const myMiddleware = (req, res, next) => {
if (myCondition) {
return cookieParser();
} else {
next();
}
}
app.use('/admin', myMiddleware, (req, res) => {
res.sendStatus(401)
})
But it's not working, the request will be just stuck.
Is this possible?
Traditional cookie-parser implementation:
app.use(cookieParser())
cookieParser() returns a middleware function, i.e. a function that takes in req, res, next as arguments. You just have to pass it the arguments:
const cookieParserMiddleware = cookieParser();
const myMiddleware = (req, res, next) => {
if (myCondition) {
return cookieParserMiddleware(req, res, next);
}
next();
};
app.use("/admin", myMiddleware, (req, res) => {
res.sendStatus(401);
});
Notice that I'm creating the cookieParser middleware outside myMiddleware - technically we could also just do return cookieParser()(req, res, next) but recreating the same middleware again and again on every request would be wasteful.
I've also removed the else since the if block returns from the function (guard clause).
Let say I want to add multiple arguments.
Here's the code
function firstArgument(req, res, next) {
// Do something
}
function secondArgument(req, res, next) {
// Do something
}
app.get('/something', firstArgument, secondArgument, function(req, res, next) {
// Is it possible to do this?
});
Is it possible? if so how does it works? Can anyone explain it to me.
Thank you
All the answers are in the express docs - http://expressjs.com/es/guide/routing.html
To summarize, for your scenario you can use:
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})
or, without the second method.
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], function (req, res) {
res.send('Hello from D!')
})
Regarding how it works - it simply runs all the methods one after the other: when the next() method is called, the next method is being called.
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();
}
})
I want to do something like this. I want to use different middleware if there is or isn't a certain query string.
app.get("/test?aaa=*", function (req, res) {
res.send("query string aaa found");
});
app.get("/test", middleware, function (req, res) {
res.send("no query string");
});
However, I failed. Can anyone help me? Thanks.
EDIT: I only need to add the middleware, I dont care what the value of the query string is
If your intention is to run the same route handler and call the middleware depending on whether the query string matches, you can use some sort of wrapping middleware:
var skipIfQuery = function(middleware) {
return function(req, res, next) {
if (req.query.aaa) return next();
return middleware(req, res, next);
};
};
app.get("/test", skipIfQuery(middleware), function (req, res) {
res.send(...);
});
If you want to have two route handlers, you could use this:
var matchQueryString = function(req, res, next) {
return next(req.query.aaa ? null : 'route');
};
app.get("/test", matchQueryString, function (req, res) {
res.send("query string aaa found");
});
app.get("/test", middleware, function (req, res) {
res.send("no query string");
});
(these obviously aren't very generic solutions, but it's just to give an idea on how to solve this)
You can do this:
app.get("/test", middleware, function (req, res) {
res.send("no query string");
});
middleware = function(req, res, next) {
if(!req.query.yourQuery) return next();
//middleware logic when query present
}
I have a express route like this:
app.get('/', auth.authOrDie, function(req, res) {
res.send();
});
where authOrDie function is defined like that (in my auth.js module):
exports.authOrDie = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
res.send(403);
}
});
Now, when the user is not authenticated, I would like to verify if the http request has a Authorization (Basic) header. To do that, I would like to use the great connect middleware basicAuth().
As you know, Express is built on top of Connect, so I can use express.basicAuth.
The basicAuth is generally used like that:
app.get('/', express.basicAuth(function(username, password) {
// username && password verification...
}), function(req, res) {
res.send();
});
But, I would like to use it in my authOrDie function like that:
exports.authOrDie = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else if {
// express.basicAuth ??? ******
} else {
res.send(403);
}
});
****** How can I call the basicAuth function with the good parameters (req ? res ? next ? ...).
Thanks.
Calling the express.basicAuth function returns the middleware function to call, so you'd invoke it directly like this:
exports.authOrDie = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
return express.basicAuth(function(username, password) {
// username && password verification...
})(req, res, next);
}
});