Wechsel zu Express 5
Ăberblick
Express 5.0 befindet sich noch in der Beta-Release-Phase. Hier finden Sie jedoch bereits eine Vorschau zu den Ănderungen in diesem Release und zur Migration Ihrer Express 4-Anwendung auf 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"
Sie können Ihre automatisierten Tests ausfĂŒhren, um zu sehen, was fehlschlĂ€gt, und Probleme gemÀà den folgenden Updates beheben. Nachdem Sie alle Testfehler behoben haben, fĂŒhren Sie Ihre Anwendung aus, um zu sehen, welche Fehler noch auftreten. Sie werden sofort feststellen, ob die Anwendung Methoden oder Eigenschaften verwendet, die nicht unterstĂŒtzt werden.
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.
Ănderungen in Express 5
Entfernte Methoden und Eigenschaften
- app.del()
- app.param(fn)
- Pluralisierte Methodennamen
- FĂŒhrender Doppelpunkt im Namensargument fĂŒr app.param(name, fn)
- 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
Verbesserungen
- 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
GeÀndert
Entfernte Methoden und Eigenschaften
Wenn Sie eine dieser Methoden oder Eigenschaften in Ihrer Anwendung verwenden, stĂŒrzt die Anwendung ab. Sie mĂŒssen also Ihre Anwendung Ă€ndern, wenn Sie auf Version 5 umgestellt haben.
app.del()
Express 5 unterstĂŒtzt die Funktion app.del()
nicht mehr. Wenn Sie diese Funktion verwenden, wird ein Fehler ausgelöst. FĂŒr die Registrierung von HTTP DELETE-Weiterleitungen verwenden Sie stattdessen die Funktion app.delete()
.
AnfÀnglich wurde del
statt delete
verwendet, weil delete
in JavaScript ein reserviertes SchlĂŒsselwort ist. Ab ECMAScript 6 jedoch können delete
und andere reservierte SchlĂŒsselwörter legal als Eigenschaftsnamen verwendet werden.
Hinweis
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)
Die Signatur app.param(fn)
wurde fĂŒr die Ănderung der Verhaltensweise der Funktion app.param(name, fn)
verwendet. Seit v4.11.0 wurde sie nicht mehr verwendet. In Express 5 wird sie ĂŒberhaupt nicht mehr unterstĂŒtzt.
Pluralisierte Methodennamen
Die folgenden Methodennamen wurden pluralisiert. In Express 4 wurde bei Verwendung der alten Methoden eine Warnung zur Einstellung der UnterstĂŒtzung ausgegeben. Express 5 unterstĂŒtzt diese Methoden nicht mehr.
req.acceptsLanguage()
wird durch req.acceptsLanguages()
ersetzt.
req.acceptsCharset()
wird durch req.acceptsCharsets()
ersetzt.
req.acceptsEncoding()
wird durch req.acceptsEncodings()
ersetzt.
Hinweis
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')
// ...
})
FĂŒhrender Doppelpunkt (:) im Namen fĂŒr app.param(name, fn)
Ein fĂŒhrendes Doppelpunktzeichen (:) im Namen fĂŒr die Funktion app.param(name, fn)
ist ein Ăberbleibsel aus Express 3. Aus GrĂŒnden der AbwĂ€rtskompatibilitĂ€t wurde dieser Name in Express 4 mit einem Hinweis zu veralteten Versionen weiter unterstĂŒtzt. In Express 5 wird dieser Name stillschwiegend ignoriert und der Namensparameter ohne einen vorangestellten Doppelpunkt verwendet.
Dies dĂŒrfte keine Auswirkungen auf Ihren Code haben, wenn Sie die Express 4-Dokumentation zu app.param befolgen, da dort der fĂŒhrende Doppelpunkt nicht erwĂ€hnt wird.
req.param(name)
Dieses potenziell verwirrende und durchaus riskante Verfahren des Abrufens von Formulardaten wurde entfernt. Sie mĂŒssen nun ganz speziell nach dem ĂŒbergebenen Parameternamen im Objekt req.params
, req.body
oder req.query
suchen.
Hinweis
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 unterstĂŒtzt die Signatur res.json(obj, status)
nicht mehr. Stattdessen mĂŒssen Sie den Status festlegen und diesen dann mit res.json()
-Methoden wie dieser verketten: res.status(status).json(obj)
.
Hinweis
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 unterstĂŒtzt die Signatur res.jsonp(obj, status)
nicht mehr. Stattdessen mĂŒssen Sie den Status festlegen und diesen dann mit res.jsonp()
-Methoden wie dieser verketten: res.status(status).jsonp(obj)
.
Hinweis
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 unterstĂŒtzt die Signatur res.send(obj, status)
nicht mehr. Stattdessen mĂŒssen Sie den Status festlegen und diesen dann mit res.send()
-Methoden wie dieser verketten: res.status(status).send(obj)
.
Hinweis
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.
Hinweis
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 no longer supports the signature res.send(obj, status)
. Instead, set the status and then chain it to the res.send()
method like this: res.status(status).send(obj)
.
Hinweis
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 unterstĂŒtzt die Signatur res.send(status)
, nicht mehr, wobei status
fĂŒr eine Zahl steht. Verwenden Sie stattdessen die Funktion res.sendStatus(statusCode)
, mit der der Statuscode fĂŒr den HTTP-Antwort-Header festgelegt und die Textversion des Codes gesendet wird: âNot Foundâ (Nicht gefunden), âInternal Server Errorâ (Interner Serverfehler) usw.
Wenn Sie eine Zahl senden und hierfĂŒr die Funktion res.send()
verwenden mĂŒssen, mĂŒssen Sie die Zahl in AnfĂŒhrungszeichen setzen, um diese in eine Zeichenfolge zu konvertieren. Dadurch interpretiert Express diese Zahl nicht als Versuch, die nicht mehr unterstĂŒtzte alte Signatur zu verwenden.
Hinweis
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()
Die Funktion res.sendfile()
wurde durch eine Version in Camel-Schreibweise von res.sendFile()
in Express 5 ersetzt.
Note: In Express 5, res.sendFile()
uses the mime-types
package for MIME type detection, which returns different Content-Type values than Express 4 for several common file types:
- JavaScript files (.js): now âtext/javascriptâ instead of âapplication/javascriptâ
- JSON files (.json): now âapplication/jsonâ instead of âtext/jsonâ
- CSS files (.css): now âtext/cssâ instead of âtext/plainâ
- XML files (.xml): now âapplication/xmlâ instead of âtext/xmlâ
- Font files (.woff): now âfont/woffâ instead of âapplication/font-woffâ
- SVG files (.svg): now âimage/svg+xmlâ instead of âapplication/svg+xmlâ
Hinweis
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. Seit v4.11.0 wurde sie nicht mehr verwendet. In Express 5 wird sie ĂŒberhaupt nicht mehr unterstĂŒtzt.
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.
Important: This change affects not only direct usage of express.static.mime
but also other Express methods that rely on MIME type detection, such as res.sendFile()
. The following MIME types have changed from Express 4:
- JavaScript files (.js): now served as âtext/javascriptâ instead of âapplication/javascriptâ
- JSON files (.json): now served as âapplication/jsonâ instead of âtext/jsonâ
- CSS files (.css): now served as âtext/cssâ instead of âtext/plainâ
- HTML files (.html): now served as âtext/html; charset=utf-8â instead of just âtext/htmlâ
- XML files (.xml): now served as âapplication/xmlâ instead of âtext/xmlâ
- Font files (.woff): now served as âfont/woffâ instead of âapplication/font-woffâ
// 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
GeÀndert
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')
})
Hinweis
*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. Beispiel:
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.
Beispiel:
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
Das Objekt app.router
, das in Express 4 entfernt wurde, ist in Express 5 wieder verfĂŒgbar. In der neuen Version fungiert dieses Objekt nur als Referenz zum Express-Basisrouter â im Gegensatz zu Express 3, wo die Anwendung dieses Objekt explizit laden musste.
req.body
The req.body
property returns undefined
when the body has not been parsed. In Express 4, it returns {}
by default.
req.host
In Express 4 ĂŒbergab die Funktion req.host
nicht ordnungsgemÀà eine eventuell vorhandene Portnummer. In Express 5 wird die Portnummer beibehalten.
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
Verbesserungen
res.render()
Diese Methode erzwingt nun asynchrones Verhalten fĂŒr alle View-Engines, sodass durch View-Engines mit synchroner Implementierung verursachte Fehler vermieden werden, durch die die empfohlene Schnittstelle nicht verwendet werden konnte.
Brotli encoding support
Express 5 supports Brotli encoding for requests received from clients that support it.
Edit this page