迷ったらコレ! Express.jsでnext()とreq.localsオブジェクトを使いこなす
Express.jsでnext()を使って次のミドルウェアに変数を渡す方法
方法
- 変数を宣言する
まず、ミドルウェア内で渡したい変数を宣言します。
const myVariable = "Hello, world!";
- next()に引数を渡す
次に、next()
関数に引数として変数を渡します。
app.use((req, res, next) => {
const myVariable = "Hello, world!";
next(myVariable);
});
- 次のミドルウェアで変数を受け取る
次のミドルウェアでは、req.locals
オブジェクトを使用して、渡された変数を受け取ることができます。
app.use((req, res, next) => {
const myVariable = req.locals.myVariable;
console.log(myVariable); // "Hello, world!"
});
例
以下は、ユーザー名とパスワードを受け取って認証を行うミドルウェアの例です。
app.use((req, res, next) => {
const username = req.body.username;
const password = req.body.password;
if (username === "admin" && password === "password") {
next();
} else {
res.status(401).send("Unauthorized");
}
});
この例では、username
とpassword
という変数をnext()
関数に渡しています。次のミドルウェアでは、req.locals.username
とreq.locals.password
を使用して、これらの変数を受け取ることができます。
注意事項
next()
関数に渡せる引数は、オブジェクト、配列、文字列など、何でも構いません。- 次のミドルウェアで渡された変数を受け取るには、
req.locals
オブジェクトを使用する必要があります。 req.locals
オブジェクトは、ミドルウェア間で情報を共有するために使用できます。
// app.js
const express = require('express');
const app = express();
// ミドルウェア1
app.use((req, res, next) => {
const myVariable = "Hello, world!";
next(myVariable);
});
// ミドルウェア2
app.use((req, res, next) => {
const myVariable = req.locals.myVariable;
console.log(myVariable); // "Hello, world!"
res.send("Hello, world!");
});
app.listen(3000);
このコードを実行すると、ブラウザで http://localhost:3000
にアクセスすると、コンソールに "Hello, world!" と出力され、ブラウザには "Hello, world!" と表示されます。
別の例
// app.js
const express = require('express');
const app = express();
// 認証ミドルウェア
app.use((req, res, next) => {
const username = req.body.username;
const password = req.body.password;
if (username === "admin" && password === "password") {
next();
} else {
res.status(401).send("Unauthorized");
}
});
// 認証後の処理
app.use((req, res, next) => {
console.log("認証成功!");
res.send("Welcome!");
});
app.listen(3000);
このコードを実行すると、ブラウザで http://localhost:3000
にアクセスし、POST
リクエストで username
と password
を送信すると、認証に成功し、コンソールに "認証成功!" と出力され、ブラウザには "Welcome!" と表示されます。
next()
を使って次のミドルウェアに変数を渡す方法は、Express.jsでミドルウェア間で情報を共有する際に非常に便利です。上記のサンプルコードを参考に、ぜひ活用してみてください。
Express.jsで次のミドルウェアに変数を渡す他の方法
req.locals
オブジェクトは、ミドルウェア間で情報を共有するために使用できます。next()
関数に引数を渡す代わりに、req.locals
オブジェクトにプロパティを設定することで、次のミドルウェアでそのプロパティにアクセスできます。
// ミドルウェア1
app.use((req, res, next) => {
req.locals.myVariable = "Hello, world!";
next();
});
// ミドルウェア2
app.use((req, res, next) => {
const myVariable = req.locals.myVariable;
console.log(myVariable); // "Hello, world!"
res.send("Hello, world!");
});
グローバル変数を使用して、ミドルウェア間で情報を共有することもできます。ただし、グローバル変数の使い過ぎはコードの可読性や保守性を低下させるので、注意が必要です。
// グローバル変数
const myVariable = "Hello, world!";
// ミドルウェア1
app.use((req, res, next) => {
// グローバル変数を使用
console.log(myVariable);
next();
});
// ミドルウェア2
app.use((req, res, next) => {
// グローバル変数を使用
console.log(myVariable);
res.send("Hello, world!");
});
カスタムミドルウェアを使用する
特定のタスクを実行するカスタムミドルウェアを作成して、そのミドルウェア内で情報を共有することができます。
// カスタムミドルウェア
const myMiddleware = (req, res, next) => {
const myVariable = "Hello, world!";
// ...
next();
};
// ミドルウェアの使用
app.use(myMiddleware);
app.use((req, res, next) => {
// ...
res.send("Hello, world!");
});
- 大量のデータを共有したり、複雑なロジックを含む場合は、カスタムミドルウェアを使用するのが良いでしょう。
- グローバル変数は、最後の手段としてのみ使用してください。
next()
関数に引数を渡す以外にも、Express.jsで次のミドルウェアに変数を渡す方法はいくつかあります。それぞれの方法の特徴を理解して、状況に応じて適切な方法を選択してください。
javascript node.js express