Assuming I have two routes one with params, one without:
/foo?bar
/foo
I want to use two different handlers for these two routes. I know I can do something like this.
app.use('/foo', (req, res) => {
if (req.params.foo !== undefined) {
// do something
} else {
// do something else
}
})
But, it would make the code harder to read. Is there a way to match a route that has a parameter? I would like to manage this situation:
app.use('/foo', x);
app.use('/foo?bar', y);
As far as I know, queries can not be filtered on use handler.
Instead, I made out with the very similar situation by using next.
app.use('/foo', (req, res, next) => {
if (req.query.foo !== undefined) return next();
//if foo is undefined, it will look for other matching route which will probably the next '/foo' route
/* things to do with foo */
});
app.use('/foo', (req, res) => {
//things to without foo
});
https://expressjs.com/en/guide/using-middleware.html
this document may also help you
How about this?
const express = require('express');
const app = express();
// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
res.send('This is foo');
});
// curl -X GET http://localhost:3000/foo/bar
app.get('/foo/:?bar', function (req, res, next) {
res.send('This is foo with bar');
});
app.listen(3000);
Related
Normally, a function is passed as callback in app.use(), like so:
const express = require('express');
const app = express();
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
In the case of node-expose-sspi however a method is passed:
const express = require('express');
const { sso } = require('node-expose-sspi');
const app = express();
app.use(sso.auth()); //stores something in req.sso
app.use((req, res, next) => {
res.json({
sso: req.sso,
});
});
Why is the method passed with ()? If it uses () why is it no called immediately (without arguments)?
Also, how can I wrap a method in a callback function, e.g.
app.use(myCallback);
function myCallback(req, res, next) {
sso.auth(); //req.sso is undefined
}
app.use(sso.auth());
calls sso.auth() and app.use()s its return value.
You can find over here in the node-expose-sspi source that .auth() indeed returns a new middleware function.
As for the second question
Also, how can I wrap a method in a callback function
you shouldn't do that – Express will call your used middlewares in order; a subsequent callback will have access to whatever a previous middleware has injected into the request.
If you for some reason really need to do that,
const ssoAuth = sso.auth();
function myCallback(req, res, next) {
ssoAuth(req, res, () => {
// whatever would regularly be in `myCallback`
next();
});
}
``
Hi I am facing the problem that I need to log each incomming request and the associated responses in my database. My current solution looks like the following:
./routes/customer.js
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.status(200).send(req.allCustomers);
next(); // <- this is my personal problem
});
./middleware/logging.js
module.exports = function (req, res, next) {
db.query(
`INSERT INTO logging SET ?`,
{
request: JSON.stringify([req.body, req.params]),
response: JSON.stringify(req.response)
}
);
}
routes declaration
module.exports = function(app) {
app.use(express.json());
app.use('/api/customers', customers); // <- ROUTE ./routes/customer.js
app.use(logging); // <- MIDDLEWARE ./middleware/logging.js
}
I already mentioned my problem in my first piece of code. It is really repetitive to call next() in every route manually and I would like to avoid this. I already tried to load the middleware before all routes, call next() in the middleware function and execute my db query afterwards but I do not have the response at this point because of the async functionality.
Is there any way to handle this situation or will I need keep calling next() at the end of each route function?
If you don't want to call next() from your routes, you cannot have middleware run after them. It needs to be placed before. But can you get the response inside a middleware that runs before the route? The answer is yes!
It may be a little hacky, but since your route uses res.send(), you can use that to your advantage. By running before your route, your middleware can hijack that res.send function, to make it do other stuff.
./routes/customer.js
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.send(req.allCustomers); // We'll hijack this
});
./middleware/logging.js
module.exports = function (shouldBeLoggedFunc) {
return function (req, res, next) {
if (shouldBeLoggedFunc(req)) {
// Store the original send method
const _send = res.send;
// Override it
res.send = function (body) {
// Reset it
res.send = _send;
// Actually send the response
res.send(body);
// Log it (console.log for the demo)
console.log(`INSERT INTO logging SET ?`, {
request: JSON.stringify([req.body, req.params]),
response: JSON.stringify(body)
});
};
}
next();
};
};
routes declaration
function shouldBeLogged(req) {
// Here, check the route and method and decide whether you want to log it
console.log(req.method, req.path); // e.g. GET /api/customers
return true;
}
module.exports = function(app) {
app.use(express.json());
app.use(logging(shouldBeLogged)); // <- Place this before your routes
app.use('/api/customers', customers);
};
when you use express.Router class like you already did and then use this code
app.use('/api/customers', customers);
you don't have to write 'next()' inside callback function in router.get .
there is an example
create a router file named birds.js in the app directory, with the following content:
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then, load the router module in the app:
var birds = require('./birds')
// ...
app.use('/birds', birds)
I am writing APIs and wanted to understand what is a good way to add middleware shared by multiple routes. The middlewares does the same things in each route, like validating hosts/ip, validate user, etc.
The req object gets loaded with other objects in each of the middlewares like req.host, req.ip, req.username etc.
app.post("/route1", middleware1, middleware2, middleware3, middleware4);
app.post("/route2", middleware1, middleware2, middleware3, middleware4);
const middleware1 = (req, res, next) => {
// does something to validate user
req.username = "username"
next();
}
const middleware2 = (req, res, next) => {
// host validation
req.host = "something modified in validation"
next();
}
const middleware3 = (req, res, next) => {
// checks for mac and ip
req.mac = "mac addr"
next();
}
const middleware4 = (req, res, next) => {
res.send();
}
Or something like this:
app.post("/route1", middleware1);
app.post("/route2", middleware1);
const middleware1 = (req, res) => {
// does something to validate user
req.username = "username"
middleware2(req, res);
}
const middleware2 = (req, res) => {
// host validation
req.host = "something modified in validation"
middleware3(req, res);
}
const middleware3 = (req, res) => {
// checks for mac and ip
req.mac = "mac addr"
middleware4(req, res);
}
const middleware1 = (req, res) => {
res.send();
}
Thanks.
Generally I wouldn't call middlewares directly from another middleware. It mixes responsibilities of middleware logic and where the middleware is used.
Express is much more configurable than you think though. You can also install common middlewares in common paths:
If all routes use the middlewares:
// How common middlewares are normally installed:
app.post(middleware1);
app.post(middleware2);
app.post(middleware3);
app.post(middleware4);
// Alternative, less common way to do it:
app.post(middleware1,middleware2,middleware3,middleware4);
If only a specific pattern of urls use the middlewares:
// Use a regexp:
app.post(/route(1|2)/, middleware1, middleware2, middleware3, middleware4);
// Or if you don't like regexp, use globs:
app.post('route*', middleware1, middleware2, middleware3, middleware4);
// Or a more specific glob pattern:
app.post('route1?2?', middleware1, middleware2, middleware3, middleware4);
If all url in a subpath use the middlewares. For example, lets say if all urls in /route/... use the middlewares:
const route = express.Router();
app.use('/route',route);
route.post(middleware1);
route.post(middleware2);
route.post(middleware3);
route.post(middleware4);
If none of the above appeal to you you can still use your second option but instead of calling middlewares inside each other you write a middleware to initialize middlewares:
function commonMiddlewares (req, res, next) {
middleware1(req,res,function() {
middleware2(req,res,function() {
middleware3(req,res,function() {
middleware4(req,res,next);
});
});
});
}
Which can be written in a less nested way:
function commonMiddlewares (req, res, next) {
function runMiddleware4 () {
middleware4(req,res,next);
}
function runMiddleware3 () {
middleware3(req,res,runMiddleware4);
}
function runMiddleware2 () {
middleware2(req,res,runMiddleware3);
}
middleware1(req,res,runMiddleware2);
}
const express = require('express')
const { routesMiddleware } =require('./middlewares')
const { pureVaidationsFunctions1 } =require('./services')
const rout1 =express.Router()
const rout2 =express.Router()
const app = express()
app.use('/route1',route1)
app.use('/route2',route2)
// routesMiddleware a middleware to handle the execution of list of functions
// pureVaidationsFunctions1 list of funtions that `routesMiddleware` will consume
route1.post(routesMiddleware(pureVaidationsFunctions1))
route2.post(routesMiddleware(pureVaidationsFunctions2))
make sense?
You can specify multiple middlewares, see the app.use docs:
An array of combinations of any of the above.
You can create a file of all middlewares like -
middlewares.js
module.exports = [
function(req, res, next){...},
function(req, res, next){...},
function(req, res, next){...},
.
.
.
function(req, res, next){...},
]
and as then simply add it like:
/*
you can pass any of the below inside app.use()
A middleware function.
A series of middleware functions (separated by commas).
An array of middleware functions.
A combination of all of the above.
*/
app.use(require('./middlewares.js'));
Note - Do this only for those middlewares which will be common for all such requests.
I would like to know how to choose between two different middleware functions, depending on the request for the endpoint. It could look something like this:
router.post("/findAvailableAgents", middleware1 || middleware2, (req, res) => {
// endpoint body
})
You could use another middleware which decides whether to choose middleware1 or middleware2
const decideMiddleware = (req, res, next) => {
if(condition) {
return middleware1(req, res,next)
} else {
return middleware2(req, res,next)
}
}
And use it in your code
router.post("/findAvailableAgents", decideMiddleware, (req, res))
There is two ways of achieve optional middleware behaviour:
1) Create another middleware, that checks condition and then passes all the parameters into the desired middleware. Example:
const middlewareStrategy = (req,res,next) => {
if(req.body.token1){
return middleware1(req,res,next);
}
return middleware2(req,res,next);
};
router.post("/findAvailableAgents", middlewareStrategy, handler);
2) Make middleware logic execution in a condition-driven manner. Example:
const middleware1 = (req,res,next) => {
if(req.body.token){
// execute some logic, then
return next();
}
// skip this middleware
next();
};
router.post("/findAvailableAgents", middleware1, middleware2, handler);
Now you can add multiple middleware using a below peice of code
app.get('/',[middleware.requireAuthentication,middleware.logger], function(req, res){
res.send('Hello!');
});
Trying to get URl parameters in express js,but got empty object.
var password= require('./routes/password');
app.use('/reset/:token',password);
password.js
router.get('/', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
console.log(req.params) output is {}
Access url :http://localhost:3000/reset/CiVv6U9HUPlES3i0eUsNwK9zb7xVZpfHsQNuzMNWqLlGA4NJKoagwbcyiUZ8
By default, nested routers do not get passed any parameters that are used in mountpaths from their parent routers.
In your case, app is the parent router, which uses /reset/:token as a mountpath, and router is the nested router.
If you want router to be able to access req.params.token, create it as follows:
let router = express.Router({ mergeParams : true });
Documented here.
You are getting params and query mixed up.
Query approach
Your code should look like this when using query values for the example url: www.example.com?token=123&foo=bar
router.get('/', function(req, res, next) {
console.log(req.query);
console.log(req.query.token); // to log value of token
console.log(req.query.foo); // to log value of foo
res.send(req.query);
});
Params approach
Your code should look like this when using params values for the example url: www.example.com/123
router.get('/:token', function(req, res, next) {
console.log(req.params);
console.log(req.params.token); // to log value of token
res.send(req.params);
});
Instead you can use a middleware to log the path params:
const logger = (req, res, next)=>{
console.log(req.params)
res.send(req.params)
next()//<----very important to call it.
};
app.use(logger); //<----use to apply in the app
router.get('/', (req, res, next)=>res.send('Logged.'));
Actually you messed it up a little bit. You have to pass instance of express to your module.
Server.js:
//adding modules
require('./routes/password')(app);
Password.js:
module.exports = function(router) {
router.get('/reset/:token', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
//and so on.. your routes go here
}