Express 5 への移行
概説
Express 5 は Express 4 とあまり変わりません。API の変更は、3.0 から 4.0 への変更ほど大きいものではありません。基本的な API は同じままですが、それでも互換性のない変更が行われています。つまり、Express 5 を使用するように既存の Express 4 を更新すると、機能しなくなる可能性があります。 Therefore, an application built with Express 4 might not work if you update it to use Express 5.
To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory:
npm install "express@5"
その後、自動テストを実行して、どの機能が失敗するかを確認し、下記の更新に従って問題を修正することができます。テストの失敗に対応した後、アプリケーションを実行して、どのようなエラーが発生するかを確認します。サポートされていないメソッドまたはプロパティーをアプリケーションが使用している場合は、すぐに判明します。 After addressing test failures, run your app to see what errors occur. You’ll find out right away if the app uses any methods or properties that are not supported.
Express 5 Codemods
To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express.
Run the following command for run all the codemods available:
npx @expressjs/codemod upgrade
If you want to run a specific codemod, you can run the following command:
npx @expressjs/codemod name-of-the-codemod
You can find the list of available codemods here.
Express 5 における変更点
削除されたメソッドとプロパティー
- app.del()
- app.param(fn)
- メソッド名の複数化
- app.param(name, fn) の name 引数の先頭コロン
- req.param(name)
- res.json(obj, status)
- res.jsonp(obj, status)
- res.redirect('back') and res.location('back')
- res.redirect(url, status)
- res.send(body, status)
- res.send(status)
- res.sendfile()
- router.param(fn)
- express.static.mime
- express:router debug logs
改善
- Path route matching syntax
- Rejected promises handled from middleware and handlers
- express.urlencoded
- app.listen
- app.router
- req.body
- req.host
- req.query
- res.clearCookie
- res.status
- res.vary
変更
削除されたメソッドとプロパティー
If you use any of these methods or properties in your app, it will crash. アプリケーションで以下のいずれかのメソッドまたはプロパティーを使用すると、異常終了します。そのため、バージョン 5 に更新した後で、アプリケーションを変更する必要があります。
app.del()
Express 5 は、app.del()
関数をサポートしなくなりました。この関数を使用すると、エラーがスローされます。HTTP DELETE ルートを登録するには、代わりに app.delete()
関数を使用してください。 If you use this function, an error is thrown. For registering HTTP DELETE routes, use the app.delete()
function instead.
最初は del
が delete
の代わりに使用されていました。delete
は、JavaScript で予約されているキーワードであるためです。しかし、ECMAScript 6 以降では、delete
およびその他の予約済みキーワードを正式にプロパティー名として使用できます。ここで、app.del
関数の非推奨につながった議論を読むことができます。 However, as of ECMAScript 6, delete
and other reserved keywords can legally be used as property names.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.del('/user/:id', (req, res) => {
res.send(`DELETE /user/${req.params.id}`)
})
// v5
app.delete('/user/:id', (req, res) => {
res.send(`DELETE /user/${req.params.id}`)
})
app.param(fn)
app.param(fn)
シグニチャーは、app.param(name, fn)
関数の動作を変更するために使用されていました。v4.11.0 以降では非推奨になったため、Express 5 は完全にサポートしなくなりました。 It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
メソッド名の複数化
The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all:
req.acceptsLanguage()
は req.acceptsLanguages()
に置き換えられます。
req.acceptsCharset()
は req.acceptsCharsets()
に置き換えられます。
req.acceptsEncoding()
は req.acceptsEncodings()
に置き換えられます。
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod pluralized-methods
// v4
app.all('/', (req, res) => {
req.acceptsCharset('utf-8')
req.acceptsEncoding('br')
req.acceptsLanguage('en')
// ...
})
// v5
app.all('/', (req, res) => {
req.acceptsCharsets('utf-8')
req.acceptsEncodings('br')
req.acceptsLanguages('en')
// ...
})
app.param(name, fn) の name の先頭コロン (:)
app.param(name, fn)
関数の name の先頭コロン文字 (:) は、Express 3 の残余物であり、Express 4 では後方互換性のためにサポートされていましたが、非推奨の通知が出されてました。Express 5 では、サイレントに無視して、先頭にコロンを付けない name パラメーターを使用します。 Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
app.param に関する Express 4 の資料では、先頭のコロンについて言及していないため、この資料に従う場合には、コードに影響は及ばないはずです。
req.param(name)
This potentially confusing and dangerous method of retrieving form data has been removed. この混乱を招く可能性がある危険なメソッドは、フォーム・データを取得するためのものでしたが、削除されました。今後は、実行依頼されたパラメーター名を req.params
、req.body
、または req.query
オブジェクトで具体的に見つける必要があります。
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod req-param
// v4
app.post('/user', (req, res) => {
const id = req.param('id')
const body = req.param('body')
const query = req.param('query')
// ...
})
// v5
app.post('/user', (req, res) => {
const id = req.params.id
const body = req.body
const query = req.query
// ...
})
res.json(obj, status)
Express 5 は、シグニチャー res.json(obj, status)
をサポートしなくなりました。代わりに、状況を設定してから、res.status(status).json(obj)
のように res.json()
メソッドにチェーニングします。 Instead, set the status and then chain it to the res.json()
method like this: res.status(status).json(obj)
.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.post('/user', (req, res) => {
res.json({ name: 'Ruben' }, 201)
})
// v5
app.post('/user', (req, res) => {
res.status(201).json({ name: 'Ruben' })
})
res.jsonp(obj, status)
Express 5 は、シグニチャー res.jsonp(obj, status)
をサポートしなくなりました。代わりに、状況を設定してから、res.status(status).jsonp(obj)
のように res.jsonp()
メソッドにチェーニングします。 Instead, set the status and then chain it to the res.jsonp()
method like this: res.status(status).jsonp(obj)
.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.post('/user', (req, res) => {
res.jsonp({ name: 'Ruben' }, 201)
})
// v5
app.post('/user', (req, res) => {
res.status(201).jsonp({ name: 'Ruben' })
})
res.redirect(url, status)
Express 5 no longer supports the signature res.redirect(url, status)
. Instead, use the following signature: res.redirect(status, url)
.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.get('/user', (req, res) => {
res.redirect('/users', 301)
})
// v5
app.get('/user', (req, res) => {
res.redirect(301, '/users')
})
res.redirect('back') and res.location('back')
Express 5 no longer supports the magic string back
in the res.redirect()
and res.location()
methods. Instead, use the req.get('Referrer') || '/'
value to redirect back to the previous page. In Express 4, the res.redirect('back')
and res.location('back')
methods were deprecated.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod magic-redirect
// v4
app.get('/user', (req, res) => {
res.redirect('back')
})
// v5
app.get('/user', (req, res) => {
res.redirect(req.get('Referrer') || '/')
})
res.send(body, status)
Express 5 は、シグニチャー res.send(obj, status)
をサポートしなくなりました。代わりに、状況を設定してから、res.status(status).send(obj)
のように res.send()
メソッドにチェーニングします。 Instead, set the status and then chain it to the res.send()
method like this: res.status(status).send(obj)
.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.get('/user', (req, res) => {
res.send({ name: 'Ruben' }, 200)
})
// v5
app.get('/user', (req, res) => {
res.status(200).send({ name: 'Ruben' })
})
res.send(status)
Express 5 no longer supports the signature res.send(status)
, where status
is a number. Instead, use the res.sendStatus(statusCode)
function, which sets the HTTP response header status code and sends the text version of the code: “Not Found”, “Internal Server Error”, and so on.
If you need to send a number by using the res.send()
function, quote the number to convert it to a string, so that Express does not interpret it as an attempt to use the unsupported old signature.
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.get('/user', (req, res) => {
res.send(200)
})
// v5
app.get('/user', (req, res) => {
res.sendStatus(200)
})
res.sendfile()
res.sendfile()
関数は、Express 5 ではキャメルケース版の res.sendFile()
に置き換えられます。
Note
You can replace the deprecated signatures with the following command:
npx @expressjs/codemod v4-deprecated-signatures
// v4
app.get('/user', (req, res) => {
res.sendfile('/path/to/file')
})
// v5
app.get('/user', (req, res) => {
res.sendFile('/path/to/file')
})
router.param(fn)
The router.param(fn)
signature was used for modifying the behavior of the router.param(name, fn)
function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
express.static.mime
In Express 5, mime
is no longer an exported property of the static
field.
Use the mime-types
package to work with MIME type values.
// v4
express.static.mime.lookup('json')
// v5
const mime = require('mime-types')
mime.lookup('json')
express:router debug logs
In Express 5, router handling logic is performed by a dependency. Therefore, the
debug logs for the router are no longer available under the express:
namespace.
In v4, the logs were available under the namespaces express:router
, express:router:layer
,
and express:router:route
. All of these were included under the namespace express:*
.
In v5.1+, the logs are available under the namespaces router
, router:layer
, and router:route
.
The logs from router:layer
and router:route
are included in the namespace router:*
.
To achieve the same detail of debug logging when using express:*
in v4, use a conjunction of
express:*
, router
, and router:*
.
# v4
DEBUG=express:* node index.js
# v5
DEBUG=express:*,router,router:* node index.js
変更
Path route matching syntax
Path route matching syntax is when a string is supplied as the first parameter to the app.all()
, app.use()
, app.METHOD()
, router.all()
, router.METHOD()
, and router.use()
APIs. The following changes have been made to how the path string is matched to an incoming request:
- The wildcard
*
must have a name, matching the behavior of parameters:
, use/*splat
instead of/*
// v4
app.get('/*', async (req, res) => {
res.send('ok')
})
// v5
app.get('/*splat', async (req, res) => {
res.send('ok')
})
Note
*splat
matches any path without the root path. If you need to match the root path as well /
, you can use /{*splat}
, wrapping the wildcard in braces.
// v5
app.get('/{*splat}', async (req, res) => {
res.send('ok')
})
- The optional character
?
is no longer supported, use braces instead.
// v4
app.get('/:file.:ext?', async (req, res) => {
res.send('ok')
})
// v5
app.get('/:file{.:ext}', async (req, res) => {
res.send('ok')
})
- Regexp characters are not supported. For example:
app.get('/[discussion|page]/:slug', async (req, res) => {
res.status(200).send('ok')
})
should be changed to:
app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => {
res.status(200).send('ok')
})
- Some characters have been reserved to avoid confusion during upgrade (
()[]?+!
), use\
to escape them. - Parameter names now support valid JavaScript identifiers, or quoted like
:"this"
.
Rejected promises handled from middleware and handlers
Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an Error
to the error handling middleware. This means that using async
functions as middleware and handlers are easier than ever. When an error is thrown in an async
function or a rejected promise is await
ed inside an async function, those errors will be passed to the error handler as if calling next(err)
.
Details of how Express handles errors is covered in the error handling documentation.
express.urlencoded
The express.urlencoded
method makes the extended
option false
by default.
app.listen
In Express 5, the app.listen
method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument.
For example:
const server = app.listen(8080, '0.0.0.0', (error) => {
if (error) {
throw error // e.g. EADDRINUSE
}
console.log(`Listening on ${JSON.stringify(server.address())}`)
})
app.router
app.router
オブジェクトは、Express 4 で削除されましたが、Express 5 で復帰しました。アプリケーションが明示的にロードする必要があった Express 3 とは異なり、新しいバージョンでは、このオブジェクトは基本の Express ルーターの単なる参照です。 In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
req.body
The req.body
property returns undefined
when the body has not been parsed. In Express 4, it returns {}
by default.
req.host
Express 4 では、req.host
関数は、ポート番号が存在する場合に、ポート番号を誤って削除していました。Express 5 では、ポート番号は維持されます。 In Express 5, the port number is maintained.
req.query
The req.query
property is no longer a writable property and is instead a getter. The default query parser has been changed from “extended” to “simple”.
res.clearCookie
The res.clearCookie
method ignores the maxAge
and expires
options provided by the user.
res.status
The res.status
method only accepts integers in the range of 100
to 999
, following the behavior defined by Node.js, and it returns an error when the status code is not an integer.
res.vary
The res.vary
throws an error when the field
argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console
改善
res.render()
このメソッドは、すべてのビュー・エンジンに非同期動作を適用するようになり、同期実装を使用して推奨インターフェースに違反していたビュー・エンジンに起因するバグを回避します。
Brotli encoding support
Express 5 supports Brotli encoding for requests received from clients that support it.
Edit this page