【Express】next()で次のミドルウェアに変数を渡したい


router.get('/', function (req, res, next) {
	const name = 'Simmon';
	next(name);
}, exampleFunc );

function exampleFunc(req, res, name) {
	console.log(name);
}

上記のような感じでnext()の引数に渡せばいけるのかなあと思ったが、それはできないとのこと。

Expressにはres.localsというプロパティが用意されているのでそれを使うらしい。
使い方は以下のような感じ。


router.get('/', function (req, res, next) {
	res.locals.name = 'Simmon';
	next();
}, exampleFunc );

function exampleFunc(req, res) {
	console.log(res.locals.name); // Simmon
}

参考