serverMiddleware プロパティ
サーバーサイドミドルウェアを定義します。
-
型:
Array
-
要素:
String
またはObject
またはFunction
-
要素:
Nuxt はカスタムミドルウェアを追加できる connect インスタンスを内部で作ります。これにより外部サーバーを必要とせずに通常は /api
ルート)を登録できます。
connect 自体はミドルウェアなので、登録されたミドルウェアは nuxt start
と express-template のようなプログラムで使われるミドルウェアとして使う場合の両方で動作します。Nuxt モジュール もまた this.addServerMiddleware() を使って serverMiddleware
を提供できます。
それらに加え、デフォルト値が true
の prefix
オプションを導入しました。サーバーミドルウェアに router base を追加します。
例:
-
サーバーミドルウェアパス:
/server-middleware
-
Router base:
/admin
-
prefix: true
の場合(デフォルト):/admin/server-middleware
-
prefix: false
の場合:/server-middleware
サーバーミドルウェア vs ミドルウェア!
クライアントサイドやサーバーサイドレンダリングで Vue によって各ルートの前に呼び出されるルートのミドルウェア と混同しないでください。 serverMiddleware
プロパティに列挙されているミドルウェアは vue-server-renderer
の前にサーバーサイドで実行され、API リクエストの処理やアセットの提供などのサーバー固有のタスクに使用できます。
使い方
もしミドルウェアが文字列の場合、 Nuxt はそのミドルウェアを自動的に解決し要求します。
import serveStatic from 'serve-static'
export default {
serverMiddleware: [
// redirect-ssl npm パッケージを登録します
'redirect-ssl',
// /server-middleware/* を処理するために、プロジェクトの server-middleware ディレクトリからファイルを登録します
{ path: '/server-middleware', handler: '~/server-middleware/index.js' },
// カスタムインスタンスを作成することもできます
{ path: '/static2', handler: serveStatic(__dirname + '/static2') }
]
}
カスタムサーバーミドルウェア
カスタムミドルウェアの作成も可能です。詳細については Connect Docs を参照してください。
ミドルウェア(server-middleware/logger.js
):
export default function (req, res, next) {
// req は Node.js の HTTP リクエストオブジェクトです
console.log(req.url)
// res は Node.js の HTTP レスポンスオブジェクトです
// next は 次のミドルウェアを呼び出すための関数です。
// ミドルウェアがエンドポイントでない場合、関数の最後で next を呼び出すのを忘れないでください!
next()
}
serverMiddleware: ['~/server-middleware/logger']
カスタム API エンドポイント
サーバーミドルウェアも Express を拡張できます。これにより REST エンドポイントを作成できます。
const bodyParser = require('body-parser')
const app = require('express')()
app.use(bodyParser.json())
app.all('/getJSON', (req, res) => {
res.json({ data: 'data' })
})
module.exports = app
serverMiddleware: [
{ path: "/server-middleware", handler: "~/server-middleware/rest.js" },
],
オブジェクトの構文
パスにマッピングされた関数のリストでサーバーミドルウェアが構成されている場合:
export default {
serverMiddleware: [
{ path: '/a', handler: '~/server-middleware/a.js' },
{ path: '/b', handler: '~/server-middleware/b.js' },
{ path: '/c', handler: '~/server-middleware/c.js' }
]
}
あるいは、次のとおりオブジェクトを渡して定義することもできます:
export default {
serverMiddleware: {
'/a': '~/server-middleware/a.js',
'/b': '~/server-middleware/b.js',
'/c': '~/server-middleware/c.js'
}
}


















































