@@ -25,7 +25,7 @@ import Alert from '@components/primitives/Alert/Alert.astro';
`true` の場合、クライアントの IP アドレスは `X-Forwarded-For` ヘッダーの中の一番左のエントリとして理解されます。
-`false` の場合、アプリはクライアントに直接向いていると理解され、クライアントの IP アドレスは `req.socket.remoteAddress` に由来します。 これはデフォルトの設定です。
+`false` の場合、アプリはクライアントに直接向いていると理解され、クライアントの IP アドレスは `req.socket.remoteAddress` に由来します。 これはデフォルトの設定です。 これはデフォルトの設定です。
`true` に設定する場合、信頼されている最後のリバースプロキシが以下のすべての HTTP ヘッダを削除/上書きすることが重要です: `X-Forwarded-For` 。 `X-Forwarded-Host` と `X-Forwarded-Proto` があれば、クライアントが何らかの値を提供できるかもしれません。
@@ -35,7 +35,7 @@ import Alert from '@components/primitives/Alert/Alert.astro';
| IPアドレス |
-リバースプロキシとして信頼する IP アドレス、サブネット、または IP アドレスとサブネットの配列。 次のリストに、事前に設定されたサブネット名が表示されます。
+リバースプロキシとして信頼する IP アドレス、サブネット、または IP アドレスとサブネットの配列。 次のリストに、事前に設定されたサブネット名が表示されます。 次のリストに、事前に設定されたサブネット名が表示されます。
- loopback - `127.0.0.1/8`, `::1/128`
- linklocal - `169.254.0.0/16`, `fe80::/10`
@@ -57,7 +57,7 @@ app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); // specify mul
|
| 数字 |
-Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 `0`の値は、最初に信頼されていないアドレスが`req.socket.remoteAddress`であることを意味します。つまり、リバースプロキシは存在しません。
+Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 `0`の値は、最初に信頼されていないアドレスが`req.socket.remoteAddress`であることを意味します。つまり、リバースプロキシは存在しません。
この設定を使用する場合は、複数がないことを確認することが重要です。 Expressアプリケーションへの異なる長さのパスは、クライアントが設定されたホップ数よりも少なくすることができるようになります。 それ以外の場合は、クライアントが何らかの価値を提供することができます。
@@ -86,13 +86,13 @@ app.set('trust proxy', (ip) => {
-
- [req.hostname](/api#req.hostname) の値は、 `X-Forwarded-Host`
- ヘッダで設定された値から取得されます。 クライアントやプロキシによって設定できます
+ The value of [req.hostname](/api/request/#reqhostname) is derived from the value set in the
+ `X-Forwarded-Host` header, which can be set by the client or by the proxy.
-
`X-Forwarded-Proto` はリバースプロキシによって設定することで、アプリが https`か`http\`
- か無効な名前かをアプリに伝えることができます。 この値は [req.protocol](/api#req.protocol)
- で反映されます。
+ か無効な名前かをアプリに伝えることができます。 This value is reflected by
+ [req.protocol](/api/request/#reqprotocol).
-
[req.ip](/api#req.ip) と [req.ips](/api#req.ips) の値は、 ソケットアドレスと `X-Forwarded-For`
@@ -100,4 +100,4 @@ app.set('trust proxy', (ip) => {
-`trust proxy` は、 [proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されています。 詳細については、そのドキュメントを参照してください。
+`trust proxy` は、 [proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されています。 詳細については、そのドキュメントを参照してください。 詳細については、そのドキュメントを参照してください。
diff --git a/src/content/docs/ja/4x/guide/debugging.mdx b/src/content/docs/ja/4x/guide/debugging.mdx
index 0d007eaafe..158b013dd9 100644
--- a/src/content/docs/ja/4x/guide/debugging.mdx
+++ b/src/content/docs/ja/4x/guide/debugging.mdx
@@ -84,7 +84,7 @@ $ DEBUG=express:* node ./bin/www
express:view render "/projects/example/views/index.pug" +1ms
```
-ルータの実装からのみログを見るには、`DEBUG`の値を`express:router`に設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。
+ルータの実装からのみログを見るには、`DEBUG`の値を`express:router`に設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。
## `express` で生成されたアプリケーション
@@ -117,8 +117,7 @@ Node.js を介して実行する場合、デバッグログの動作を変更す
The environment variables beginning with `DEBUG_` end up being converted into an Options object
-that gets used with `%o`/`%O` formatters.
-[`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) の完全な
+that gets used with `%o`/`%O` formatters. [`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) の完全な
リストについては Node.js のドキュメントを参照してください。
diff --git a/src/content/docs/ja/4x/guide/error-handling.mdx b/src/content/docs/ja/4x/guide/error-handling.mdx
index ad7c54ba34..4a8bc65690 100644
--- a/src/content/docs/ja/4x/guide/error-handling.mdx
+++ b/src/content/docs/ja/4x/guide/error-handling.mdx
@@ -6,6 +6,7 @@ description: Express.jsが同期コードと非同期コードのエラーを処
import Alert from '@components/primitives/Alert/Alert.astro';
*Error Handling*は、
+が同期と非同期の両方で発生するエラーをExpress がキャッチして処理する方法を指します。 _Error Handling_は、
が同期と非同期の両方で発生するエラーをExpress がキャッチして処理する方法を指します。 Expressにはデフォルトのエラー
ハンドラが付属しているので、始めるために自分で書く必要はありません。
@@ -16,6 +17,7 @@ Express がルートハンドラと
ルートハンドラとミドルウェア
内の同期コードで発生するエラーは追加の作業を必要としません。 同期コードがエラーをスローする場合、Expressは
+キャッチして処理します。 例: 同期コードがエラーをスローする場合、Expressは
キャッチして処理します。 例:
```js
@@ -40,8 +42,9 @@ app.get('/', (req, res, next) => {
});
```
-Express 5以降、Promise
-を返すルートハンドラとミドルウェアは、エラーの拒否またはスロー時に自動的に`next(value)`を呼び出します。
+Define error-handling middleware functions in the same way as other middleware functions,
+except error-handling functions have four arguments instead of three:
+`(err, req, res, next)`.
例:
```js
@@ -78,7 +81,7 @@ which is called with or without errors. エラーがなければ、2番目の
ハンドラが実行されます。そうでなければ、Expressはエラーをキャッチして処理します。
route handler または
-ミドルウェアによって呼び出された非同期コードで発生するエラーをキャッチし、処理のために Express に渡す必要があります。 例:
+ミドルウェアによって呼び出された非同期コードで発生するエラーをキャッチし、処理のために Express に渡す必要があります。 例: 例:
```js
app.get('/', (req, res, next) => {
@@ -93,12 +96,13 @@ app.get('/', (req, res, next) => {
```
上の例では、
+非同期コードのエラーをキャッチし、Expressに渡すために`try...catch`ブロックを使用しています。 上の例では、
非同期コードのエラーをキャッチし、Expressに渡すために`try...catch`ブロックを使用しています。 `try...catch`
ブロックが省略された場合、Expressは同期
ハンドラコードの一部ではないため、エラーをキャッチしません。
プロミスを返す関数
-を使うと、`try...catch` のオーバーヘッドを避けることができます。 例:
+を使うと、`try...catch` のオーバーヘッドを避けることができます。 例: 例:
```js
app.get('/', (req, res, next) => {
@@ -115,7 +119,7 @@ you can simply provide `next` as the final catch handler and Express will catch
because the catch handler is given the error as the first argument.
また、非同期コードを些細なものに減らすことで、同期エラー
-のキャッチに依存するハンドラのチェーンを使用することもできます。 例:
+のキャッチに依存するハンドラのチェーンを使用することもできます。 例: 例:
```js
app.get('/', [
@@ -133,11 +137,15 @@ app.get('/', [
```
上の例では、`readFile`
+呼び出しからいくつかの些細な文があります。 上の例では、`readFile`
呼び出しからいくつかの些細な文があります。 `readFile` でエラーが発生した場合、エラーは Express に渡されます。 それ以外の場合は、
チェーン内の次のハンドラ
で同期エラー処理の世界にすばやく戻ります。 そして、上記の例はデータを処理しようとします。 これが失敗した場合、
同期エラーハンドラはそれをキャッチします。 `readFile`コールバックの
内でこの処理を行った場合、アプリケーションが終了する可能性があり、Expressエラー
+ハンドラは実行されません。 そして、上記の例はデータを処理しようとします。 これが失敗した場合、
+同期エラーハンドラはそれをキャッチします。 `readFile`コールバックの
+内でこの処理を行った場合、アプリケーションが終了する可能性があり、Expressエラー
ハンドラは実行されません。
どちらの方法を使っても、Expressエラーハンドラを呼び出し、
@@ -145,7 +153,7 @@ app.get('/', [
## デフォルトのエラーハンドラです
-Expressには、アプリで発生する可能性のあるエラーを処理する内蔵のエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。
+Expressには、アプリで発生する可能性のあるエラーを処理する内蔵のエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。
If you pass an error to `next()` and you do not handle it in a custom error
handler, it will be handled by the built-in error handler; the error will be
@@ -207,7 +215,7 @@ app.use((err, req, res, next) => {
エラー処理ミドルウェアは、他の `app.use()`とルート呼び出しの後に最後に定義します。例:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +231,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
ミドルウェア関数内からのレスポンスは、HTMLエラーページ、シンプルなメッセージ、JSON文字列など、あらゆる形式で使用できます。
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +254,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. 例えば、`XHR`とそれ以外のリクエストに対してエラーハンドラ
を定義するには、次のようにします。
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +270,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
この例では、一般的な`logErrors`はリクエストと
エラー情報を`stderr`に書き込むことができます。
@@ -258,7 +298,7 @@ function logErrors(err, req, res, next) {
この例でも、`clientErrorHandler`は以下のように定義されています。この場合、エラーは明示的に次のエラーに渡されます。
-エラー処理関数で「next」を呼び出さない場合、レスポンスの書き込み(および終了)を行う責任があることに注意してください。 そうでなければ、これらのリクエストは「ハング」し、ガベージコレクションの対象になりません。
+Notice that when _not_ calling "next" in an error-handling function, you are responsible for writing (and ending) the response. Otherwise, those requests will "hang" and will not be eligible for garbage collection.
```js
function clientErrorHandler(err, req, res, next) {
@@ -279,7 +319,7 @@ function errorHandler(err, req, res, next) {
}
```
-複数のコールバック関数を持つルートハンドラがある場合は、`route` パラメータを使用して次のルートハンドラにスキップできます。 例:
+複数のコールバック関数を持つルートハンドラがある場合は、`route` パラメータを使用して次のルートハンドラにスキップできます。 例: 例:
```js
app.get(
@@ -308,5 +348,7 @@ app.get(
`next()`と`next(err)`への呼び出しは、現在のハンドラが完了している状態を示します。
`next(err)`は、上記のように
に設定されているものを除いて、チェーン内の残りのハンドラをすべてスキップします。
+`next(err)` will skip all remaining handlers in the chain except for those that are set up to
+handle errors as described above.
diff --git a/src/content/docs/ja/4x/guide/overriding-express-api.md b/src/content/docs/ja/4x/guide/overriding-express-api.md
index 6406244645..683b56ee93 100644
--- a/src/content/docs/ja/4x/guide/overriding-express-api.md
+++ b/src/content/docs/ja/4x/guide/overriding-express-api.md
@@ -3,18 +3,18 @@ title: Express API のオーバーライド
description: リクエストとレスポンスオブジェクトのメソッドとプロパティをプロトタイプを使用してオーバーライドすることで、Express.js API をカスタマイズして拡張する方法をご覧ください。
---
-Express API は、リクエストオブジェクトとレスポンスオブジェクトのさまざまなメソッドとプロパティで構成されています。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。
+Express API は、リクエストオブジェクトとレスポンスオブジェクトのさまざまなメソッドとプロパティで構成されています。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。
1. `express.request` と `express.response` のグローバルプロトタイプ。
2. `app.request`と`app.response`でアプリ固有のプロトタイプ。
-グローバルプロトタイプを変更すると、読み込まれたすべてのExpressアプリが同じプロセスで影響を受けます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。
+グローバルプロトタイプを変更すると、読み込まれたすべてのExpressアプリが同じプロセスで影響を受けます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。
## メソッド
カスタム関数を割り当てることで、既存のメソッドの署名と振る舞いを独自のメソッドで上書きできます。
-以下は、 [res.sendStatus](/api#res.sendStatus) の挙動を上書きした例です。
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
@@ -23,7 +23,7 @@ app.response.sendStatus = function (statusCode, type, message) {
};
```
-上記の実装は `res.sendStatus` の元の署名を完全に変更します。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。
+上記の実装は `res.sendStatus` の元の署名を完全に変更します。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。
オーバーライドされたメソッドは次のように使用できます。
@@ -42,7 +42,7 @@ category 1 のプロパティは、現在のリクエスト-レスポンスサ
カテゴリ2のプロパティはExpress API拡張機能APIを使用して上書きすることができます。
-次のコードは `req.ip` の値をどのように派生するかを書き換えます。 これで、`Client-IP` リクエストヘッダの値を返すだけです。
+次のコードは `req.ip` の値をどのように派生するかを書き換えます。 次のコードは `req.ip` の値をどのように派生するかを書き換えます。 これで、`Client-IP` リクエストヘッダの値を返すだけです。
```js
Object.defineProperty(app.request, 'ip', {
@@ -56,7 +56,7 @@ Object.defineProperty(app.request, 'ip', {
## プロトタイプ
-Express API を提供するためには、Express に渡された request/response オブジェクトを (`app(req) 経由で) 提供します。 res)`は同じプロトタイプチェーンから継承する必要があります。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。
+Express API を提供するためには、Express に渡された request/response オブジェクトを (`app(req) 経由で) 提供します。 res)`は同じプロトタイプチェーンから継承する必要があります。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。
必要がない限り、これはアプリケーションレベルでのみ行うことを推奨します。 また、使用されているプロトタイプは、可能な限りデフォルトのプロトタイプに近い機能を備えていることに注意してください。
diff --git a/src/content/docs/ja/4x/guide/routing.mdx b/src/content/docs/ja/4x/guide/routing.mdx
index b85163b4d1..b11ce83f90 100644
--- a/src/content/docs/ja/4x/guide/routing.mdx
+++ b/src/content/docs/ja/4x/guide/routing.mdx
@@ -7,21 +7,24 @@ import Alert from '@components/primitives/Alert/Alert.astro';
_Routing_ とは、アプリケーションのエンドポイント(URI)がクライアントリクエストに対してどのように応答するかを指します。
For an introduction to routing, see [Basic routing](/starter/basic-routing).
+For an introduction to routing, see [Basic routing](/starter/basic-routing).
HTTPメソッドに対応するExpress `app` オブジェクトのメソッドを使用してルーティングを定義します。
-のように、`app。 POST リクエストを処理する GET リクエストと `app.post\` を処理します。 完全なリストについては、
-[app.METHOD](/api/application#appmethodpath-callback--callback-) を参照してください。 [app.all()](/api/application#appallpath-callback--callback-)を使用して、すべてのHTTPメソッドと[app]を処理することもできます。 se()](/api/application#appusepath-callback--callback) to
-コールバック関数としてミドルウェアを指定する (詳細は [Using middleware](/guide/using-middleware) を参照)。
+のように、`app。 POST リクエストを処理する GET リクエストと `app.post\` を処理します。 For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
+specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-これらのルーティングメソッドは、アプリケーションが指定されたルート (エンドポイント) と HTTP メソッドへのリクエストを受け取ったときに呼び出されるコールバック関数 ("handler functions" と呼ばれることもあります) を指定します。 言い換えれば、アプリケーションは指定されたルートとメソッドに一致するリクエストを「リッスン」します。 マッチを検出すると、指定されたコールバック関数を呼び出します。
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. 言い換えれば、アプリケーションは指定されたルートとメソッドに一致するリクエストを「リッスン」します。 マッチを検出すると、指定されたコールバック関数を呼び出します。
実際、ルーティングメソッドは引数として複数のコールバック関数を持つことができます。
複数のコールバック関数を使用。 コールバック関数に `next` を引数として渡し、関数の本体内で `next()` を呼び出して、次のコールバックに
を渡すことが重要です。
+複数のコールバック関数を使用。 コールバック関数に `next` を引数として渡し、関数の本体内で `next()` を呼び出して、次のコールバックに
+を渡すことが重要です。
以下のコードは、非常に基本的なルートの例です。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +34,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## ルートメソッド
routeメソッドはHTTPメソッドのいずれかから派生し、`express` クラスのインスタンスに追加されます。
@@ -51,8 +65,9 @@ app.post('/', (req, res) => {
Expressは、すべてのHTTPリクエストメソッドに対応するメソッドをサポートしています: `get`、`post`など。
完全なリストについては、 [app.METHOD](/api/application#appmethodpath-callback--callback-) を参照してください。
+For a full list, see [app.METHOD](/api/application#appmethod).
-特別なルーティングメソッド`app.all()`があり、\_all_HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用されます。 例えば、`GET`を使用しているかどうかに関わらず、ルート`"/secret"へのリクエストに対して以下のハンドラが実行されます。 `POST`、`PUT`、`DELETE\`、または[http module](https://nodejs.org/api/http.html#http_http_methods)でサポートされている他のHTTPリクエストメソッド。
+特別なルーティングメソッド`app.all()`があり、\_all_HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用されます。 例えば、`GET`を使用しているかどうかに関わらず、ルート`"/secret"へのリクエストに対して以下のハンドラが実行されます。 `POST`、`PUT`、`DELETE\`、または[http module](https://nodejs.org/api/http.html#http_http_methods)でサポートされている他のHTTPリクエストメソッド。 For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
```js
app.all('/secret', (req, res, next) => {
@@ -63,12 +78,13 @@ app.all('/secret', (req, res, next) => {
## ルートパス
-ルートパスはリクエストメソッドと組み合わせて、リクエストを作成できるエンドポイントを定義します。 ルートパスは文字列、文字列パターン、または正規表現であることができます。
+ルートパスはリクエストメソッドと組み合わせて、リクエストを作成できるエンドポイントを定義します。 ルートパスは文字列または正規表現にすることができます。 Route paths can be strings, string patterns, or regular expressions.
Express はルートパスに一致する [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) を使用します。ルートパスの定義におけるすべての可能性については、path-to-regexp ドキュメントを参照してください。
[Express Playground Router](https://bjohansebas.github.io/playground-router/)は、パターンマッチングをサポートしていませんが、基本的なExpressルートをテストするための便利なツールです。
+[Express Playground Router](https://bjohansebas.github.io/playground-router/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
@@ -160,7 +176,7 @@ app.get(/.*fly$/, (req, res) => {
## ルートパラメータ
-ルートパラメータは、URL 内の位置で指定された値をキャプチャするために使用される名前付きの URL セグメントです。 取得した値は `req.params` オブジェクト内に入力され、パス内でそれぞれのキーとして指定されたrouteパラメータの名前が入力されます。
+Route parameters are named URL segments that are used to capture the values specified at their position in the URL. ルートパラメータは、URL 内の位置で指定された値をキャプチャするために使用される名前付きの URL セグメントです。 取得した値は `req.params` オブジェクト内に入力され、パス内でそれぞれのキーとして指定されたrouteパラメータの名前が入力されます。
```
Route path: /users/:userId/books/:bookId
@@ -212,12 +228,12 @@ req.params: {"userId": "42"}
-The `*` character in regular expressions is not interpreted in the usual way. 回避策として、`*` の代わりに `{0,}` を使用します。
+The [`*`](https://github.com/expressjs/express/issues/2495) character in regular expressions is not interpreted in the usual way. 回避策として、`*` の代わりに `{0,}` を使用します。
## Route handlers
-リクエストを処理するために、 [middleware](/guide/using-middleware) のように動作する複数のコールバック関数を提供できます。 唯一の例外は、これらのコールバックが `next('route')` を呼び出して、残りのルートコールバックをバイパスすることです。 このメカニズムを使用して、ルート上に事前条件を設定できます。 次に現在のルートを進める理由がなければ次のルートに制御を渡す。
+リクエストを処理するために、 [middleware](/guide/using-middleware) のように動作する複数のコールバック関数を提供できます。 唯一の例外は、これらのコールバックが `next('route')` を呼び出して、残りのルートコールバックをバイパスすることです。 このメカニズムを使用して、ルート上に事前条件を設定できます。 次に現在のルートを進める理由がなければ次のルートに制御を渡す。 The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
```js
app.get('/user/:id', (req, res, next) => {
@@ -239,7 +255,7 @@ app.get('/user/:id', (req, res) => {
ルートハンドラは、次の例に示すように、関数、関数の配列、または両方の組み合わせの形式で使用できます。
-単一のコールバック関数はルートを処理できます。 例:
+単一のコールバック関数はルートを処理できます。 例: 例:
```js
app.get('/example/a', (req, res) => {
@@ -247,7 +263,7 @@ app.get('/example/a', (req, res) => {
});
```
-複数のコールバック関数がルートを処理できます (`next` オブジェクトを指定してください)。 例:
+複数のコールバック関数がルートを処理できます (`next` オブジェクトを指定してください)。 例: 例:
```js
app.get(
@@ -262,7 +278,7 @@ app.get(
);
```
-コールバック関数の配列はルートを処理できます。 例:
+コールバック関数の配列はルートを処理できます。 例: 例:
```js
const cb0 = function (req, res, next) {
@@ -282,7 +298,7 @@ const cb2 = function (req, res) {
app.get('/example/c', [cb0, cb1, cb2]);
```
-独立した関数と関数の配列の組み合わせは、ルートを処理することができます。 例:
+独立した関数と関数の配列の組み合わせは、ルートを処理することができます。 例: 例:
```js
const cb0 = function (req, res, next) {
@@ -310,24 +326,25 @@ app.get(
## レスポンスメソッド
-次の表のレスポンスオブジェクト (`res`) のメソッドは、クライアントにレスポンスを送信し、リクエスト応答のサイクルを終了することができます。 これらのメソッドのいずれもルートハンドラから呼び出されない場合、クライアントリクエストはハングしたままになります。
+次の表のレスポンスオブジェクト (`res`) のメソッドは、クライアントにレスポンスを送信し、リクエスト応答のサイクルを終了することができます。 これらのメソッドのいずれもルートハンドラから呼び出されない場合、クライアントリクエストはハングしたままになります。 If none of these methods are called from a route handler, the client request will be left hanging.
-| 方法 | 説明 |
-| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | ダウンロードするファイルを指示します。 |
-| [res.end()](/api/response#resenddata-encoding-callback) | 応答プロセスを終了します。 |
-| [res.json()](/api/response#resjsonbody) | JSON 応答を送信します。 |
-| [res.jsonp()](/api/response#resjsonpbody) | JSONP サポートを使用して JSON 応答を送信します。 |
-| [res.redirect()](/api/response#resredirectstatus-path) | リダイレクトします。 |
-| [res.render()](/api/response#resrenderview--locals--callback) | ビューテンプレートをレンダリングします。 |
-| [res.send()](/api/response#ressendbody) | さまざまなタイプの応答を送信します。 |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | ファイルをオクテットストリームとして送信する。 |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | レスポンスステータスコードを設定し、文字列表現をレスポンスボディとして送信します。 |
+| 方法 | 説明 |
+| ----------------------------------------------- | ---------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | ダウンロードするファイルを指示します。 |
+| [res.end()](/api/response#resend) | 応答プロセスを終了します。 |
+| [res.json()](/api/response#resjson) | JSON 応答を送信します。 |
+| [res.jsonp()](/api/response#resjsonp) | JSONP サポートを使用して JSON 応答を送信します。 |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | ビューテンプレートをレンダリングします。 |
+| [res.send()](/api/response#ressend) | さまざまなタイプの応答を送信します。 |
+| [res.sendFile()](/api/response#ressendfile) | ファイルをオクテットストリームとして送信する。 |
+| [res.sendStatus()](/api/response#ressendstatus) | レスポンスステータスコードを設定し、文字列表現をレスポンスボディとして送信します。 |
## app.route()
`app.route()` を使用すると、ルートパスに対してチェーン可能なルートハンドラを作成できます。
パスは単一の場所で指定されているため、モジュラールートを作成することは、冗長性とタイプミスを削減するのに役立ちます。 ルートの詳細については、以下を参照してください: [Router() documentation](/api/router)。
+Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](/api/router).
以下は、`app.route()`を使用して定義されたルートハンドラの例です。
@@ -347,13 +364,13 @@ app
## express.Router
-`express.Router` クラスを使用して、モジュール化されたマウント可能なルートハンドラを作成します。 `Router`インスタンスは完全なミドルウェアとルーティングシステムです。そのため、しばしば「ミニアプリ」と呼ばれます。
+Use the `express.Router` class to create modular, mountable route handlers. `express.Router` クラスを使用して、モジュール化されたマウント可能なルートハンドラを作成します。 `Router`インスタンスは完全なミドルウェアとルーティングシステムです。そのため、しばしば「ミニアプリ」と呼ばれます。
次の例では、ルータをモジュールとして作成し、ミドルウェア関数をロードします。 いくつかのルートを定義し、メインアプリのパスにルータモジュールをマウントします。
appディレクトリに`birds.js`という名前のルーターファイルを作成します。以下の内容を使用します。
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -376,9 +393,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
次に、アプリにルーターモジュールをロードします。
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -386,9 +427,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
アプリは `/birds` と `/birds/about` へのリクエストを処理できるようになりました。 同様に、ルート固有の「timeLog」ミドルウェア関数を呼び出します。
-ただし、親ルート `/birds` にパスパラメータがある場合、サブルートからデフォルトではアクセスできません。 アクセス可能にするには、 `mergeParams` オプションを Router コンストラクタ [reference](/api/application#appusepath-callback--callback) に渡す必要があります。
+ただし、親ルート `/birds` にパスパラメータがある場合、サブルートからデフォルトではアクセスできません。 アクセス可能にするには、 `mergeParams` オプションを Router コンストラクタ [reference](/api/application#appusepath-callback--callback) に渡す必要があります。 To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/ja/4x/guide/using-middleware.mdx b/src/content/docs/ja/4x/guide/using-middleware.mdx
index c8b84c154f..dbaadc2e90 100644
--- a/src/content/docs/ja/4x/guide/using-middleware.mdx
+++ b/src/content/docs/ja/4x/guide/using-middleware.mdx
@@ -4,10 +4,11 @@ description: Express.jsアプリケーションでミドルウェアを使用す
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express はルーティングおよびミドルウェアの Web フレームワークで、独自の最小限の機能を持っています。Express アプリケーションは、基本的にはミドルウェア関数の一連の呼び出しです。
-_Middleware_ 関数は、[request object](/5x/api#req) (`req`) にアクセスできる関数です。 [response object](/5x/api#res) (`res`) と、アプリケーションのリクエストレスポンスサイクルの次のミドルウェア関数。 次のミドルウェア関数は通常`next`という名前の変数で表されます。
+_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`) と、アプリケーションのリクエストレスポンスサイクルの次のミドルウェア関数。 次のミドルウェア関数は通常`next`という名前の変数で表されます。 次のミドルウェア関数は通常`next`という名前の変数で表されます。
ミドルウェア機能は以下のタスクを実行できます。
@@ -16,7 +17,7 @@ _Middleware_ 関数は、[request object](/5x/api#req) (`req`) にアクセス
- リクエストレスポンスサイクルを終了します。
- スタック内の次のミドルウェア関数を呼び出します。
-現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。
+現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。 そうでなければ、リクエストはハングアップのままになります。
Express アプリケーションでは、次のタイプのミドルウェアを使用できます。
@@ -28,14 +29,15 @@ Express アプリケーションでは、次のタイプのミドルウェアを
アプリケーションレベルおよびルーターレベルのミドルウェアは、任意のマウントパスでロードできます。
また、一連のミドルウェア関数を一緒にロードして、マウントポイントでミドルウェアシステムのサブスタックを作成することもできます。
+また、一連のミドルウェア関数を一緒にロードして、マウントポイントでミドルウェアシステムのサブスタックを作成することもできます。
## アプリケーションレベルのミドルウェア
-`app.use()` と `app()` を使用して、アプリケーションレベルのミドルウェアを [app object](/5x/api#app) のインスタンスにバインドします。 ETHOD()関数。`METHOD`はミドルウェア関数が小文字で処理するHTTPメソッドです(GET、PUT、POSTなど)。
+`app.use()` と `app()` を使用して、アプリケーションレベルのミドルウェアを [app object](/api#app) のインスタンスにバインドします。 ETHOD()関数。`METHOD`はミドルウェア関数が小文字で処理するHTTPメソッドです(GET、PUT、POSTなど)。
-この例では、マウントパスのないミドルウェア関数を示します。 この関数はアプリがリクエストを受け取るたびに実行されます。
+この例では、マウントパスのないミドルウェア関数を示します。 この関数はアプリがリクエストを受け取るたびに実行されます。 この関数はアプリがリクエストを受け取るたびに実行されます。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,7 +47,18 @@ app.use((req, res, next) => {
});
```
-この例では、`/user/:id` パスにマウントされたミドルウェア関数を示します。 関数は `/user/:id` パス上の任意のタイプの
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
+This example shows a middleware function mounted on the `/user/:id` path. この例では、`/user/:id` パスにマウントされたミドルウェア関数を示します。 関数は `/user/:id` パス上の任意のタイプの
HTTP リクエストに対して実行されます。
```js
@@ -55,7 +68,7 @@ app.use('/user/:id', (req, res, next) => {
});
```
-この例ではルートとハンドラ関数(ミドルウェアシステム)を示します。 関数は`/user/:id`パスへのGETリクエストを処理します。
+This example shows a route and its handler function (middleware system). この例ではルートとハンドラ関数(ミドルウェアシステム)を示します。 関数は`/user/:id`パスへのGETリクエストを処理します。
```js
app.get('/user/:id', (req, res, next) => {
@@ -63,8 +76,8 @@ app.get('/user/:id', (req, res, next) => {
});
```
-次に、マウントパスを持つ一連のミドルウェア関数をマウントポイントにロードする例を示します。
-これは `/user/:id` パスにHTTPリクエスト情報を出力するミドルウェアのサブスタックを示しています。
+Here is an example of loading a series of middleware functions at a mount point, with a mount path.
+It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
```js
app.use(
@@ -80,7 +93,7 @@ app.use(
);
```
-ルートハンドラを使用すると、パスに複数のルートを定義できます。 下の例では、`/user/:id`パスへのGETリクエストに対する2つのルートを定義しています。 2番目のルートは問題を引き起こすことはありませんが、最初のルートはリクエスト応答サイクルを終了するため、呼び出されることはありません。
+Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
この例では、`/user/:id`パスへのGETリクエストを処理するミドルウェアサブスタックを示します。
@@ -167,7 +180,7 @@ const router = express.Router();
次のコード例は、ルーターレベルのミドルウェアを使用して、アプリケーションレベルのミドルウェアに対して上記のミドルウェアシステムを複製します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +229,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
ルーターのミドルウェア関数の残りをスキップするには、`next('router')`
を呼び出してルーターインスタンスからコントロールを渡します。
この例では、`/user/:id`パスへのGETリクエストを処理するミドルウェアサブスタックを示します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,13 +305,35 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## エラー処理のミドルウェア
-エラー処理ミドルウェアは常に\_4つの引数を取ります。 エラー処理ミドルウェア関数として
-識別するには、4つの引数を指定する必要があります。 `next`
-オブジェクトを使用しなくても、署名を維持するために指定する必要があります。 Otherwise, the `next` object will be
+Error-handling middleware always takes _four_ arguments. You must provide four arguments to
+identify it as an error-handling middleware function. Even if you don't need to use the `next`
+object, you must specify it to maintain the signature. Otherwise, the `next` object will be
interpreted as regular middleware and will fail to handle errors.
@@ -266,16 +351,16 @@ app.use((err, req, res, next) => {
## 組み込みのミドルウェア
-バージョン 4.x 以降、Express は [Connect](https://github.com/senchalabs/connect) に依存しなくなりました。 The middleware
+Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). バージョン 4.x 以降、Express は [Connect](https://github.com/senchalabs/connect) に依存しなくなりました。 The middleware
functions that were previously included with Express are now in separate modules; see [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
Express には次のミドルウェア関数が組み込まれています。
-- [express.static](/5x/api#express.static) は、HTML ファイル、画像などの静的なアセットを提供します。
-- [express.json](/5x/api#express.json) は、JSON ペイロードで受信したリクエストを解析します。 \*\*注意: Express 4.16.0+で利用可能
-- [express.urlencoded](/5x/api#express.urlencoded) は、URLエンコードされたペイロードで受信するリクエストを解析します。 \*\*注意: Express 4.16.0+で利用可能
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
-## サードパーティのミドルウェア
+## Third-party middleware
サードパーティ製ミドルウェアを使用して、Express アプリに機能を追加します。
@@ -283,11 +368,9 @@ Express には次のミドルウェア関数が組み込まれています。
次の例は、cookie-parser関数`cookie-parser`のインストールとロードを示しています。
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +379,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
Expressで一般的に使用されるサードパーティミドルウェア関数の部分的なリストについては、[サードパーティミドルウェア](/resources/middleware)を参照してください。
diff --git a/src/content/docs/ja/4x/guide/using-template-engines.mdx b/src/content/docs/ja/4x/guide/using-template-engines.mdx
index 63d74a5f75..0a78a99ab4 100644
--- a/src/content/docs/ja/4x/guide/using-template-engines.mdx
+++ b/src/content/docs/ja/4x/guide/using-template-engines.mdx
@@ -4,30 +4,30 @@ description: Pug、Handlebars、EJSなどのテンプレートエンジンをExp
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-_template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 実行時に、テンプレートエンジンはテンプレートファイルの
+_template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 _template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 実行時に、テンプレートエンジンはテンプレートファイルの
変数を実際の値に置き換えます。 をクリックして、テンプレートをクライアントに送信する HTML ファイルに変換します。
このアプローチにより、HTML ページのデザインが容易になります。
+このアプローチにより、HTML ページのデザインが容易になります。
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-テンプレートファイルをレンダリングするには、ジェネレータが作成したデフォルトの `app.js` で、次の[アプリケーション設定プロパティ](/api#app.set)を設定します。
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views` テンプレートファイルがあるディレクトリ。 例: `app.set('views', './views')` 。
デフォルトはアプリケーションのルートディレクトリにある `views` ディレクトリです。
-- `viewengine` を使用するテンプレートエンジン。 たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使います。
+- `viewengine` を使用するテンプレートエンジン。 `viewengine` を使用するテンプレートエンジン。 たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使います。
次に、対応するテンプレートエンジン npm パッケージをインストールします。例えば、Pug をインストールする場合:
-```bash
-$ npm install pug --save
-```
+
Pug のような Express 準拠のテンプレートエンジンは、 `__express(filePath, options, callback)` という名前の関数、 `res.render()` がテンプレートコードのレンダリングを呼び出す
をエクスポートします。
-一部のテンプレートエンジンはこの規約に従っていません。 [@ladjs/integrate](https://www.npmjs.com/package/@ladjs/consolidate)
+一部のテンプレートエンジンはこの規約に従っていません。 一部のテンプレートエンジンはこの規約に従っていません。 [@ladjs/integrate](https://www.npmjs.com/package/@ladjs/consolidate)
ライブラリは、一般的な Node.js テンプレートエンジンのすべてをマッピングすることによって、この規則に従っており、したがって、Express 内でシームレスに動作します。
@@ -49,7 +49,7 @@ html
h1= message
```
-`index.pug` ファイルをレンダリングするルートを作成します。 If the `view engine` property is not set,
+`index.pug` ファイルをレンダリングするルートを作成します。 `index.pug` ファイルをレンダリングするルートを作成します。 If the `view engine` property is not set,
you must specify the extension of the `view` file. そうでなければ、それを省略することができます。
```js
@@ -60,4 +60,4 @@ app.get('/', (req, res) => {
ホームページへのリクエストを行うと、 `index.pug` ファイルは HTML としてレンダリングされます。
-ビューエンジンキャッシュはテンプレートの出力の内容をキャッシュせず、元のテンプレート自体のみキャッシュします。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。
+ビューエンジンキャッシュはテンプレートの出力の内容をキャッシュせず、元のテンプレート自体のみキャッシュします。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。
diff --git a/src/content/docs/ja/4x/guide/writing-middleware.mdx b/src/content/docs/ja/4x/guide/writing-middleware.mdx
index 4a20386f60..db0b68eda1 100644
--- a/src/content/docs/ja/4x/guide/writing-middleware.mdx
+++ b/src/content/docs/ja/4x/guide/writing-middleware.mdx
@@ -5,7 +5,7 @@ description: Express.jsアプリケーション用にカスタムミドルウェ
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ 関数は、[request object](/5x/api#req) (`req`) にアクセスできる関数です。 [response object](/5x/api#res) (`res`)とアプリケーションのリクエストレスポンスサイクルの中の `next` 関数。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。
+_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`)とアプリケーションのリクエストレスポンスサイクルの中の `next` 関数。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。
ミドルウェア機能は以下のタスクを実行できます。
@@ -14,7 +14,7 @@ _Middleware_ 関数は、[request object](/5x/api#req) (`req`) にアクセス
- リクエストレスポンスサイクルを終了します。
- スタック内の次のミドルウェアを呼び出します。
-現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。
+現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。 そうでなければ、リクエストはハングアップのままになります。
次の図はミドルウェア関数呼び出しの要素を示しています。
@@ -40,26 +40,26 @@ _Middleware_ 関数は、[request object](/5x/api#req) (`req`) にアクセス
- HTTP レスポンス は、
- 規則によって「res」と呼ばれるミドルウェア関数への引数です。
+ HTTP [response](/api/response) argument to the middleware function, called "res" by convention.
-
+HTTP [request](/api/request) argument to the middleware function, called "req" by convention.
|
-Express 5以降、Promiseを返すミドルウェア関数はエラーの拒否またはスロー時に「next(value)」を呼び出します。 `next`は、拒否された値またはスローされたエラーで呼び出されます。
+Express 5以降、Promiseを返すミドルウェア関数はエラーの拒否またはスロー時に「next(value)」を呼び出します。 `next`は、拒否された値またはスローされたエラーで呼び出されます。 `next`は、拒否された値またはスローされたエラーで呼び出されます。
## 例
+以下は、簡単な「Hello World」エクスプレスアプリケーションの例です。
以下は、簡単な「Hello World」エクスプレスアプリケーションの例です。
The remainder of this article will define and add three middleware functions to the application:
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -70,9 +70,22 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### ミドルウェア関数 myLogger
-以下は、「myLogger」というミドルウェア関数の簡単な例です。 この関数は、アプリへのリクエストがそれを通過したときに
+Here is a simple example of a middleware function called "myLogger". This function just prints
+"LOGGED" when a request to the app passes through it. 以下は、「myLogger」というミドルウェア関数の簡単な例です。 この関数は、アプリへのリクエストがそれを通過したときに
"LOGGED" を出力します。 ミドルウェア関数は、`myLogger`という名前の
変数に割り当てられます。
@@ -85,17 +98,18 @@ const myLogger = function (req, res, next) {
-上記の `next()` の呼び出しに注目してください。 この関数を呼び出すと、
-アプリケーションで次のミドルウェア関数が呼び出されます。 `next()`関数はノードの一部ではありません。 sまたはExpress APIはミドルウェア関数に渡される3番目の
-引数です。 `next()`関数には、
-という名前が付けられますが、慣習的には常に「next」という名前が付けられています。 混乱を避けるため、常にこの規約を使用してください。
+Notice the call above to `next()`. Calling this function invokes the next middleware function in
+the app. The `next()` function is not a part of the Node.js or Express API, but is the third
+argument that is passed to the middleware function. The `next()` function could be named anything,
+but by convention it is always named "next". To avoid confusion, always use this convention.
ミドルウェア関数をロードするには、ミドルウェア関数を指定して `app.use()` を呼び出します。
例えば、次のコードはルートパス(/)の前に`myLogger`ミドルウェア関数をロードします。
+For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -113,6 +127,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
アプリがリクエストを受け取るたびに、「LOGGED」というメッセージが端末に出力されます。
ミドルウェアのロード順序は重要です。最初にロードされるミドルウェア関数も最初に実行されます。
@@ -133,9 +166,9 @@ const requestTime = function (req, res, next) {
};
```
-アプリは `requestTime` ミドルウェア関数を使用します。 また、ルートのコールバック関数はミドルウェア関数が`req`(リクエストオブジェクト)に追加するプロパティを使用します。
+The app now uses the `requestTime` middleware function. アプリは `requestTime` ミドルウェア関数を使用します。 また、ルートのコールバック関数はミドルウェア関数が`req`(リクエストオブジェクト)に追加するプロパティを使用します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -155,6 +188,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
アプリのルートにリクエストを送信すると、アプリはブラウザにリクエストのタイムスタンプを表示するようになりました。
### ミドルウェア関数 validateCookies
@@ -173,9 +227,9 @@ async function cookieValidator(cookies) {
}
```
-ここでは、[`cookie-parser`](/resources/middleware/cookie-parser) ミドルウェアを使用して、`req`オブジェクトから入ってくるCookieを解析し、それを私たちの`cookieValidator`関数に渡します。 `validateCookies`ミドルウェアは、拒否時に自動的にエラーハンドラをトリガーするPromiseを返します。
+ここでは、[`cookie-parser`](/resources/middleware/cookie-parser) ミドルウェアを使用して、`req`オブジェクトから入ってくるCookieを解析し、それを私たちの`cookieValidator`関数に渡します。 `validateCookies`ミドルウェアは、拒否時に自動的にエラーハンドラをトリガーするPromiseを返します。 The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -199,12 +253,40 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
`await cookieValidator(req.cookies)`の後に`next()`が呼び出されることに注意してください。 これにより、
`cookieValidator` が解決した場合、スタック内の次のミドルウェアが呼ばれます。 If you pass anything
to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
request as being an error and will skip any remaining non-error handling routing and middleware
+functions. This ensures that if
+`cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything
+to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
+request as being an error and will skip any remaining non-error handling routing and middleware
functions.
@@ -217,9 +299,7 @@ Express ミドルウェアの詳細については、[Express ミドルウェア
ミドルウェアの設定が必要な場合は、optionsオブジェクトや他のパラメータを受け付ける関数をエクスポートしてください。 入力パラメータに基づいてミドルウェアの実装を返します。
-ファイル: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -228,10 +308,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
ミドルウェアを以下のように使用できるようになりました。
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/ja/4x/starter/basic-routing.mdx b/src/content/docs/ja/4x/starter/basic-routing.mdx
index 65a350f2c0..d94e4a1079 100644
--- a/src/content/docs/ja/4x/starter/basic-routing.mdx
+++ b/src/content/docs/ja/4x/starter/basic-routing.mdx
@@ -26,7 +26,8 @@ app.METHOD(PATH, HANDLER);
このチュートリアルでは、`app` という名前の `express` インスタンスが作成され、サーバーが
動作していることを前提としています。 アプリの作成に慣れていない場合は、Hello world
-exampleを参照してください。
+exampleを参照してください。 If you are not familiar with creating an app and starting it, see the Hello world
+example.
diff --git a/src/content/docs/ja/4x/starter/examples.mdx b/src/content/docs/ja/4x/starter/examples.mdx
index 0c0be44268..5211ad2df3 100644
--- a/src/content/docs/ja/4x/starter/examples.mdx
+++ b/src/content/docs/ja/4x/starter/examples.mdx
@@ -41,5 +41,4 @@ import Alert from '@components/primitives/Alert/Alert.astro';
ここでの掲載は、 Expressjsプロジェクトチームの推奨または推奨を構成するものではありません。
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - ORMとしてExpressとNext.jsを使用したフルスタックアプリ [Prisma](https://www.npmjs.com/package/prisma)
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - ORMとして [Prisma](https://www.npmjs.com/package/prisma) を使用する Express をTypeScript で REST API
diff --git a/src/content/docs/ja/4x/starter/faq.md b/src/content/docs/ja/4x/starter/faq.md
index 41f95f69d8..d46ade50ed 100644
--- a/src/content/docs/ja/4x/starter/faq.md
+++ b/src/content/docs/ja/4x/starter/faq.md
@@ -5,12 +5,13 @@ description: Express.jsについてよく寄せられる質問の答えを見つ
## アプリケーションを構成するにはどうすればいいですか?
-この質問には決定的な答えはありません。 The answer depends
+この質問には決定的な答えはありません。 この質問には決定的な答えはありません。 The answer depends
on the scale of your application and the team that is involved. 可能な限り
柔軟性を持たせるために、Expressは構造的な仮定をしません。
ルートやその他のアプリケーション固有のロジックは、任意のディレクトリ構造において、
好きな数のファイルに保存することができます。 View the following
+examples for inspiration: View the following
examples for inspiration:
- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
@@ -25,6 +26,8 @@ examples for inspiration:
Express にはデータベースという概念はありません。 このコンセプトは
サードパーティ製の Node モジュールに残されており、ほぼすべてのデータベースと
+インターフェイスを使用できます。 このコンセプトは
+サードパーティ製の Node モジュールに残されており、ほぼすべてのデータベースと
インターフェイスを使用できます。
モデルを中心とした Express ベースのフレームワークについては [LoopBack](http://loopback.io) を参照してください。
@@ -33,11 +36,15 @@ Express にはデータベースという概念はありません。 このコ
Authentication is another opinionated area that Express does not
venture into. 任意の認証スキームを使用できます。
+任意の認証スキームを使用できます。
単純なユーザー名/パスワードスキームについては、[この例](https://github.com/expressjs/express/tree/master/examples/auth)を参照してください。
## Expressはどのテンプレートエンジンをサポートしていますか?
-Express は、\`(path, local, callback) 署名に適合するテンプレートエンジンをサポートしています。
+Express は、\\`(path, local, callback) 署名に適合するテンプレートエンジンをサポートしています。
+テンプレートエンジンインターフェイスとキャッシュを正規化するには、
+[consolidate.js](https://github.com/visionmedia/consolidate.js)
+プロジェクトをサポートしてください。 リストされていないテンプレートエンジンは引き続きExpress 署名をサポートする可能性があります。
テンプレートエンジンインターフェイスとキャッシュを正規化するには、
[consolidate.js](https://github.com/visionmedia/consolidate.js)
プロジェクトをサポートしてください。 リストされていないテンプレートエンジンは引き続きExpress 署名をサポートする可能性があります。
@@ -47,6 +54,7 @@ Express は、\`(path, local, callback) 署名に適合するテンプレート
## 404応答はどのように処理すればいいですか?
Expressでは404応答はエラーの結果ではないため、
+エラーハンドラミドルウェアはそれらを捕捉しません。 Expressでは404応答はエラーの結果ではないため、
エラーハンドラミドルウェアはそれらを捕捉しません。 This behavior is
because a 404 response simply indicates the absence of additional work to do;
in other words, Express has executed all middleware functions and routes,
@@ -79,7 +87,10 @@ app.use((err, req, res, next) => {
## プレーンHTMLをレンダリングするにはどうすればいいですか?
-違います! `res.render()`関数でHTMLを「レンダリング」する必要はありません。
+違います! 違います! `res.render()`関数でHTMLを「レンダリング」する必要はありません。
+特定のファイルがある場合は、 `res.sendFile()` 関数を使用します。
+ディレクトリから多くのアセットを提供している場合は、`express.static()`
+ミドルウェア関数を使用してください。
特定のファイルがある場合は、 `res.sendFile()` 関数を使用します。
ディレクトリから多くのアセットを提供している場合は、`express.static()`
ミドルウェア関数を使用してください。
diff --git a/src/content/docs/ja/4x/starter/hello-world.mdx b/src/content/docs/ja/4x/starter/hello-world.mdx
index 9f8fe81ab2..1077d1e2a8 100644
--- a/src/content/docs/ja/4x/starter/hello-world.mdx
+++ b/src/content/docs/ja/4x/starter/hello-world.mdx
@@ -7,14 +7,14 @@ import Alert from '@components/primitives/Alert/Alert.astro';
-以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 It is a single file app
+以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 It is a single file app
— _not_ what you'd get if you use the [Express generator](/starter/generator), which
creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and
sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,12 +28,27 @@ app.listen(port, () => {
});
```
-このアプリはサーバーを起動し、接続のためにポート3000をリッスンします。 アプリはルート URL (`/`) または _route_ にリクエスト
-を返します。 他のすべてのパスについては、**404 Not Found**で応答します。
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
+This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
+to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
## ローカルで実行中
-最初に `myapp` という名前のディレクトリを作成し、変更して `npm init` を実行します。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
+最初に `myapp` という名前のディレクトリを作成し、変更して `npm init` を実行します。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing). Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
`myapp` ディレクトリで、`app.js`という名前のファイルを作成し、上の例からコードをコピーします。
diff --git a/src/content/docs/ja/4x/starter/installing.mdx b/src/content/docs/ja/4x/starter/installing.mdx
index 3d720295e7..1f6f38e729 100644
--- a/src/content/docs/ja/4x/starter/installing.mdx
+++ b/src/content/docs/ja/4x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: プロジェクトディレクトリの設定やnpmとの依存関
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
始める前に、 [Node.js](https://nodejs.org/) 0.10 以上がインストールされていることを確認してください。 次に、アプリケーションのディレクトリを作成し、その中に移動します。
@@ -15,9 +16,7 @@ cd myapp
`npm init` コマンドを使用して、アプリケーション用の `package.json` ファイルを作成します。
`package.json` がどのように動作するかについては、[npm の package.json handling](https://docs.npmjs.com/files/package.json) を参照してください。
-```bash
-npm init
-```
+
このコマンドを実行すると、アプリケーションの名前やバージョンなど、さまざまなものが表示されます。
今のところ、RETURNを押すと、ほとんどのデフォルトを受け入れることができます。以下の例外があります。
@@ -30,15 +29,11 @@ entry point: (index.js)
次に、Expressを`myapp`ディレクトリにインストールし、依存関係リストに保存します。 例:
-```bash
-npm install express
-```
+
Express を一時的にインストールし、依存関係リストに追加しないでください。
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/ja/4x/starter/static-files.mdx b/src/content/docs/ja/4x/starter/static-files.mdx
index 35d8aaf70a..9ce3278bac 100644
--- a/src/content/docs/ja/4x/starter/static-files.mdx
+++ b/src/content/docs/ja/4x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
`root` 引数は、静的アセットを提供するルートディレクトリを指定します。
-引数 `options` の詳細については、 [express.static](/5x/api#express.static) を参照してください。
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
例えば、`public`という名前のディレクトリに画像、CSSファイル、JavaScriptファイルを表示するには、次のコードを使用します。
@@ -56,7 +56,7 @@ serving static assets.
-\`expressで提供されるファイルに対して、仮想パスプレフィックス(ファイルシステム内にパスが実際に存在しない場所)を作成します。 以下に示すように、staticディレクトリの[mount path](/5x/api#app.use)を指定します。
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -72,11 +72,17 @@ http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
```
-しかし、`express.static`関数に与えるパスは、`node`プロセスを起動したディレクトリからの相対パスです。 expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です:
+しかし、`express.static`関数に与えるパスは、`node`プロセスを起動したディレクトリからの相対パスです。 expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です: expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
`serve-static` 関数とそのオプションの詳細については、 [serve-static](/resources/middleware/serve-static) を参照してください。
diff --git a/src/content/docs/ja/5x/guide/behind-proxies.mdx b/src/content/docs/ja/5x/guide/behind-proxies.mdx
index 27a7590f87..7e2360ce8f 100644
--- a/src/content/docs/ja/5x/guide/behind-proxies.mdx
+++ b/src/content/docs/ja/5x/guide/behind-proxies.mdx
@@ -5,7 +5,7 @@ description: クライアントの IP アドレスを処理するトラストプ
import Alert from '@components/primitives/Alert/Alert.astro';
-リバースプロキシの背後で Express アプリケーションを実行する場合、Express API の中には予想以外の値が返されるものがあります。 これを調整するために `trust proxy` アプリケーションの設定は、Express API のリバースプロキシによって提供された情報を公開するために使用することができます。 最も一般的な問題は、クライアントのIPアドレスを公開するAPIで、リバースプロキシの内部IPアドレスが表示される可能性があります。
+リバースプロキシの背後で Express アプリケーションを実行する場合、Express API の中には予想以外の値が返されるものがあります。 これを調整するために `trust proxy` アプリケーションの設定は、Express API のリバースプロキシによって提供された情報を公開するために使用することができます。 最も一般的な問題は、クライアントのIPアドレスを公開するAPIで、リバースプロキシの内部IPアドレスが表示される可能性があります。 これを調整するために `trust proxy` アプリケーションの設定は、Express API のリバースプロキシによって提供された情報を公開するために使用することができます。 最も一般的な問題は、クライアントのIPアドレスを公開するAPIで、リバースプロキシの内部IPアドレスが表示される可能性があります。
@@ -25,7 +25,7 @@ import Alert from '@components/primitives/Alert/Alert.astro';
`true` の場合、クライアントの IP アドレスは `X-Forwarded-For` ヘッダーの中の一番左のエントリとして理解されます。
-`false` の場合、アプリはクライアントに直接向いていると理解され、クライアントの IP アドレスは `req.socket.remoteAddress` に由来します。 これはデフォルトの設定です。
+`false` の場合、アプリはクライアントに直接向いていると理解され、クライアントの IP アドレスは `req.socket.remoteAddress` に由来します。 これはデフォルトの設定です。 これはデフォルトの設定です。
`true` に設定する場合、信頼されている最後のリバースプロキシが以下のすべての HTTP ヘッダを削除/上書きすることが重要です: `X-Forwarded-For` 。 `X-Forwarded-Host` と `X-Forwarded-Proto` があれば、クライアントが何らかの値を提供できるかもしれません。
@@ -35,7 +35,7 @@ import Alert from '@components/primitives/Alert/Alert.astro';
| IPアドレス |
-リバースプロキシとして信頼する IP アドレス、サブネット、または IP アドレスとサブネットの配列。 次のリストに、事前に設定されたサブネット名が表示されます。
+リバースプロキシとして信頼する IP アドレス、サブネット、または IP アドレスとサブネットの配列。 次のリストに、事前に設定されたサブネット名が表示されます。 次のリストに、事前に設定されたサブネット名が表示されます。
- loopback - `127.0.0.1/8`, `::1/128`
- linklocal - `169.254.0.0/16`, `fe80::/10`
@@ -57,7 +57,7 @@ app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); // specify mul
|
| 数字 |
-Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 `0`の値は、最初に信頼されていないアドレスが`req.socket.remoteAddress`であることを意味します。つまり、リバースプロキシは存在しません。
+Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 Expressアプリケーションから離れたホップの最大数のアドレスを使用してください。 `req.socket.remoteAddress` は最初のホップで、残りは右から左への `X-Forwarded-For` ヘッダで探します。 `0`の値は、最初に信頼されていないアドレスが`req.socket.remoteAddress`であることを意味します。つまり、リバースプロキシは存在しません。
この設定を使用する場合は、複数がないことを確認することが重要です。 Expressアプリケーションへの異なる長さのパスは、クライアントが設定されたホップ数よりも少なくすることができるようになります。 それ以外の場合は、クライアントが何らかの価値を提供することができます。
@@ -86,13 +86,13 @@ app.set('trust proxy', (ip) => {
-
- [req.hostname](/api#req.hostname) の値は、 `X-Forwarded-Host`
- ヘッダで設定された値から取得されます。 クライアントやプロキシによって設定できます
+ The value of [req.hostname](/api/request/#reqhostname) is derived from the value set in the
+ `X-Forwarded-Host` header, which can be set by the client or by the proxy.
-
`X-Forwarded-Proto` はリバースプロキシによって設定することで、アプリが https`か`http\`
- か無効な名前かをアプリに伝えることができます。 この値は [req.protocol](/api#req.protocol)
- で反映されます。
+ か無効な名前かをアプリに伝えることができます。 This value is reflected by
+ [req.protocol](/api/request/#reqprotocol).
-
[req.ip](/api#req.ip) と [req.ips](/api#req.ips) の値は、 ソケットアドレスと `X-Forwarded-For`
@@ -100,4 +100,4 @@ app.set('trust proxy', (ip) => {
-`trust proxy` は、 [proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されています。 詳細については、そのドキュメントを参照してください。
+`trust proxy` は、 [proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されています。 詳細については、そのドキュメントを参照してください。 詳細については、そのドキュメントを参照してください。
diff --git a/src/content/docs/ja/5x/guide/debugging.mdx b/src/content/docs/ja/5x/guide/debugging.mdx
index 0d007eaafe..158b013dd9 100644
--- a/src/content/docs/ja/5x/guide/debugging.mdx
+++ b/src/content/docs/ja/5x/guide/debugging.mdx
@@ -84,7 +84,7 @@ $ DEBUG=express:* node ./bin/www
express:view render "/projects/example/views/index.pug" +1ms
```
-ルータの実装からのみログを見るには、`DEBUG`の値を`express:router`に設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。
+ルータの実装からのみログを見るには、`DEBUG`の値を`express:router`に設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。 同様に、アプリケーションの実装からのログのみを見るには、`DEBUG`の値を`express:application`などに設定します。
## `express` で生成されたアプリケーション
@@ -117,8 +117,7 @@ Node.js を介して実行する場合、デバッグログの動作を変更す
The environment variables beginning with `DEBUG_` end up being converted into an Options object
-that gets used with `%o`/`%O` formatters.
-[`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) の完全な
+that gets used with `%o`/`%O` formatters. [`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) の完全な
リストについては Node.js のドキュメントを参照してください。
diff --git a/src/content/docs/ja/5x/guide/error-handling.mdx b/src/content/docs/ja/5x/guide/error-handling.mdx
index ad7c54ba34..4a8bc65690 100644
--- a/src/content/docs/ja/5x/guide/error-handling.mdx
+++ b/src/content/docs/ja/5x/guide/error-handling.mdx
@@ -6,6 +6,7 @@ description: Express.jsが同期コードと非同期コードのエラーを処
import Alert from '@components/primitives/Alert/Alert.astro';
*Error Handling*は、
+が同期と非同期の両方で発生するエラーをExpress がキャッチして処理する方法を指します。 _Error Handling_は、
が同期と非同期の両方で発生するエラーをExpress がキャッチして処理する方法を指します。 Expressにはデフォルトのエラー
ハンドラが付属しているので、始めるために自分で書く必要はありません。
@@ -16,6 +17,7 @@ Express がルートハンドラと
ルートハンドラとミドルウェア
内の同期コードで発生するエラーは追加の作業を必要としません。 同期コードがエラーをスローする場合、Expressは
+キャッチして処理します。 例: 同期コードがエラーをスローする場合、Expressは
キャッチして処理します。 例:
```js
@@ -40,8 +42,9 @@ app.get('/', (req, res, next) => {
});
```
-Express 5以降、Promise
-を返すルートハンドラとミドルウェアは、エラーの拒否またはスロー時に自動的に`next(value)`を呼び出します。
+Define error-handling middleware functions in the same way as other middleware functions,
+except error-handling functions have four arguments instead of three:
+`(err, req, res, next)`.
例:
```js
@@ -78,7 +81,7 @@ which is called with or without errors. エラーがなければ、2番目の
ハンドラが実行されます。そうでなければ、Expressはエラーをキャッチして処理します。
route handler または
-ミドルウェアによって呼び出された非同期コードで発生するエラーをキャッチし、処理のために Express に渡す必要があります。 例:
+ミドルウェアによって呼び出された非同期コードで発生するエラーをキャッチし、処理のために Express に渡す必要があります。 例: 例:
```js
app.get('/', (req, res, next) => {
@@ -93,12 +96,13 @@ app.get('/', (req, res, next) => {
```
上の例では、
+非同期コードのエラーをキャッチし、Expressに渡すために`try...catch`ブロックを使用しています。 上の例では、
非同期コードのエラーをキャッチし、Expressに渡すために`try...catch`ブロックを使用しています。 `try...catch`
ブロックが省略された場合、Expressは同期
ハンドラコードの一部ではないため、エラーをキャッチしません。
プロミスを返す関数
-を使うと、`try...catch` のオーバーヘッドを避けることができます。 例:
+を使うと、`try...catch` のオーバーヘッドを避けることができます。 例: 例:
```js
app.get('/', (req, res, next) => {
@@ -115,7 +119,7 @@ you can simply provide `next` as the final catch handler and Express will catch
because the catch handler is given the error as the first argument.
また、非同期コードを些細なものに減らすことで、同期エラー
-のキャッチに依存するハンドラのチェーンを使用することもできます。 例:
+のキャッチに依存するハンドラのチェーンを使用することもできます。 例: 例:
```js
app.get('/', [
@@ -133,11 +137,15 @@ app.get('/', [
```
上の例では、`readFile`
+呼び出しからいくつかの些細な文があります。 上の例では、`readFile`
呼び出しからいくつかの些細な文があります。 `readFile` でエラーが発生した場合、エラーは Express に渡されます。 それ以外の場合は、
チェーン内の次のハンドラ
で同期エラー処理の世界にすばやく戻ります。 そして、上記の例はデータを処理しようとします。 これが失敗した場合、
同期エラーハンドラはそれをキャッチします。 `readFile`コールバックの
内でこの処理を行った場合、アプリケーションが終了する可能性があり、Expressエラー
+ハンドラは実行されません。 そして、上記の例はデータを処理しようとします。 これが失敗した場合、
+同期エラーハンドラはそれをキャッチします。 `readFile`コールバックの
+内でこの処理を行った場合、アプリケーションが終了する可能性があり、Expressエラー
ハンドラは実行されません。
どちらの方法を使っても、Expressエラーハンドラを呼び出し、
@@ -145,7 +153,7 @@ app.get('/', [
## デフォルトのエラーハンドラです
-Expressには、アプリで発生する可能性のあるエラーを処理する内蔵のエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。
+Expressには、アプリで発生する可能性のあるエラーを処理する内蔵のエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの末尾に追加されます。
If you pass an error to `next()` and you do not handle it in a custom error
handler, it will be handled by the built-in error handler; the error will be
@@ -207,7 +215,7 @@ app.use((err, req, res, next) => {
エラー処理ミドルウェアは、他の `app.use()`とルート呼び出しの後に最後に定義します。例:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +231,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
ミドルウェア関数内からのレスポンスは、HTMLエラーページ、シンプルなメッセージ、JSON文字列など、あらゆる形式で使用できます。
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +254,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. 例えば、`XHR`とそれ以外のリクエストに対してエラーハンドラ
を定義するには、次のようにします。
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +270,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
この例では、一般的な`logErrors`はリクエストと
エラー情報を`stderr`に書き込むことができます。
@@ -258,7 +298,7 @@ function logErrors(err, req, res, next) {
この例でも、`clientErrorHandler`は以下のように定義されています。この場合、エラーは明示的に次のエラーに渡されます。
-エラー処理関数で「next」を呼び出さない場合、レスポンスの書き込み(および終了)を行う責任があることに注意してください。 そうでなければ、これらのリクエストは「ハング」し、ガベージコレクションの対象になりません。
+Notice that when _not_ calling "next" in an error-handling function, you are responsible for writing (and ending) the response. Otherwise, those requests will "hang" and will not be eligible for garbage collection.
```js
function clientErrorHandler(err, req, res, next) {
@@ -279,7 +319,7 @@ function errorHandler(err, req, res, next) {
}
```
-複数のコールバック関数を持つルートハンドラがある場合は、`route` パラメータを使用して次のルートハンドラにスキップできます。 例:
+複数のコールバック関数を持つルートハンドラがある場合は、`route` パラメータを使用して次のルートハンドラにスキップできます。 例: 例:
```js
app.get(
@@ -308,5 +348,7 @@ app.get(
`next()`と`next(err)`への呼び出しは、現在のハンドラが完了している状態を示します。
`next(err)`は、上記のように
に設定されているものを除いて、チェーン内の残りのハンドラをすべてスキップします。
+`next(err)` will skip all remaining handlers in the chain except for those that are set up to
+handle errors as described above.
diff --git a/src/content/docs/ja/5x/guide/overriding-express-api.md b/src/content/docs/ja/5x/guide/overriding-express-api.md
index 7bd8a1a5cf..683b56ee93 100644
--- a/src/content/docs/ja/5x/guide/overriding-express-api.md
+++ b/src/content/docs/ja/5x/guide/overriding-express-api.md
@@ -3,18 +3,18 @@ title: Express API のオーバーライド
description: リクエストとレスポンスオブジェクトのメソッドとプロパティをプロトタイプを使用してオーバーライドすることで、Express.js API をカスタマイズして拡張する方法をご覧ください。
---
-Express API は、リクエストオブジェクトとレスポンスオブジェクトのさまざまなメソッドとプロパティで構成されています。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。
+Express API は、リクエストオブジェクトとレスポンスオブジェクトのさまざまなメソッドとプロパティで構成されています。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。 これらはプロトタイプによって継承されます。 Express API には 2 つの拡張ポイントがあります。
1. `express.request` と `express.response` のグローバルプロトタイプ。
2. `app.request`と`app.response`でアプリ固有のプロトタイプ。
-グローバルプロトタイプを変更すると、読み込まれたすべてのExpressアプリが同じプロセスで影響を受けます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。
+グローバルプロトタイプを変更すると、読み込まれたすべてのExpressアプリが同じプロセスで影響を受けます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。 必要に応じて、新しいアプリを作成した後にアプリ固有のプロトタイプを変更するだけで、アプリ固有の変更を行うことができます。
## メソッド
カスタム関数を割り当てることで、既存のメソッドの署名と振る舞いを独自のメソッドで上書きできます。
-以下は、 [res.sendStatus](/4x/api#res.sendStatus) の挙動を上書きした例です。
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
@@ -23,7 +23,7 @@ app.response.sendStatus = function (statusCode, type, message) {
};
```
-上記の実装は `res.sendStatus` の元の署名を完全に変更します。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。
+上記の実装は `res.sendStatus` の元の署名を完全に変更します。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。 ステータスコード、エンコーディングタイプ、およびメッセージをクライアントに送信できるようになりました。
オーバーライドされたメソッドは次のように使用できます。
@@ -42,7 +42,7 @@ category 1 のプロパティは、現在のリクエスト-レスポンスサ
カテゴリ2のプロパティはExpress API拡張機能APIを使用して上書きすることができます。
-次のコードは `req.ip` の値をどのように派生するかを書き換えます。 これで、`Client-IP` リクエストヘッダの値を返すだけです。
+次のコードは `req.ip` の値をどのように派生するかを書き換えます。 次のコードは `req.ip` の値をどのように派生するかを書き換えます。 これで、`Client-IP` リクエストヘッダの値を返すだけです。
```js
Object.defineProperty(app.request, 'ip', {
@@ -56,7 +56,7 @@ Object.defineProperty(app.request, 'ip', {
## プロトタイプ
-Express API を提供するためには、Express に渡された request/response オブジェクトを (`app(req) 経由で) 提供します。 res)`は同じプロトタイプチェーンから継承する必要があります。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。
+Express API を提供するためには、Express に渡された request/response オブジェクトを (`app(req) 経由で) 提供します。 res)`は同じプロトタイプチェーンから継承する必要があります。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。 デフォルトでは、リクエストの `http.IncomingRequest.prototype` と、レスポンスの `http.ServerResponse.prototype` です。
必要がない限り、これはアプリケーションレベルでのみ行うことを推奨します。 また、使用されているプロトタイプは、可能な限りデフォルトのプロトタイプに近い機能を備えていることに注意してください。
diff --git a/src/content/docs/ja/5x/guide/routing.mdx b/src/content/docs/ja/5x/guide/routing.mdx
index b06384930d..0d65b09387 100644
--- a/src/content/docs/ja/5x/guide/routing.mdx
+++ b/src/content/docs/ja/5x/guide/routing.mdx
@@ -7,21 +7,24 @@ import Alert from '@components/primitives/Alert/Alert.astro';
_Routing_ とは、アプリケーションのエンドポイント(URI)がクライアントリクエストに対してどのように応答するかを指します。
For an introduction to routing, see [Basic routing](/starter/basic-routing).
+For an introduction to routing, see [Basic routing](/starter/basic-routing).
HTTPメソッドに対応するExpress `app` オブジェクトのメソッドを使用してルーティングを定義します。
-のように、`app。 POST リクエストを処理する GET リクエストと `app.post\` を処理します。 完全なリストについては、
-[app.METHOD](/api/application#appmethodpath-callback--callback-) を参照してください。 [app.all()](/api/application#appallpath-callback--callback-)を使用して、すべてのHTTPメソッドと[app]を処理することもできます。 se()](/api/application#appusepath-callback--callback) to
-コールバック関数としてミドルウェアを指定する (詳細は [Using middleware](/guide/using-middleware) を参照)。
+のように、`app。 POST リクエストを処理する GET リクエストと `app.post\` を処理します。 For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
+specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-これらのルーティングメソッドは、アプリケーションが指定されたルート (エンドポイント) と HTTP メソッドへのリクエストを受け取ったときに呼び出されるコールバック関数 ("handler functions" と呼ばれることもあります) を指定します。 言い換えれば、アプリケーションは指定されたルートとメソッドに一致するリクエストを「リッスン」します。 マッチを検出すると、指定されたコールバック関数を呼び出します。
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. 言い換えれば、アプリケーションは指定されたルートとメソッドに一致するリクエストを「リッスン」します。 マッチを検出すると、指定されたコールバック関数を呼び出します。
実際、ルーティングメソッドは引数として複数のコールバック関数を持つことができます。
複数のコールバック関数を使用。 コールバック関数に `next` を引数として渡し、関数の本体内で `next()` を呼び出して、次のコールバックに
を渡すことが重要です。
+複数のコールバック関数を使用。 コールバック関数に `next` を引数として渡し、関数の本体内で `next()` を呼び出して、次のコールバックに
+を渡すことが重要です。
以下のコードは、非常に基本的なルートの例です。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +34,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## ルートメソッド
routeメソッドはHTTPメソッドのいずれかから派生し、`express` クラスのインスタンスに追加されます。
@@ -51,8 +65,9 @@ app.post('/', (req, res) => {
Expressは、すべてのHTTPリクエストメソッドに対応するメソッドをサポートしています: `get`、`post`など。
完全なリストについては、 [app.METHOD](/api/application#appmethodpath-callback--callback-) を参照してください。
+For a full list, see [app.METHOD](/api/application#appmethod).
-特別なルーティングメソッド`app.all()`があり、\_all_HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用されます。 例えば、`GET`を使用しているかどうかに関わらず、ルート`"/secret"へのリクエストに対して以下のハンドラが実行されます。 `POST`、`PUT`、`DELETE\`、または[http module](https://nodejs.org/api/http.html#http_http_methods)でサポートされている他のHTTPリクエストメソッド。
+特別なルーティングメソッド`app.all()`があり、\_all_HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用されます。 例えば、`GET`を使用しているかどうかに関わらず、ルート`"/secret"へのリクエストに対して以下のハンドラが実行されます。 `POST`、`PUT`、`DELETE\`、または[http module](https://nodejs.org/api/http.html#http_http_methods)でサポートされている他のHTTPリクエストメソッド。 For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
```js
app.all('/secret', (req, res, next) => {
@@ -63,18 +78,19 @@ app.all('/secret', (req, res, next) => {
## ルートパス
-ルートパスはリクエストメソッドと組み合わせて、リクエストを作成できるエンドポイントを定義します。 ルートパスは文字列または正規表現にすることができます。
+ルートパスはリクエストメソッドと組み合わせて、リクエストを作成できるエンドポイントを定義します。 ルートパスは文字列または正規表現にすることができます。 Route paths can be strings or regular expressions.
Express はルートパスに一致する [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) v8 を使用します。ルートパスの定義におけるすべての可能性については、path-to-regexp ドキュメントを参照してください。
[Express Playground Router](https://bjohansebas.github.io/playground-router/)は、パターンマッチングをサポートしていませんが、基本的なExpressルートをテストするための便利なツールです。
+[Express Playground Router](https://bjohansebas.github.io/playground-router/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
### 文字列パス
-文字列パスはリクエストと完全に一致します。 ドット(`.`)とハイフン(`-`)は文字通り解釈されます。
+文字列パスはリクエストと完全に一致します。 ドット(`.`)とハイフン(`-`)は文字通り解釈されます。 The dot (`.`) and hyphen (`-`) are interpreted literally.
クエリ文字列はルートパスの一部ではありません。
@@ -94,7 +110,7 @@ app.get('/random.text', (req, res) => {
### ワイルドカード
-ワイルドカードはプレフィックスの後の任意のパスに一致します。 ルートパラメータと同様に名前が必要で、パスセグメントの配列として取得されます。
+Wildcards match any path after a prefix. ワイルドカードはプレフィックスの後の任意のパスに一致します。 ルートパラメータと同様に名前が必要で、パスセグメントの配列として取得されます。
```js
app.get('/files/*filepath', (req, res) => {
@@ -118,7 +134,7 @@ app.get('/{*splat}', (req, res) => {
### 任意のセグメント
-ルートパスで任意のセグメントを定義するには、括弧を使用します。 セグメントが存在しない場合、パラメータは `req.params` から省略されます。
+Use braces to define optional segments in a route path. ルートパスで任意のセグメントを定義するには、括弧を使用します。 セグメントが存在しない場合、パラメータは `req.params` から省略されます。
```js
app.get('/:file{.:ext}', (req, res) => {
@@ -130,13 +146,13 @@ app.get('/:file{.:ext}', (req, res) => {
-`?`、`+`、`*`、`[]`、`()`の文字は予約されており、ルートパスの文字列として使用することはできません。 必要に応じてエスケープするには`\`を使用します。
+`?`、`+`、`*`、`[]`、`()`の文字は予約されており、ルートパスの文字列として使用することはできません。 必要に応じてエスケープするには`\`を使用します。 Use `\` to escape them if needed.
### 正規表現
-正規表現をルートパスとして使用することもできます。 これは、より複雑なマッチングロジックが必要な場合に便利です。
+正規表現をルートパスとして使用することもできます。 これは、より複雑なマッチングロジックが必要な場合に便利です。 This is useful when you need more complex matching logic.
```js
// Matches any path containing "a"
@@ -152,7 +168,7 @@ app.get(/.*fly$/, (req, res) => {
## ルートパラメータ
-ルートパラメータは、URL 内の位置で指定された値をキャプチャするために使用される名前付きの URL セグメントです。 取得した値は `req.params` オブジェクト内に入力され、パス内でそれぞれのキーとして指定されたrouteパラメータの名前が入力されます。
+Route parameters are named URL segments that are used to capture the values specified at their position in the URL. ルートパラメータは、URL 内の位置で指定された値をキャプチャするために使用される名前付きの URL セグメントです。 取得した値は `req.params` オブジェクト内に入力され、パス内でそれぞれのキーとして指定されたrouteパラメータの名前が入力されます。
```
Route path: /users/:userId/books/:bookId
@@ -191,13 +207,14 @@ req.params: { "genus": "Prunus", "species": "persica" }
正規表現文字はルートパスではサポートされていません。 代わりにパスまたは正規表現の配列を使用してください。
-詳細については、[パスルートマッチング構文](/guide/migrating-5#path-syntax)を参照してください。
+詳細については、[パスルートマッチング構文](/guide/migrating-5#path-syntax)を参照してください。 Use an array of paths or regular expressions instead.
+See the [path route matching syntax](/guide/migrating-5#path-route-matching-syntax) for more information.
## Route handlers
-リクエストを処理するために、 [middleware](/guide/using-middleware) のように動作する複数のコールバック関数を提供できます。 唯一の例外は、これらのコールバックが `next('route')` を呼び出して、残りのルートコールバックをバイパスすることです。 このメカニズムを使用して、ルート上に事前条件を設定できます。 次に現在のルートを進める理由がなければ次のルートに制御を渡す。
+リクエストを処理するために、 [middleware](/guide/using-middleware) のように動作する複数のコールバック関数を提供できます。 唯一の例外は、これらのコールバックが `next('route')` を呼び出して、残りのルートコールバックをバイパスすることです。 このメカニズムを使用して、ルート上に事前条件を設定できます。 次に現在のルートを進める理由がなければ次のルートに制御を渡す。 The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
```js
app.get('/user/:id', (req, res, next) => {
@@ -219,7 +236,7 @@ app.get('/user/:id', (req, res) => {
ルートハンドラは、次の例に示すように、関数、関数の配列、または両方の組み合わせの形式で使用できます。
-単一のコールバック関数はルートを処理できます。 例:
+単一のコールバック関数はルートを処理できます。 例: 例:
```js
app.get('/example/a', (req, res) => {
@@ -227,7 +244,7 @@ app.get('/example/a', (req, res) => {
});
```
-複数のコールバック関数がルートを処理できます (`next` オブジェクトを指定してください)。 例:
+複数のコールバック関数がルートを処理できます (`next` オブジェクトを指定してください)。 例: 例:
```js
app.get(
@@ -242,7 +259,7 @@ app.get(
);
```
-コールバック関数の配列はルートを処理できます。 例:
+コールバック関数の配列はルートを処理できます。 例: 例:
```js
const cb0 = function (req, res, next) {
@@ -262,7 +279,7 @@ const cb2 = function (req, res) {
app.get('/example/c', [cb0, cb1, cb2]);
```
-独立した関数と関数の配列の組み合わせは、ルートを処理することができます。 例:
+独立した関数と関数の配列の組み合わせは、ルートを処理することができます。 例: 例:
```js
const cb0 = function (req, res, next) {
@@ -290,24 +307,25 @@ app.get(
## レスポンスメソッド
-次の表のレスポンスオブジェクト (`res`) のメソッドは、クライアントにレスポンスを送信し、リクエスト応答のサイクルを終了することができます。 これらのメソッドのいずれもルートハンドラから呼び出されない場合、クライアントリクエストはハングしたままになります。
+次の表のレスポンスオブジェクト (`res`) のメソッドは、クライアントにレスポンスを送信し、リクエスト応答のサイクルを終了することができます。 これらのメソッドのいずれもルートハンドラから呼び出されない場合、クライアントリクエストはハングしたままになります。 If none of these methods are called from a route handler, the client request will be left hanging.
-| 方法 | 説明 |
-| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | ダウンロードするファイルを指示します。 |
-| [res.end()](/api/response#resenddata-encoding-callback) | 応答プロセスを終了します。 |
-| [res.json()](/api/response#resjsonbody) | JSON 応答を送信します。 |
-| [res.jsonp()](/api/response#resjsonpbody) | JSONP サポートを使用して JSON 応答を送信します。 |
-| [res.redirect()](/api/response#resredirectstatus-path) | リダイレクトします。 |
-| [res.render()](/api/response#resrenderview--locals--callback) | ビューテンプレートをレンダリングします。 |
-| [res.send()](/api/response#ressendbody) | さまざまなタイプの応答を送信します。 |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | ファイルをオクテットストリームとして送信する。 |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | レスポンスステータスコードを設定し、文字列表現をレスポンスボディとして送信します。 |
+| 方法 | 説明 |
+| ----------------------------------------------- | ---------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | ダウンロードするファイルを指示します。 |
+| [res.end()](/api/response#resend) | 応答プロセスを終了します。 |
+| [res.json()](/api/response#resjson) | JSON 応答を送信します。 |
+| [res.jsonp()](/api/response#resjsonp) | JSONP サポートを使用して JSON 応答を送信します。 |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | ビューテンプレートをレンダリングします。 |
+| [res.send()](/api/response#ressend) | さまざまなタイプの応答を送信します。 |
+| [res.sendFile()](/api/response#ressendfile) | ファイルをオクテットストリームとして送信する。 |
+| [res.sendStatus()](/api/response#ressendstatus) | レスポンスステータスコードを設定し、文字列表現をレスポンスボディとして送信します。 |
## app.route()
`app.route()` を使用すると、ルートパスに対してチェーン可能なルートハンドラを作成できます。
パスは単一の場所で指定されているため、モジュラールートを作成することは、冗長性とタイプミスを削減するのに役立ちます。 ルートの詳細については、以下を参照してください: [Router() documentation](/api/router)。
+Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](/api/router).
以下は、`app.route()`を使用して定義されたルートハンドラの例です。
@@ -327,13 +345,13 @@ app
## express.Router
-`express.Router` クラスを使用して、モジュール化されたマウント可能なルートハンドラを作成します。 `Router`インスタンスは完全なミドルウェアとルーティングシステムです。そのため、しばしば「ミニアプリ」と呼ばれます。
+Use the `express.Router` class to create modular, mountable route handlers. `express.Router` クラスを使用して、モジュール化されたマウント可能なルートハンドラを作成します。 `Router`インスタンスは完全なミドルウェアとルーティングシステムです。そのため、しばしば「ミニアプリ」と呼ばれます。
次の例では、ルータをモジュールとして作成し、ミドルウェア関数をロードします。 いくつかのルートを定義し、メインアプリのパスにルータモジュールをマウントします。
appディレクトリに`birds.js`という名前のルーターファイルを作成します。以下の内容を使用します。
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -356,9 +374,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
次に、アプリにルーターモジュールをロードします。
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -366,9 +408,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
アプリは `/birds` と `/birds/about` へのリクエストを処理できるようになりました。 同様に、ルート固有の「timeLog」ミドルウェア関数を呼び出します。
-ただし、親ルート `/birds` にパスパラメータがある場合、サブルートからデフォルトではアクセスできません。 アクセス可能にするには、 `mergeParams` オプションを Router コンストラクタ [reference](/api/application#appusepath-callback--callback) に渡す必要があります。
+ただし、親ルート `/birds` にパスパラメータがある場合、サブルートからデフォルトではアクセスできません。 アクセス可能にするには、 `mergeParams` オプションを Router コンストラクタ [reference](/api/application#appusepath-callback--callback) に渡す必要があります。 To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/ja/5x/guide/using-middleware.mdx b/src/content/docs/ja/5x/guide/using-middleware.mdx
index 02b75c8250..dbaadc2e90 100644
--- a/src/content/docs/ja/5x/guide/using-middleware.mdx
+++ b/src/content/docs/ja/5x/guide/using-middleware.mdx
@@ -4,10 +4,11 @@ description: Express.jsアプリケーションでミドルウェアを使用す
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express はルーティングおよびミドルウェアの Web フレームワークで、独自の最小限の機能を持っています。Express アプリケーションは、基本的にはミドルウェア関数の一連の呼び出しです。
-_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`) と、アプリケーションのリクエストレスポンスサイクルの次のミドルウェア関数。 次のミドルウェア関数は通常`next`という名前の変数で表されます。
+_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`) と、アプリケーションのリクエストレスポンスサイクルの次のミドルウェア関数。 次のミドルウェア関数は通常`next`という名前の変数で表されます。 次のミドルウェア関数は通常`next`という名前の変数で表されます。
ミドルウェア機能は以下のタスクを実行できます。
@@ -16,7 +17,7 @@ _Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスで
- リクエストレスポンスサイクルを終了します。
- スタック内の次のミドルウェア関数を呼び出します。
-現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。
+現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。 そうでなければ、リクエストはハングアップのままになります。
Express アプリケーションでは、次のタイプのミドルウェアを使用できます。
@@ -28,14 +29,15 @@ Express アプリケーションでは、次のタイプのミドルウェアを
アプリケーションレベルおよびルーターレベルのミドルウェアは、任意のマウントパスでロードできます。
また、一連のミドルウェア関数を一緒にロードして、マウントポイントでミドルウェアシステムのサブスタックを作成することもできます。
+また、一連のミドルウェア関数を一緒にロードして、マウントポイントでミドルウェアシステムのサブスタックを作成することもできます。
## アプリケーションレベルのミドルウェア
`app.use()` と `app()` を使用して、アプリケーションレベルのミドルウェアを [app object](/api#app) のインスタンスにバインドします。 ETHOD()関数。`METHOD`はミドルウェア関数が小文字で処理するHTTPメソッドです(GET、PUT、POSTなど)。
-この例では、マウントパスのないミドルウェア関数を示します。 この関数はアプリがリクエストを受け取るたびに実行されます。
+この例では、マウントパスのないミドルウェア関数を示します。 この関数はアプリがリクエストを受け取るたびに実行されます。 この関数はアプリがリクエストを受け取るたびに実行されます。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,7 +47,18 @@ app.use((req, res, next) => {
});
```
-この例では、`/user/:id` パスにマウントされたミドルウェア関数を示します。 関数は `/user/:id` パス上の任意のタイプの
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
+This example shows a middleware function mounted on the `/user/:id` path. この例では、`/user/:id` パスにマウントされたミドルウェア関数を示します。 関数は `/user/:id` パス上の任意のタイプの
HTTP リクエストに対して実行されます。
```js
@@ -55,7 +68,7 @@ app.use('/user/:id', (req, res, next) => {
});
```
-この例ではルートとハンドラ関数(ミドルウェアシステム)を示します。 関数は`/user/:id`パスへのGETリクエストを処理します。
+This example shows a route and its handler function (middleware system). この例ではルートとハンドラ関数(ミドルウェアシステム)を示します。 関数は`/user/:id`パスへのGETリクエストを処理します。
```js
app.get('/user/:id', (req, res, next) => {
@@ -63,8 +76,8 @@ app.get('/user/:id', (req, res, next) => {
});
```
-次に、マウントパスを持つ一連のミドルウェア関数をマウントポイントにロードする例を示します。
-これは `/user/:id` パスにHTTPリクエスト情報を出力するミドルウェアのサブスタックを示しています。
+Here is an example of loading a series of middleware functions at a mount point, with a mount path.
+It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
```js
app.use(
@@ -80,7 +93,7 @@ app.use(
);
```
-ルートハンドラを使用すると、パスに複数のルートを定義できます。 下の例では、`/user/:id`パスへのGETリクエストに対する2つのルートを定義しています。 2番目のルートは問題を引き起こすことはありませんが、最初のルートはリクエスト応答サイクルを終了するため、呼び出されることはありません。
+Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
この例では、`/user/:id`パスへのGETリクエストを処理するミドルウェアサブスタックを示します。
@@ -167,7 +180,7 @@ const router = express.Router();
次のコード例は、ルーターレベルのミドルウェアを使用して、アプリケーションレベルのミドルウェアに対して上記のミドルウェアシステムを複製します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +229,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
ルーターのミドルウェア関数の残りをスキップするには、`next('router')`
を呼び出してルーターインスタンスからコントロールを渡します。
この例では、`/user/:id`パスへのGETリクエストを処理するミドルウェアサブスタックを示します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,13 +305,35 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## エラー処理のミドルウェア
-エラー処理ミドルウェアは常に\_4つの引数を取ります。 エラー処理ミドルウェア関数として
-識別するには、4つの引数を指定する必要があります。 `next`
-オブジェクトを使用しなくても、署名を維持するために指定する必要があります。 Otherwise, the `next` object will be
+Error-handling middleware always takes _four_ arguments. You must provide four arguments to
+identify it as an error-handling middleware function. Even if you don't need to use the `next`
+object, you must specify it to maintain the signature. Otherwise, the `next` object will be
interpreted as regular middleware and will fail to handle errors.
@@ -266,16 +351,16 @@ app.use((err, req, res, next) => {
## 組み込みのミドルウェア
-バージョン 4.x 以降、Express は [Connect](https://github.com/senchalabs/connect) に依存しなくなりました。 The middleware
+Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). バージョン 4.x 以降、Express は [Connect](https://github.com/senchalabs/connect) に依存しなくなりました。 The middleware
functions that were previously included with Express are now in separate modules; see [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
Express には次のミドルウェア関数が組み込まれています。
-- [express.static](/api#express.static) は、HTML ファイル、画像などの静的なアセットを提供します。
-- [express.json](/api#express.json) は、JSON ペイロードで受信したリクエストを解析します。 \*\*注意: Express 4.16.0+で利用可能
-- [express.urlencoded](/api#express.urlencoded) は、URLエンコードされたペイロードで受信するリクエストを解析します。 \*\*注意: Express 4.16.0+で利用可能
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
-## サードパーティのミドルウェア
+## Third-party middleware
サードパーティ製ミドルウェアを使用して、Express アプリに機能を追加します。
@@ -283,11 +368,9 @@ Express には次のミドルウェア関数が組み込まれています。
次の例は、cookie-parser関数`cookie-parser`のインストールとロードを示しています。
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +379,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
Expressで一般的に使用されるサードパーティミドルウェア関数の部分的なリストについては、[サードパーティミドルウェア](/resources/middleware)を参照してください。
diff --git a/src/content/docs/ja/5x/guide/using-template-engines.mdx b/src/content/docs/ja/5x/guide/using-template-engines.mdx
index 0375f3ec06..0a78a99ab4 100644
--- a/src/content/docs/ja/5x/guide/using-template-engines.mdx
+++ b/src/content/docs/ja/5x/guide/using-template-engines.mdx
@@ -4,30 +4,30 @@ description: Pug、Handlebars、EJSなどのテンプレートエンジンをExp
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-_template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 実行時に、テンプレートエンジンはテンプレートファイルの
+_template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 _template engine_ を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 実行時に、テンプレートエンジンはテンプレートファイルの
変数を実際の値に置き換えます。 をクリックして、テンプレートをクライアントに送信する HTML ファイルに変換します。
このアプローチにより、HTML ページのデザインが容易になります。
+このアプローチにより、HTML ページのデザインが容易になります。
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-テンプレートファイルをレンダリングするには、ジェネレータが作成したデフォルトの `app.js` で、次の[アプリケーション設定プロパティ](/4x/api#app.set)を設定します。
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views` テンプレートファイルがあるディレクトリ。 例: `app.set('views', './views')` 。
デフォルトはアプリケーションのルートディレクトリにある `views` ディレクトリです。
-- `viewengine` を使用するテンプレートエンジン。 たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使います。
+- `viewengine` を使用するテンプレートエンジン。 `viewengine` を使用するテンプレートエンジン。 たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使います。
次に、対応するテンプレートエンジン npm パッケージをインストールします。例えば、Pug をインストールする場合:
-```bash
-$ npm install pug --save
-```
+
Pug のような Express 準拠のテンプレートエンジンは、 `__express(filePath, options, callback)` という名前の関数、 `res.render()` がテンプレートコードのレンダリングを呼び出す
をエクスポートします。
-一部のテンプレートエンジンはこの規約に従っていません。 [@ladjs/integrate](https://www.npmjs.com/package/@ladjs/consolidate)
+一部のテンプレートエンジンはこの規約に従っていません。 一部のテンプレートエンジンはこの規約に従っていません。 [@ladjs/integrate](https://www.npmjs.com/package/@ladjs/consolidate)
ライブラリは、一般的な Node.js テンプレートエンジンのすべてをマッピングすることによって、この規則に従っており、したがって、Express 内でシームレスに動作します。
@@ -49,7 +49,7 @@ html
h1= message
```
-`index.pug` ファイルをレンダリングするルートを作成します。 If the `view engine` property is not set,
+`index.pug` ファイルをレンダリングするルートを作成します。 `index.pug` ファイルをレンダリングするルートを作成します。 If the `view engine` property is not set,
you must specify the extension of the `view` file. そうでなければ、それを省略することができます。
```js
@@ -60,4 +60,4 @@ app.get('/', (req, res) => {
ホームページへのリクエストを行うと、 `index.pug` ファイルは HTML としてレンダリングされます。
-ビューエンジンキャッシュはテンプレートの出力の内容をキャッシュせず、元のテンプレート自体のみキャッシュします。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。
+ビューエンジンキャッシュはテンプレートの出力の内容をキャッシュせず、元のテンプレート自体のみキャッシュします。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。
diff --git a/src/content/docs/ja/5x/guide/writing-middleware.mdx b/src/content/docs/ja/5x/guide/writing-middleware.mdx
index 4aeecbf7d4..385cfbacbb 100644
--- a/src/content/docs/ja/5x/guide/writing-middleware.mdx
+++ b/src/content/docs/ja/5x/guide/writing-middleware.mdx
@@ -5,7 +5,7 @@ description: Express.jsアプリケーション用にカスタムミドルウェ
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`)とアプリケーションのリクエストレスポンスサイクルの中の `next` 関数。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。
+_Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスできる関数です。 [response object](/api#res) (`res`)とアプリケーションのリクエストレスポンスサイクルの中の `next` 関数。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。 `next` 関数はExpressルータ内の関数で、呼び出されたときに現在のミドルウェアを継承してミドルウェアを実行します。
ミドルウェア機能は以下のタスクを実行できます。
@@ -14,22 +14,23 @@ _Middleware_ 関数は、[request object](/api#req) (`req`) にアクセスで
- リクエストレスポンスサイクルを終了します。
- スタック内の次のミドルウェアを呼び出します。
-現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。
+現在のミドルウェア関数がリクエスト応答サイクルを終了しない場合は、次のミドルウェア関数に制御を渡すために `next()` を呼び出す必要があります。 そうでなければ、リクエストはハングアップのままになります。 そうでなければ、リクエストはハングアップのままになります。
次の図はミドルウェア関数呼び出しの要素を示しています。

-Express 5以降、Promiseを返すミドルウェア関数はエラーの拒否またはスロー時に「next(value)」を呼び出します。 `next`は、拒否された値またはスローされたエラーで呼び出されます。
+Express 5以降、Promiseを返すミドルウェア関数はエラーの拒否またはスロー時に「next(value)」を呼び出します。 `next`は、拒否された値またはスローされたエラーで呼び出されます。 `next`は、拒否された値またはスローされたエラーで呼び出されます。
## 例
+以下は、簡単な「Hello World」エクスプレスアプリケーションの例です。
以下は、簡単な「Hello World」エクスプレスアプリケーションの例です。
The remainder of this article will define and add three middleware functions to the application:
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -40,9 +41,22 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### ミドルウェア関数 myLogger
-以下は、「myLogger」というミドルウェア関数の簡単な例です。 この関数は、アプリへのリクエストがそれを通過したときに
+Here is a simple example of a middleware function called "myLogger". This function just prints
+"LOGGED" when a request to the app passes through it. 以下は、「myLogger」というミドルウェア関数の簡単な例です。 この関数は、アプリへのリクエストがそれを通過したときに
"LOGGED" を出力します。 ミドルウェア関数は、`myLogger`という名前の
変数に割り当てられます。
@@ -55,17 +69,18 @@ const myLogger = function (req, res, next) {
-上記の `next()` の呼び出しに注目してください。 この関数を呼び出すと、
-アプリケーションで次のミドルウェア関数が呼び出されます。 `next()`関数はノードの一部ではありません。 sまたはExpress APIはミドルウェア関数に渡される3番目の
-引数です。 `next()`関数には、
-という名前が付けられますが、慣習的には常に「next」という名前が付けられています。 混乱を避けるため、常にこの規約を使用してください。
+Notice the call above to `next()`. Calling this function invokes the next middleware function in
+the app. The `next()` function is not a part of the Node.js or Express API, but is the third
+argument that is passed to the middleware function. The `next()` function could be named anything,
+but by convention it is always named "next". To avoid confusion, always use this convention.
ミドルウェア関数をロードするには、ミドルウェア関数を指定して `app.use()` を呼び出します。
例えば、次のコードはルートパス(/)の前に`myLogger`ミドルウェア関数をロードします。
+For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -83,6 +98,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
アプリがリクエストを受け取るたびに、「LOGGED」というメッセージが端末に出力されます。
ミドルウェアのロード順序は重要です。最初にロードされるミドルウェア関数も最初に実行されます。
@@ -103,9 +137,9 @@ const requestTime = function (req, res, next) {
};
```
-アプリは `requestTime` ミドルウェア関数を使用します。 また、ルートのコールバック関数はミドルウェア関数が`req`(リクエストオブジェクト)に追加するプロパティを使用します。
+The app now uses the `requestTime` middleware function. アプリは `requestTime` ミドルウェア関数を使用します。 また、ルートのコールバック関数はミドルウェア関数が`req`(リクエストオブジェクト)に追加するプロパティを使用します。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -125,6 +159,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
アプリのルートにリクエストを送信すると、アプリはブラウザにリクエストのタイムスタンプを表示するようになりました。
### ミドルウェア関数 validateCookies
@@ -143,9 +198,9 @@ async function cookieValidator(cookies) {
}
```
-ここでは、[`cookie-parser`](/resources/middleware/cookie-parser) ミドルウェアを使用して、`req`オブジェクトから入ってくるCookieを解析し、それを私たちの`cookieValidator`関数に渡します。 `validateCookies`ミドルウェアは、拒否時に自動的にエラーハンドラをトリガーするPromiseを返します。
+ここでは、[`cookie-parser`](/resources/middleware/cookie-parser) ミドルウェアを使用して、`req`オブジェクトから入ってくるCookieを解析し、それを私たちの`cookieValidator`関数に渡します。 `validateCookies`ミドルウェアは、拒否時に自動的にエラーハンドラをトリガーするPromiseを返します。 The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -169,12 +224,40 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
`await cookieValidator(req.cookies)`の後に`next()`が呼び出されることに注意してください。 これにより、
`cookieValidator` が解決した場合、スタック内の次のミドルウェアが呼ばれます。 If you pass anything
to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
request as being an error and will skip any remaining non-error handling routing and middleware
+functions. This ensures that if
+`cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything
+to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
+request as being an error and will skip any remaining non-error handling routing and middleware
functions.
@@ -187,9 +270,7 @@ Express ミドルウェアの詳細については、[Express ミドルウェア
ミドルウェアの設定が必要な場合は、optionsオブジェクトや他のパラメータを受け付ける関数をエクスポートしてください。 入力パラメータに基づいてミドルウェアの実装を返します。
-ファイル: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -198,10 +279,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
ミドルウェアを以下のように使用できるようになりました。
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/ja/5x/starter/basic-routing.mdx b/src/content/docs/ja/5x/starter/basic-routing.mdx
index 65a350f2c0..d94e4a1079 100644
--- a/src/content/docs/ja/5x/starter/basic-routing.mdx
+++ b/src/content/docs/ja/5x/starter/basic-routing.mdx
@@ -26,7 +26,8 @@ app.METHOD(PATH, HANDLER);
このチュートリアルでは、`app` という名前の `express` インスタンスが作成され、サーバーが
動作していることを前提としています。 アプリの作成に慣れていない場合は、Hello world
-exampleを参照してください。
+exampleを参照してください。 If you are not familiar with creating an app and starting it, see the Hello world
+example.
diff --git a/src/content/docs/ja/5x/starter/examples.mdx b/src/content/docs/ja/5x/starter/examples.mdx
index f95e9eeba1..97cef8939a 100644
--- a/src/content/docs/ja/5x/starter/examples.mdx
+++ b/src/content/docs/ja/5x/starter/examples.mdx
@@ -45,5 +45,4 @@ Expressjsプロジェクトチームの推奨または推奨を構成するも
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - ORMとしてExpressとNext.jsを使用したフルスタックアプリ [Prisma](https://www.npmjs.com/package/prisma)
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - ORMとして [Prisma](https://www.npmjs.com/package/prisma) を使用する Express をTypeScript で REST API
diff --git a/src/content/docs/ja/5x/starter/faq.md b/src/content/docs/ja/5x/starter/faq.md
index f95643148f..3be772423d 100644
--- a/src/content/docs/ja/5x/starter/faq.md
+++ b/src/content/docs/ja/5x/starter/faq.md
@@ -5,12 +5,13 @@ description: Express.jsについてよく寄せられる質問の答えを見つ
## アプリケーションを構成するにはどうすればいいですか?
-この質問には決定的な答えはありません。 The answer depends
+この質問には決定的な答えはありません。 この質問には決定的な答えはありません。 The answer depends
on the scale of your application and the team that is involved. 可能な限り
柔軟性を持たせるために、Expressは構造的な仮定をしません。
ルートやその他のアプリケーション固有のロジックは、任意のディレクトリ構造において、
好きな数のファイルに保存することができます。 View the following
+examples for inspiration: View the following
examples for inspiration:
- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
@@ -25,6 +26,8 @@ examples for inspiration:
Express にはデータベースという概念はありません。 このコンセプトは
サードパーティ製の Node モジュールに残されており、ほぼすべてのデータベースと
+インターフェイスを使用できます。 このコンセプトは
+サードパーティ製の Node モジュールに残されており、ほぼすべてのデータベースと
インターフェイスを使用できます。
モデルを中心とした Express ベースのフレームワークについては [LoopBack](http://loopback.io) を参照してください。
@@ -33,11 +36,15 @@ Express にはデータベースという概念はありません。 このコ
Authentication is another opinionated area that Express does not
venture into. 任意の認証スキームを使用できます。
+任意の認証スキームを使用できます。
単純なユーザー名/パスワードスキームについては、[この例](https://github.com/expressjs/express/tree/master/examples/auth)を参照してください。
## Expressはどのテンプレートエンジンをサポートしていますか?
-Express は、\`(path, local, callback) 署名に適合するテンプレートエンジンをサポートしています。
+Express は、\\`(path, local, callback) 署名に適合するテンプレートエンジンをサポートしています。
+テンプレートエンジンインターフェイスとキャッシュを正規化するには、
+[consolidate.js](https://github.com/visionmedia/consolidate.js)
+プロジェクトをサポートしてください。 リストされていないテンプレートエンジンは引き続きExpress 署名をサポートする可能性があります。
テンプレートエンジンインターフェイスとキャッシュを正規化するには、
[consolidate.js](https://github.com/visionmedia/consolidate.js)
プロジェクトをサポートしてください。 リストされていないテンプレートエンジンは引き続きExpress 署名をサポートする可能性があります。
@@ -47,6 +54,7 @@ Express は、\`(path, local, callback) 署名に適合するテンプレート
## 404応答はどのように処理すればいいですか?
Expressでは404応答はエラーの結果ではないため、
+エラーハンドラミドルウェアはそれらを捕捉しません。 Expressでは404応答はエラーの結果ではないため、
エラーハンドラミドルウェアはそれらを捕捉しません。 This behavior is
because a 404 response simply indicates the absence of additional work to do;
in other words, Express has executed all middleware functions and routes,
@@ -79,7 +87,10 @@ app.use((err, req, res, next) => {
## プレーンHTMLをレンダリングするにはどうすればいいですか?
-違います! `res.render()`関数でHTMLを「レンダリング」する必要はありません。
+違います! 違います! `res.render()`関数でHTMLを「レンダリング」する必要はありません。
+特定のファイルがある場合は、 `res.sendFile()` 関数を使用します。
+ディレクトリから多くのアセットを提供している場合は、`express.static()`
+ミドルウェア関数を使用してください。
特定のファイルがある場合は、 `res.sendFile()` 関数を使用します。
ディレクトリから多くのアセットを提供している場合は、`express.static()`
ミドルウェア関数を使用してください。
diff --git a/src/content/docs/ja/5x/starter/hello-world.mdx b/src/content/docs/ja/5x/starter/hello-world.mdx
index 9f8fe81ab2..1077d1e2a8 100644
--- a/src/content/docs/ja/5x/starter/hello-world.mdx
+++ b/src/content/docs/ja/5x/starter/hello-world.mdx
@@ -7,14 +7,14 @@ import Alert from '@components/primitives/Alert/Alert.astro';
-以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 It is a single file app
+以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 以下に埋め込まれているのは、基本的に作成できる最も簡単なExpressアプリです。 It is a single file app
— _not_ what you'd get if you use the [Express generator](/starter/generator), which
creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and
sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,12 +28,27 @@ app.listen(port, () => {
});
```
-このアプリはサーバーを起動し、接続のためにポート3000をリッスンします。 アプリはルート URL (`/`) または _route_ にリクエスト
-を返します。 他のすべてのパスについては、**404 Not Found**で応答します。
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
+This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
+to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
## ローカルで実行中
-最初に `myapp` という名前のディレクトリを作成し、変更して `npm init` を実行します。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
+最初に `myapp` という名前のディレクトリを作成し、変更して `npm init` を実行します。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing). Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
`myapp` ディレクトリで、`app.js`という名前のファイルを作成し、上の例からコードをコピーします。
diff --git a/src/content/docs/ja/5x/starter/installing.mdx b/src/content/docs/ja/5x/starter/installing.mdx
index e5607a2e07..cd734c394c 100644
--- a/src/content/docs/ja/5x/starter/installing.mdx
+++ b/src/content/docs/ja/5x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: プロジェクトディレクトリの設定やnpmとの依存関
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
始める前に、 [Node.js](https://nodejs.org/) 18 以上のインストールがあることを確認してください。 次に、アプリケーションのディレクトリを作成し、その中に移動します。
@@ -15,9 +16,7 @@ cd myapp
`npm init` コマンドを使用して、アプリケーション用の `package.json` ファイルを作成します。
`package.json` がどのように動作するかについては、[npm の package.json handling](https://docs.npmjs.com/files/package.json) を参照してください。
-```bash
-npm init
-```
+
このコマンドを実行すると、アプリケーションの名前やバージョンなど、さまざまなものが表示されます。
今のところ、RETURNを押すと、ほとんどのデフォルトを受け入れることができます。以下の例外があります。
@@ -30,12 +29,8 @@ entry point: (index.js)
次に、Expressを`myapp`ディレクトリにインストールし、依存関係リストに保存します。 例:
-```bash
-npm install express
-```
+
Express を一時的にインストールし、依存関係リストに追加しないでください。
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/ja/5x/starter/static-files.mdx b/src/content/docs/ja/5x/starter/static-files.mdx
index 03a03ac8e1..9ce3278bac 100644
--- a/src/content/docs/ja/5x/starter/static-files.mdx
+++ b/src/content/docs/ja/5x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
`root` 引数は、静的アセットを提供するルートディレクトリを指定します。
-引数 `options` の詳細については、 [express.static](/api#express.static) を参照してください。
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
例えば、`public`という名前のディレクトリに画像、CSSファイル、JavaScriptファイルを表示するには、次のコードを使用します。
@@ -56,7 +56,7 @@ serving static assets.
-\`expressで提供されるファイルに対して、仮想パスプレフィックス(ファイルシステム内にパスが実際に存在しない場所)を作成します。 以下に示すように、staticディレクトリの[mount path](/api#app.use)を指定します。
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -72,11 +72,17 @@ http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
```
-しかし、`express.static`関数に与えるパスは、`node`プロセスを起動したディレクトリからの相対パスです。 expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です:
+しかし、`express.static`関数に与えるパスは、`node`プロセスを起動したディレクトリからの相対パスです。 expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です: expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
`serve-static` 関数とそのオプションの詳細については、 [serve-static](/resources/middleware/serve-static) を参照してください。
diff --git a/src/content/docs/ko/4x/guide/error-handling.mdx b/src/content/docs/ko/4x/guide/error-handling.mdx
index 507232b013..3d65d4d3b6 100644
--- a/src/content/docs/ko/4x/guide/error-handling.mdx
+++ b/src/content/docs/ko/4x/guide/error-handling.mdx
@@ -207,7 +207,7 @@ app.use((err, req, res, next) => {
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +223,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +246,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. For example, to define an error-handler
for requests made by using `XHR` and those without:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +262,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
diff --git a/src/content/docs/ko/4x/guide/overriding-express-api.md b/src/content/docs/ko/4x/guide/overriding-express-api.md
index ac0953c945..ef06cf056c 100644
--- a/src/content/docs/ko/4x/guide/overriding-express-api.md
+++ b/src/content/docs/ko/4x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Altering the global prototypes will affect all loaded Express apps in the same p
You can override the signature and behavior of existing methods with your own, by assigning a custom function.
-Following is an example of overriding the behavior of [res.sendStatus](/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/ko/4x/guide/routing.mdx b/src/content/docs/ko/4x/guide/routing.mdx
index b795b146ba..ae581e72dd 100644
--- a/src/content/docs/ko/4x/guide/routing.mdx
+++ b/src/content/docs/ko/4x/guide/routing.mdx
@@ -10,10 +10,10 @@ For an introduction to routing, see [Basic routing](/starter/basic-routing).
You define routing using methods of the Express `app` object that correspond to HTTP methods;
for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as arguments.
With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
@@ -21,7 +21,7 @@ to the next callback.
The following code is an example of a very basic route.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
@@ -212,7 +223,7 @@ characters with an additional backslash, for example `\d+`.
-The `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`.
+The [`*`](https://github.com/expressjs/express/issues/2495) character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`.
## Route handlers
@@ -312,17 +323,17 @@ app.get(
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | Description |
+| ----------------------------------------------- | ------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Prompt a file to be downloaded. |
+| [res.end()](/api/response#resend) | End the response process. |
+| [res.json()](/api/response#resjson) | Send a JSON response. |
+| [res.jsonp()](/api/response#resjsonp) | Send a JSON response with JSONP support. |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | Render a view template. |
+| [res.send()](/api/response#ressend) | Send a response of various types. |
+| [res.sendFile()](/api/response#ressendfile) | Send a file as an octet stream. |
+| [res.sendStatus()](/api/response#ressendstatus) | Set the response status code and send its string representation as the response body. |
## app.route()
@@ -353,7 +364,7 @@ The following example creates a router as a module, loads a middleware function
Create a router file named `birds.js` in the app directory, with the following content:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -376,9 +387,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -386,9 +421,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/ko/4x/guide/using-middleware.mdx b/src/content/docs/ko/4x/guide/using-middleware.mdx
index 1372e8ca17..9e832fe09f 100644
--- a/src/content/docs/ko/4x/guide/using-middleware.mdx
+++ b/src/content/docs/ko/4x/guide/using-middleware.mdx
@@ -4,10 +4,11 @@ description: Learn how to use middleware in Express.js applications, including a
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
Middleware functions can perform the following tasks:
@@ -31,11 +32,11 @@ You can also load a series of middleware functions together, which creates a sub
## Application-level middleware
-Bind application-level middleware to an instance of the [app object](/5x/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
+Bind application-level middleware to an instance of the [app object](/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
HTTP request on the `/user/:id` path.
@@ -167,7 +179,7 @@ Load router-level middleware by using the `router.use()` and `router.METHOD()` f
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
To skip the rest of the router's middleware functions, call `next('router')`
to pass control back out of the router instance.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Error-handling middleware
@@ -271,9 +355,9 @@ functions that were previously included with Express are now in separate modules
Express has the following built-in middleware functions:
-- [express.static](/5x/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/5x/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/5x/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
## Third-party middleware
@@ -283,11 +367,9 @@ Install the Node.js module for the required functionality, then load it in your
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
diff --git a/src/content/docs/ko/4x/guide/using-template-engines.mdx b/src/content/docs/ko/4x/guide/using-template-engines.mdx
index 0f660ddbb2..18de44b3bf 100644
--- a/src/content/docs/ko/4x/guide/using-template-engines.mdx
+++ b/src/content/docs/ko/4x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate and use template engines like Pug, Handle
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ This approach makes it easier to design an HTML page.
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-To render template files, set the following [application setting properties](/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
This defaults to the `views` directory in the application root directory.
@@ -19,9 +20,7 @@ To render template files, set the following [application setting properties](/ap
Then install the corresponding template engine npm package; for example to install Pug:
-```bash
-$ npm install pug --save
-```
+
Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
diff --git a/src/content/docs/ko/4x/guide/writing-middleware.mdx b/src/content/docs/ko/4x/guide/writing-middleware.mdx
index ae0eeaf7f0..5d822b2883 100644
--- a/src/content/docs/ko/4x/guide/writing-middleware.mdx
+++ b/src/content/docs/ko/4x/guide/writing-middleware.mdx
@@ -5,7 +5,7 @@ description: Learn how to write custom middleware functions for Express.js appli
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
@@ -40,11 +40,10 @@ The following figure shows the elements of a middleware function call:
- HTTP response argument to the middleware function, called "res" by
- convention.
+ HTTP [response](/api/response) argument to the middleware function, called "res" by convention.
-HTTP request argument to the middleware function, called "req" by convention.
+HTTP [request](/api/request) argument to the middleware function, called "req" by convention.
|
@@ -59,7 +58,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -70,6 +69,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Middleware function myLogger
Here is a simple example of a middleware function called "myLogger". This function just prints
@@ -95,7 +106,7 @@ but by convention it is always named "next". To avoid confusion, always use this
To load the middleware function, call `app.use()`, specifying the middleware function.
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -113,6 +124,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
@@ -135,7 +165,7 @@ const requestTime = function (req, res, next) {
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -155,6 +185,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
### Middleware function validateCookies
@@ -175,7 +226,7 @@ async function cookieValidator(cookies) {
Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -199,6 +250,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
@@ -217,9 +292,7 @@ For more information about Express middleware, see: [Using Express middleware](/
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
-File: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -228,10 +301,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
The middleware can now be used as shown below.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/ko/4x/starter/examples.mdx b/src/content/docs/ko/4x/starter/examples.mdx
index 6685b9cbe4..a38dd14df2 100644
--- a/src/content/docs/ko/4x/starter/examples.mdx
+++ b/src/content/docs/ko/4x/starter/examples.mdx
@@ -41,5 +41,4 @@ These are some additional examples with more extensive integrations.
Expressjs project team.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
diff --git a/src/content/docs/ko/4x/starter/hello-world.mdx b/src/content/docs/ko/4x/starter/hello-world.mdx
index 629d697721..4c26ad0813 100644
--- a/src/content/docs/ko/4x/starter/hello-world.mdx
+++ b/src/content/docs/ko/4x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
diff --git a/src/content/docs/ko/4x/starter/installing.mdx b/src/content/docs/ko/4x/starter/installing.mdx
index fc66c7f9df..d2e6ad2a1a 100644
--- a/src/content/docs/ko/4x/starter/installing.mdx
+++ b/src/content/docs/ko/4x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Learn how to install Express.js in your Node.js environment, includ
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Before you begin, make sure you have [Node.js](https://nodejs.org/) 0.10 or higher installed. Then, create a directory for your application and navigate into it.
@@ -15,9 +16,7 @@ cd myapp
Use the `npm init` command to create a `package.json` file for your application.
For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
This command prompts you for a number of things, such as the name and version of your application.
For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
@@ -30,15 +29,11 @@ Enter `app.js`, or whatever you want the name of the main file to be. If you wan
Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
-```bash
-npm install express
-```
+
To install Express temporarily and not add it to the dependencies list:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/ko/4x/starter/static-files.mdx b/src/content/docs/ko/4x/starter/static-files.mdx
index 0f2c8280b1..15a901a994 100644
--- a/src/content/docs/ko/4x/starter/static-files.mdx
+++ b/src/content/docs/ko/4x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/5x/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
@@ -56,7 +56,7 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/5x/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/ko/5x/guide/error-handling.mdx b/src/content/docs/ko/5x/guide/error-handling.mdx
index 507232b013..3d65d4d3b6 100644
--- a/src/content/docs/ko/5x/guide/error-handling.mdx
+++ b/src/content/docs/ko/5x/guide/error-handling.mdx
@@ -207,7 +207,7 @@ app.use((err, req, res, next) => {
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +223,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +246,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. For example, to define an error-handler
for requests made by using `XHR` and those without:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +262,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
diff --git a/src/content/docs/ko/5x/guide/overriding-express-api.md b/src/content/docs/ko/5x/guide/overriding-express-api.md
index 6167938c4d..ef06cf056c 100644
--- a/src/content/docs/ko/5x/guide/overriding-express-api.md
+++ b/src/content/docs/ko/5x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Altering the global prototypes will affect all loaded Express apps in the same p
You can override the signature and behavior of existing methods with your own, by assigning a custom function.
-Following is an example of overriding the behavior of [res.sendStatus](/4x/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/ko/5x/guide/routing.mdx b/src/content/docs/ko/5x/guide/routing.mdx
index c24b1f6395..f7a1e00a3f 100644
--- a/src/content/docs/ko/5x/guide/routing.mdx
+++ b/src/content/docs/ko/5x/guide/routing.mdx
@@ -10,10 +10,10 @@ For an introduction to routing, see [Basic routing](/starter/basic-routing).
You define routing using methods of the Express `app` object that correspond to HTTP methods;
for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as arguments.
With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
@@ -21,7 +21,7 @@ to the next callback.
The following code is an example of a very basic route.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
@@ -292,17 +303,17 @@ app.get(
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | Description |
+| ----------------------------------------------- | ------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Prompt a file to be downloaded. |
+| [res.end()](/api/response#resend) | End the response process. |
+| [res.json()](/api/response#resjson) | Send a JSON response. |
+| [res.jsonp()](/api/response#resjsonp) | Send a JSON response with JSONP support. |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | Render a view template. |
+| [res.send()](/api/response#ressend) | Send a response of various types. |
+| [res.sendFile()](/api/response#ressendfile) | Send a file as an octet stream. |
+| [res.sendStatus()](/api/response#ressendstatus) | Set the response status code and send its string representation as the response body. |
## app.route()
@@ -333,7 +344,7 @@ The following example creates a router as a module, loads a middleware function
Create a router file named `birds.js` in the app directory, with the following content:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -356,9 +367,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -366,9 +401,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/ko/5x/guide/using-middleware.mdx b/src/content/docs/ko/5x/guide/using-middleware.mdx
index e6b97dd47f..9e832fe09f 100644
--- a/src/content/docs/ko/5x/guide/using-middleware.mdx
+++ b/src/content/docs/ko/5x/guide/using-middleware.mdx
@@ -4,6 +4,7 @@ description: Learn how to use middleware in Express.js applications, including a
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
@@ -35,7 +36,7 @@ Bind application-level middleware to an instance of the [app object](/api#app) b
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
HTTP request on the `/user/:id` path.
@@ -167,7 +179,7 @@ Load router-level middleware by using the `router.use()` and `router.METHOD()` f
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
To skip the rest of the router's middleware functions, call `next('router')`
to pass control back out of the router instance.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Error-handling middleware
@@ -271,9 +355,9 @@ functions that were previously included with Express are now in separate modules
Express has the following built-in middleware functions:
-- [express.static](/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
## Third-party middleware
@@ -283,11 +367,9 @@ Install the Node.js module for the required functionality, then load it in your
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
diff --git a/src/content/docs/ko/5x/guide/using-template-engines.mdx b/src/content/docs/ko/5x/guide/using-template-engines.mdx
index 6b74b66f11..18de44b3bf 100644
--- a/src/content/docs/ko/5x/guide/using-template-engines.mdx
+++ b/src/content/docs/ko/5x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate and use template engines like Pug, Handle
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ This approach makes it easier to design an HTML page.
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-To render template files, set the following [application setting properties](/4x/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
This defaults to the `views` directory in the application root directory.
@@ -19,9 +20,7 @@ To render template files, set the following [application setting properties](/4x
Then install the corresponding template engine npm package; for example to install Pug:
-```bash
-$ npm install pug --save
-```
+
Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
diff --git a/src/content/docs/ko/5x/guide/writing-middleware.mdx b/src/content/docs/ko/5x/guide/writing-middleware.mdx
index de62911dd9..4f58c9ec58 100644
--- a/src/content/docs/ko/5x/guide/writing-middleware.mdx
+++ b/src/content/docs/ko/5x/guide/writing-middleware.mdx
@@ -29,7 +29,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -40,6 +40,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Middleware function myLogger
Here is a simple example of a middleware function called "myLogger". This function just prints
@@ -65,7 +77,7 @@ but by convention it is always named "next". To avoid confusion, always use this
To load the middleware function, call `app.use()`, specifying the middleware function.
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -83,6 +95,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
@@ -105,7 +136,7 @@ const requestTime = function (req, res, next) {
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -125,6 +156,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
### Middleware function validateCookies
@@ -145,7 +197,7 @@ async function cookieValidator(cookies) {
Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -169,6 +221,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
@@ -187,9 +263,7 @@ For more information about Express middleware, see: [Using Express middleware](/
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
-File: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -198,10 +272,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
The middleware can now be used as shown below.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/ko/5x/starter/examples.mdx b/src/content/docs/ko/5x/starter/examples.mdx
index 69f410e908..385c0ef3b9 100644
--- a/src/content/docs/ko/5x/starter/examples.mdx
+++ b/src/content/docs/ko/5x/starter/examples.mdx
@@ -45,5 +45,4 @@ Expressjs project team.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
diff --git a/src/content/docs/ko/5x/starter/hello-world.mdx b/src/content/docs/ko/5x/starter/hello-world.mdx
index 629d697721..4c26ad0813 100644
--- a/src/content/docs/ko/5x/starter/hello-world.mdx
+++ b/src/content/docs/ko/5x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
diff --git a/src/content/docs/ko/5x/starter/installing.mdx b/src/content/docs/ko/5x/starter/installing.mdx
index f6dc8220d4..30424bae35 100644
--- a/src/content/docs/ko/5x/starter/installing.mdx
+++ b/src/content/docs/ko/5x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Learn how to install Express.js in your Node.js environment, includ
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Before you begin, make sure you have [Node.js](https://nodejs.org/) 18 or higher installed. Then, create a directory for your application and navigate into it.
@@ -15,9 +16,7 @@ cd myapp
Use the `npm init` command to create a `package.json` file for your application.
For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
This command prompts you for a number of things, such as the name and version of your application.
For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
@@ -30,12 +29,8 @@ Enter `app.js`, or whatever you want the name of the main file to be. If you wan
Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
-```bash
-npm install express
-```
+
To install Express temporarily and not add it to the dependencies list:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/ko/5x/starter/static-files.mdx b/src/content/docs/ko/5x/starter/static-files.mdx
index dbadee731a..15a901a994 100644
--- a/src/content/docs/ko/5x/starter/static-files.mdx
+++ b/src/content/docs/ko/5x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
@@ -56,7 +56,7 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/pt-br/4x/guide/behind-proxies.mdx b/src/content/docs/pt-br/4x/guide/behind-proxies.mdx
index 20c5dee06c..104b30d280 100644
--- a/src/content/docs/pt-br/4x/guide/behind-proxies.mdx
+++ b/src/content/docs/pt-br/4x/guide/behind-proxies.mdx
@@ -17,7 +17,7 @@ a combinação da configuração no Express corresponda a como o proxy reverso f
A configuração do aplicativo 'proxy confiável' pode ser definida para um dos valores listados na tabela a seguir.
-
+
| Digite | Valor |
diff --git a/src/content/docs/pt-br/4x/guide/error-handling.mdx b/src/content/docs/pt-br/4x/guide/error-handling.mdx
index d290d15cf8..3dd3ea3d1c 100644
--- a/src/content/docs/pt-br/4x/guide/error-handling.mdx
+++ b/src/content/docs/pt-br/4x/guide/error-handling.mdx
@@ -97,8 +97,8 @@ e passá-los para o Express. Se o bloco `tentar...catch`
fosse omitido, Express não pegaria o erro, uma vez que ele não faz parte do código de manipulador
síncrono.
-Use promessas para evitar a sobrecarga do bloco `tentar... capturar` ou ao usar funções
-que retornam promessas. Por exemplo:
+Você também pode usar uma cadeia de manipuladores para confiar em erro síncrono
+de recuperação, reduzindo o código assíncrono a algo trivial. Por exemplo:
```js
app.get('/', (req, res, next) => {
@@ -114,8 +114,7 @@ Since promises automatically catch both synchronous errors and rejected promises
you can simply provide `next` as the final catch handler and Express will catch errors,
because the catch handler is given the error as the first argument.
-Você também pode usar uma cadeia de manipuladores para confiar em erro síncrono
-de recuperação, reduzindo o código assíncrono a algo trivial. Por exemplo:
+Se você tiver um gerenciador de rotas com múltiplas funções de retorno de chamada, você pode usar o parâmetro `rota` para pular para o próximo manipulador de rota. Por exemplo:
```js
app.get('/', [
@@ -207,7 +206,7 @@ app.use((err, req, res, next) => {
Você define o middleware de erro duramente, depois de outro `app.use()` e roteia chamadas; por exemplo:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +222,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
As respostas de dentro de uma função middleware podem estar em qualquer formato, como uma página de erro HTML, uma mensagem simples ou uma string JSON.
Para fins de estrutura organizacional (e de nível superior), você pode definir
@@ -230,7 +245,7 @@ várias funções de middleware com manipulação de erros, tanto quanto você p
regulares. Por exemplo, para definir um manipulador de erro
para solicitações feitas usando `XHR` e aqueles sem:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +261,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
@@ -279,7 +310,7 @@ function errorHandler(err, req, res, next) {
}
```
-Se você tiver um gerenciador de rotas com múltiplas funções de retorno de chamada, você pode usar o parâmetro `rota` para pular para o próximo manipulador de rota. Por exemplo:
+If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. Por exemplo:
```js
app.get(
diff --git a/src/content/docs/pt-br/4x/guide/overriding-express-api.md b/src/content/docs/pt-br/4x/guide/overriding-express-api.md
index 9566d01dbf..8b1ef4d289 100644
--- a/src/content/docs/pt-br/4x/guide/overriding-express-api.md
+++ b/src/content/docs/pt-br/4x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Alterar os protótipos globais afetará todos os aplicativos do Express carregad
Você pode substituir a assinatura e o comportamento dos métodos existentes com o seu próprio, atribuindo uma função personalizada.
-A seguir é um exemplo de substituição do comportamento de [res.sendStatus](/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/pt-br/4x/guide/routing.mdx b/src/content/docs/pt-br/4x/guide/routing.mdx
index 72e47e9466..4fdc006e0f 100644
--- a/src/content/docs/pt-br/4x/guide/routing.mdx
+++ b/src/content/docs/pt-br/4x/guide/routing.mdx
@@ -9,11 +9,11 @@ _Routing_ refere-se a como os endpoints de um aplicativo (URIs) respondem às so
Para uma introdução ao roteamento, veja [Roteamento básico](/starter/basic-routing).
Você define roteamento usando métodos do objeto Express `app` que correspondem aos métodos HTTP;
-por exemplo, `app. et()` para lidar com solicitações GET e `app.post` para lidar com solicitações POST. Para obter uma lista completa,
-ver [app.METHOD](/api/application#appmethodpath-callback--callback-). Você também pode usar o [app.all()](/api/application#appallpath-callback--callback-) para lidar com todos os métodos HTTP e [app. se()](/api/application#appusepath-callback--callback) para
-especifique middleware como função de retorno de chamada (Veja [Usando middleware](/guide/using-middleware) para detalhes).
+por exemplo, `app. et()` para lidar com solicitações GET e `app.post` para lidar com solicitações POST. For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
+specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-Esses métodos de roteamento especificam uma função de callback (às vezes chamada de "funções de manipulador") chamada quando a aplicação recebe uma solicitação para a rota especificada (endpoint) e método HTTP. Em outras palavras, o aplicativo "listas" para solicitações que correspondem com a(s) rota(s) e método(s) especificado(s), e quando ela detecta uma correspondência, ela chama a função de retorno de chamada especificado.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. Em outras palavras, o aplicativo "listas" para solicitações que correspondem com a(s) rota(s) e método(s) especificado(s), e quando ela detecta uma correspondência, ela chama a função de retorno de chamada especificado.
Na verdade, os métodos de roteamento podem ter mais de uma função de callback como argumentos.
Com múltiplas funções de callback, é importante fornecer `next` como um argumento para a função de callback e então chamar `next()` dentro do corpo da função para liberar o controle
@@ -21,7 +21,7 @@ para a próxima callback.
O código a seguir é um exemplo de uma rota muito básica.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Métodos de rota
Um método de route é derivado de um dos métodos HTTP e é anexado a uma instância da classe 'express'.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Expresso suporta métodos que correspondem a todos os métodos de requisição HTTP: `get`, `post`, e assim por diante.
-Para uma lista completa, consulte [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
Há um método de roteamento especial, `app.all()`, usado para carregar funções de middleware em um caminho para os métodos de requisição HTTP. Por exemplo, o seguinte manipulador é executado para solicitações para a rota `"/secre"` usando `GET`, `POST`, `PUT`, `DELETE`, ou qualquer outro método de solicitação HTTP suportado no [módulo http](https://nodejs.org/api/http.html#http_http_methods).
@@ -212,7 +223,7 @@ com uma barra invertida adicional, por exemplo `\d+`.
-O caractere `*` em expressões regulares não é interpretado da maneira habitual. Como uma alternativa, use `{0,}` em vez de `*`.
+The [`*`](https://github.com/expressjs/express/issues/2495) character in regular expressions is not interpreted in the usual way. Como uma alternativa, use `{0,}` em vez de `*`.
## Manipuladores de rota
@@ -312,17 +323,17 @@ app.get(
Os métodos no objeto de resposta ('res') na tabela a seguir podem enviar uma resposta para o cliente e encerrar o ciclo de resposta de solicitação. Se nenhum destes métodos for chamado de um manipulador de redes, a solicitação do cliente será deixada em suspenso.
-| Método | Descrição: |
-| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Solicite que um arquivo seja baixado. |
-| [res.end()](/api/response#resenddata-encoding-callback) | Encerrar o processo de resposta. |
-| [res.json()](/api/response#resjsonbody) | Enviar uma resposta JSON. |
-| [res.jsonp()](/api/response#resjsonpbody) | Envie uma resposta JSON com suporte a JSONP. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirecionar uma requisição. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Renderizar um modelo de visão. |
-| [res.send()](/api/response#ressendbody) | Envie uma resposta de vários tipos. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Envia um arquivo como uma transmissão octet. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Defina o código de status da resposta e envie sua representação de string como o corpo da resposta. |
+| Método | Descrição: |
+| ----------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Solicite que um arquivo seja baixado. |
+| [res.end()](/api/response#resend) | Encerrar o processo de resposta. |
+| [res.json()](/api/response#resjson) | Enviar uma resposta JSON. |
+| [res.jsonp()](/api/response#resjsonp) | Envie uma resposta JSON com suporte a JSONP. |
+| [res.redirect()](/api/response#resredirect) | Redirecionar uma requisição. |
+| [res.render()](/api/response#resrender) | Renderizar um modelo de visão. |
+| [res.send()](/api/response#ressend) | Envie uma resposta de vários tipos. |
+| [res.sendFile()](/api/response#ressendfile) | Envia um arquivo como uma transmissão octet. |
+| [res.sendStatus()](/api/response#ressendstatus) | Defina o código de status da resposta e envie sua representação de string como o corpo da resposta. |
## app.route()
@@ -345,7 +356,7 @@ app
});
```
-## expressão.Roteador
+## express.Router
Use a classe 'express.Router' para criar módulo, manipuladores de rotas montáveis. Uma instância `Router` é um sistema completo de middleware e roteamento; por este motivo, é muitas vezes referido como um "mini-app".
@@ -353,7 +364,7 @@ O exemplo a seguir cria um roteador como um módulo, carrega uma função middle
Crie um arquivo de roteador chamado `birds.js` no diretório de aplicativos, com o seguinte conteúdo:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -376,9 +387,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Em seguida, carregue o módulo do roteador no aplicativo:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -386,9 +421,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
O aplicativo agora poderá lidar com pedidos para `/birds` e `/birds/about`, Além de chamar a função middleware `timeLog` que é específica da rota.
-Mas se a rota pai `/birds` tiver parâmetros de caminho, ela não será acessível por padrão nas sub-rotas. Para torná-lo acessível, você precisará passar a opção `mergeParams` para o construtor do roteador [reference](/api/application#appusepath-callback--callback).
+Mas se a rota pai `/birds` tiver parâmetros de caminho, ela não será acessível por padrão nas sub-rotas. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/pt-br/4x/guide/using-middleware.mdx b/src/content/docs/pt-br/4x/guide/using-middleware.mdx
index 13623d12d2..0a60894404 100644
--- a/src/content/docs/pt-br/4x/guide/using-middleware.mdx
+++ b/src/content/docs/pt-br/4x/guide/using-middleware.mdx
@@ -4,10 +4,11 @@ description: Aprenda a usar o middleware em aplicativos do Express.js, incluindo
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express é uma web framework de roteamento e middleware que tem a funcionalidade mínima de sua própria funcionalidade: Um aplicativo Express é essencialmente uma série de chamadas de função middleware.
-Middleware\_ são funções que têm acesso ao [objeto de requisição](/5x/api#req) (`req`), a [objeto de resposta](/5x/api#res) (`res`) e a próxima função de middleware no ciclo de resposta de solicitação do aplicativo. A próxima função de middleware é comumente denotada por uma variável chamada `next`.
+Middleware\_ são funções que têm acesso ao [objeto de requisição](/api#req) (`req`), a [objeto de resposta](/api#res) (`res`) e a próxima função de middleware no ciclo de resposta de solicitação do aplicativo. A próxima função de middleware é comumente denotada por uma variável chamada `next`.
As funções do Middleware podem executar as seguintes tarefas:
@@ -31,11 +32,11 @@ Você também pode carregar uma série de funções intermediárias juntas, o qu
## Midddleware no nível de aplicação
-Vincular aplicativo de nível middleware a uma instância do [objeto de aplicativo](/5x/api#app) usando o `app.use()` e `app. Funções ETHOD()`, onde `METHOD` é o método HTTP da solicitação que a função middleware lida (como GET, PUT, ou POST) em minúsculas.
+Vincular aplicativo de nível middleware a uma instância do [objeto de aplicativo](/api#app) usando o `app.use()` e `app. Funções ETHOD()`, onde `METHOD` é o método HTTP da solicitação que a função middleware lida (como GET, PUT, ou POST) em minúsculas.
Este exemplo mostra uma função middleware sem caminho de montagem. A função é executada toda vez que o aplicativo recebe uma solicitação.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
Este exemplo mostra uma função middleware montada no caminho `/user/:id`. A função é executada para qualquer tipo de solicitação HTTP
no caminho `/user/:id`.
@@ -167,7 +179,7 @@ Carregue o middleware no nível de roteador usando as funções `router.use()` e
O código a seguir replica o sistema middleware que é mostrado acima para o middleware no nível de aplicativos, usando o middleware no nível de roteador:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
Para ignorar o resto das funções de middleware do roteador, chame `next('router')`
para passar o controle de volta para fora da instância do roteador.
Este exemplo mostra uma sub-pilha de middleware que lida com requisições GET para o caminho `/user/:id`.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Midddleware com erro manipulado
@@ -271,9 +355,9 @@ funções que foram previamente incluídas com Express estão agora em módulos
O Express tem as seguintes funções de middleware incorporadas:
-- [express.static](/5x/api#express.static) serve como arquivos estáticos, como arquivos HTML, imagens e assim por diante.
-- [express.json](/5x/api#express.json) analisa solicitações recebidas com carga JSON. **NOTA: Disponível com Expresso 4.16.0+**
-- [express.urlencoded](/5x/api#express.urlencoded) analisa solicitações recebidas com payloads codificados por URL. **NOTA: Disponível com Expresso 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTA: Disponível com Expresso 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTA: Disponível com Expresso 4.16.0+**
## Midddleware de terceiros
@@ -283,11 +367,9 @@ Instale o módulo Node.js para a funcionalidade requerida e, em seguida, carregu
O exemplo a seguir ilustra a instalação e o carregamento da função middleware de análise de cookie-parser\`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
Para uma lista parcial de funções intermediárias de terceiros que são comumente usadas com Express, veja: [middleware de terceiros](/resources/middleware).
diff --git a/src/content/docs/pt-br/4x/guide/using-template-engines.mdx b/src/content/docs/pt-br/4x/guide/using-template-engines.mdx
index a117b7d495..4082c75bb7 100644
--- a/src/content/docs/pt-br/4x/guide/using-template-engines.mdx
+++ b/src/content/docs/pt-br/4x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Descubra como integrar e usar mecanismos de modelos como Pug, Handl
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Um _motor de template_ permite que você use arquivos de template estáticos na sua aplicação. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ Esta abordagem torna mais fácil projetar uma página HTML.
O [gerador de aplicação Expressa](/starter/generator) usa [Pug](https://pugjs.org/api/getting-started.html) como seu padrão, mas também apoia [Handlebars](https://www.npmjs.com/package/handlebars), e [EJS](https://www.npmjs.com/package/ejs), entre outros.
-Para renderizar arquivos de template, defina as seguintes [propriedades de configuração da aplicação](/api#app.set), no `app.js` padrão criado pelo gerador:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, o diretório onde se localizam os arquivos de template. Ex: `app.set('views', './views')`.
Isto é padrão para o diretório `views` no diretório raiz do aplicativo.
@@ -19,9 +20,7 @@ Para renderizar arquivos de template, defina as seguintes [propriedades de confi
Então instale o correspondente mecanismo de template do npm pacote; por exemplo, para instalar o Pug:
-```bash
-$ npm install pug --save
-```
+
Mecanismos de template compatíveis com o código, como Pug exporta uma função chamada `__express(filePath, opções, callback)`,
diff --git a/src/content/docs/pt-br/4x/guide/writing-middleware.mdx b/src/content/docs/pt-br/4x/guide/writing-middleware.mdx
index 6ab2ffa42e..83b3abfa53 100644
--- a/src/content/docs/pt-br/4x/guide/writing-middleware.mdx
+++ b/src/content/docs/pt-br/4x/guide/writing-middleware.mdx
@@ -5,7 +5,7 @@ description: Aprenda a escrever funções de middleware personalizadas para apli
import Alert from '@components/primitives/Alert/Alert.astro';
-Middleware\_ são funções que têm acesso ao [objeto de requisição](/5x/api#req) (`req`), a [objeto de resposta](/5x/api#res) (`res`) e a função `next` no ciclo de resposta de solicitação do aplicativo. A função `próxima` é uma função no roteador Expresso que, quando invocado, executa o intermediário sucedendo ao intermediário atual.
+Middleware\_ são funções que têm acesso ao [objeto de requisição](/api#req) (`req`), a [objeto de resposta](/api#res) (`res`) e a função `next` no ciclo de resposta de solicitação do aplicativo. A função `próxima` é uma função no roteador Expresso que, quando invocado, executa o intermediário sucedendo ao intermediário atual.
As funções do Middleware podem executar as seguintes tarefas:
@@ -40,11 +40,10 @@ A figura a seguir mostra os elementos de uma chamada de função middleware:
- HTTP resposta argumento para a função middleware, chamada de "res" pela
- convenção .
+ HTTP [response](/api/response) argument to the middleware function, called "res" by convention.
-HTTP request argumento para a função middleware, chamado de "req" pela convenção.
+HTTP [request](/api/request) argument to the middleware function, called "req" by convention.
@@ -59,7 +58,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -70,6 +69,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Função Middleware myLogger
Aqui está um exemplo simples de uma função de middleware chamada "myLogger". Essa função apenas imprime
@@ -95,7 +106,7 @@ mas por convenção é sempre chamada de "next". Para evitar confusões, utilize
Para carregar a função middleware, chame `app.use()`, especificando a função middleware.
Por exemplo, o código a seguir carrega a função `myLogger` middleware antes da rota para o caminho raiz (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -113,6 +124,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Toda vez que o aplicativo recebe uma solicitação, ele imprime a mensagem "LOGGED" no terminal.
A ordem do carregamento do middleware é importante: as funções de middleware que são carregadas primeiro também são executadas primeiro.
@@ -135,7 +165,7 @@ const requestTime = function (req, res, next) {
O aplicativo agora usa a função middleware `requestTime`. Além disso, a função de retorno de chamada da rota raiz usa a propriedade que a função middleware adiciona a `req` (o objeto de solicitação).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -155,6 +185,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
Quando você faz uma solicitação na raiz do aplicativo, o aplicativo agora mostra a marcação de hora da sua solicitação no navegador.
### Função Middleware validateCookies
@@ -173,9 +224,9 @@ async function cookieValidator(cookies) {
}
```
-Aqui, usamos o [`cookie-parser`](/resources/middleware/cookie-parser) middleware para analisar cookies recebidos do objeto `req` e passá-los para a nossa função `cookieValidator`. O middleware 'validateCookies' retorna a promessa de que, após a rejeição, irá automaticamente acionar o nosso manipulador de erros.
+O middleware 'validateCookies' retorna a promessa de que, após a rejeição, irá automaticamente acionar o nosso manipulador de erros. Aqui, usamos o [`cookie-parser`](/resources/middleware/cookie-parser) middleware para analisar cookies recebidos do objeto `req` e passá-los para a nossa função `cookieValidator`.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -199,6 +250,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Observe como `next()` é chamado depois `await cookieValidator(req.cookies)`. Isto garante que se
@@ -217,9 +292,7 @@ Para mais informações sobre Express middleware, veja: [Usando Express middlewa
Se precisar de seu middleware para ser configurável, exporte uma função que aceite um objeto de opções ou outros parâmetros, que então retorna a implementação intermediária com base nos parâmetros de entrada.
-Arquivo: `meu-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -228,10 +301,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
O middleware agora pode ser usado como mostrado abaixo.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/pt-br/4x/starter/examples.mdx b/src/content/docs/pt-br/4x/starter/examples.mdx
index ff0c62c56f..06ee16092f 100644
--- a/src/content/docs/pt-br/4x/starter/examples.mdx
+++ b/src/content/docs/pt-br/4x/starter/examples.mdx
@@ -41,5 +41,4 @@ Estes são alguns exemplos adicionais com integrações mais extensas.
Expressjs.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Aplicativo Fullstack com Express and Next.js usando [Prisma](https://www.npmjs.com/package/prisma) como ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - API REST com Express in TypeScript usando [Prisma](https://www.npmjs.com/package/prisma) como ORM
diff --git a/src/content/docs/pt-br/4x/starter/faq.md b/src/content/docs/pt-br/4x/starter/faq.md
index 3906d8ba23..2c6f49d5de 100644
--- a/src/content/docs/pt-br/4x/starter/faq.md
+++ b/src/content/docs/pt-br/4x/starter/faq.md
@@ -10,8 +10,8 @@ da escala do seu aplicativo e da equipe que está envolvida. Para ser o mais fle
flexível, Express não faz suposições em termos de estrutura.
Rotas e outras lógicas específicas do aplicativo podem viver em quantos arquivos
-você quiser, em qualquer estrutura de diretório que preferir. View the following
-examples for inspiration:
+você quiser, em qualquer estrutura de diretório que preferir. Veja os seguintes exemplos
+de inspiração:
- [Lista de rotas](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
- [Mapa de rotas](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
@@ -23,9 +23,9 @@ Além disso, existem extensões para o Express, que simplificam alguns desses pa
## Como faço para definir modelos?
-Expresso não tem noção de um banco de dados. This concept is
-left up to third-party Node modules, allowing you to
-interface with nearly any database.
+Expresso não tem noção de um banco de dados. Este conceito é
+deixado para módulos de Nó de terceiros, permitindo a você
+interface com quase qualquer banco de dados.
Veja [LoopBack](http://loopback.io) para um framework baseado em Express que é centralizado em torno de modelos.
diff --git a/src/content/docs/pt-br/4x/starter/hello-world.mdx b/src/content/docs/pt-br/4x/starter/hello-world.mdx
index 9d04256d65..8eef8f5e61 100644
--- a/src/content/docs/pt-br/4x/starter/hello-world.mdx
+++ b/src/content/docs/pt-br/4x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ para vários fins.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
Este aplicativo inicia um servidor e escuta na porta 3000 para conexões. O aplicativo responde com "Olá Mundo!" para solicitações
para a URL raiz (`/`) ou _route_. Para todos os outros caminhos, responderá com um **404 Não Encontrado**.
diff --git a/src/content/docs/pt-br/4x/starter/installing.mdx b/src/content/docs/pt-br/4x/starter/installing.mdx
index d37d8f5e6a..9e4403a458 100644
--- a/src/content/docs/pt-br/4x/starter/installing.mdx
+++ b/src/content/docs/pt-br/4x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Aprenda a instalar o Express.js no seu ambiente Node.js, incluindo
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Antes de começar, certifique-se de ter [Node.js](https://nodejs.org/) 0.10 ou superior instalado. Em seguida, crie um diretório para a sua aplicação e navegue até ele.
@@ -15,9 +16,7 @@ cd myapp
Use o comando `npm init` para criar um arquivo `package.json` para sua aplicação.
Para obter mais informações sobre como funciona o arquivo `package.json`, veja [Especificações da manipulação do package.json do npm](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
Este comando avisa você para várias coisas, como o nome e a versão de seu aplicativo.
Por enquanto, você simplesmente pode clicar em RETURN para aceitar os padrões para a maioria deles, com a seguinte exceção:
@@ -30,15 +29,11 @@ Digite `app.js`, ou o que quiser que o nome do arquivo principal seja. Se você
Agora, instale o Express no diretório `myapp` e salve-o na lista de dependências. Por exemplo:
-```bash
-npm install express
-```
+
Para instalar o Express temporariamente e não adicioná-lo à lista de dependências:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/pt-br/4x/starter/static-files.mdx b/src/content/docs/pt-br/4x/starter/static-files.mdx
index a0303d6fb1..ccbcc4619c 100644
--- a/src/content/docs/pt-br/4x/starter/static-files.mdx
+++ b/src/content/docs/pt-br/4x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
O argumento `root` especifica o diretório raiz do qual se destinam os assets estáticos.
-Para obter mais informações sobre o argumento `options`, consulte [express.static](/5x/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
Por exemplo, use o seguinte código para servir imagens, arquivos CSS e arquivos JavaScript em um diretório chamado `public`:
@@ -56,7 +56,7 @@ servindo ativos estáticos.
-Para criar um prefixo de caminho virtual (onde o caminho não existe realmente no sistema de arquivos) para arquivos que são servidos pelo `express. função tática`, [especifique um caminho de montagem](/5x/api#app.use) para o diretório estático, conforme mostrado abaixo:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
No entanto, o caminho que você fornece para a função `express.static` é relativo ao diretório de onde você inicia seu processo `node`. Se você executar o aplicativo expresso a partir de outro diretório, é mais seguro usar o caminho absoluto do diretório que você deseja servir:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
Para mais detalhes sobre a função `serve-static` e suas opções, consulte [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/pt-br/5x/guide/behind-proxies.mdx b/src/content/docs/pt-br/5x/guide/behind-proxies.mdx
index 20c5dee06c..104b30d280 100644
--- a/src/content/docs/pt-br/5x/guide/behind-proxies.mdx
+++ b/src/content/docs/pt-br/5x/guide/behind-proxies.mdx
@@ -17,7 +17,7 @@ a combinação da configuração no Express corresponda a como o proxy reverso f
A configuração do aplicativo 'proxy confiável' pode ser definida para um dos valores listados na tabela a seguir.
-
+
| Digite | Valor |
diff --git a/src/content/docs/pt-br/5x/guide/error-handling.mdx b/src/content/docs/pt-br/5x/guide/error-handling.mdx
index d290d15cf8..3dd3ea3d1c 100644
--- a/src/content/docs/pt-br/5x/guide/error-handling.mdx
+++ b/src/content/docs/pt-br/5x/guide/error-handling.mdx
@@ -97,8 +97,8 @@ e passá-los para o Express. Se o bloco `tentar...catch`
fosse omitido, Express não pegaria o erro, uma vez que ele não faz parte do código de manipulador
síncrono.
-Use promessas para evitar a sobrecarga do bloco `tentar... capturar` ou ao usar funções
-que retornam promessas. Por exemplo:
+Você também pode usar uma cadeia de manipuladores para confiar em erro síncrono
+de recuperação, reduzindo o código assíncrono a algo trivial. Por exemplo:
```js
app.get('/', (req, res, next) => {
@@ -114,8 +114,7 @@ Since promises automatically catch both synchronous errors and rejected promises
you can simply provide `next` as the final catch handler and Express will catch errors,
because the catch handler is given the error as the first argument.
-Você também pode usar uma cadeia de manipuladores para confiar em erro síncrono
-de recuperação, reduzindo o código assíncrono a algo trivial. Por exemplo:
+Se você tiver um gerenciador de rotas com múltiplas funções de retorno de chamada, você pode usar o parâmetro `rota` para pular para o próximo manipulador de rota. Por exemplo:
```js
app.get('/', [
@@ -207,7 +206,7 @@ app.use((err, req, res, next) => {
Você define o middleware de erro duramente, depois de outro `app.use()` e roteia chamadas; por exemplo:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +222,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
As respostas de dentro de uma função middleware podem estar em qualquer formato, como uma página de erro HTML, uma mensagem simples ou uma string JSON.
Para fins de estrutura organizacional (e de nível superior), você pode definir
@@ -230,7 +245,7 @@ várias funções de middleware com manipulação de erros, tanto quanto você p
regulares. Por exemplo, para definir um manipulador de erro
para solicitações feitas usando `XHR` e aqueles sem:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +261,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
@@ -279,7 +310,7 @@ function errorHandler(err, req, res, next) {
}
```
-Se você tiver um gerenciador de rotas com múltiplas funções de retorno de chamada, você pode usar o parâmetro `rota` para pular para o próximo manipulador de rota. Por exemplo:
+If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. Por exemplo:
```js
app.get(
diff --git a/src/content/docs/pt-br/5x/guide/overriding-express-api.md b/src/content/docs/pt-br/5x/guide/overriding-express-api.md
index 8372f1c98f..8b1ef4d289 100644
--- a/src/content/docs/pt-br/5x/guide/overriding-express-api.md
+++ b/src/content/docs/pt-br/5x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Alterar os protótipos globais afetará todos os aplicativos do Express carregad
Você pode substituir a assinatura e o comportamento dos métodos existentes com o seu próprio, atribuindo uma função personalizada.
-A seguir é um exemplo de substituição do comportamento de [res.sendStatus](/4x/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/pt-br/5x/guide/routing.mdx b/src/content/docs/pt-br/5x/guide/routing.mdx
index 541ca9721d..d487d75cff 100644
--- a/src/content/docs/pt-br/5x/guide/routing.mdx
+++ b/src/content/docs/pt-br/5x/guide/routing.mdx
@@ -9,11 +9,11 @@ _Routing_ refere-se a como os endpoints de um aplicativo (URIs) respondem às so
Para uma introdução ao roteamento, veja [Roteamento básico](/starter/basic-routing).
Você define roteamento usando métodos do objeto Express `app` que correspondem aos métodos HTTP;
-por exemplo, `app. et()` para lidar com solicitações GET e `app.post` para lidar com solicitações POST. Para obter uma lista completa,
-ver [app.METHOD](/api/application#appmethodpath-callback--callback-). Você também pode usar o [app.all()](/api/application#appallpath-callback--callback-) para lidar com todos os métodos HTTP e [app. se()](/api/application#appusepath-callback--callback) para
-especifique middleware como função de retorno de chamada (Veja [Usando middleware](/guide/using-middleware) para detalhes).
+por exemplo, `app. et()` para lidar com solicitações GET e `app.post` para lidar com solicitações POST. For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
+specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-Esses métodos de roteamento especificam uma função de callback (às vezes chamada de "funções de manipulador") chamada quando a aplicação recebe uma solicitação para a rota especificada (endpoint) e método HTTP. Em outras palavras, o aplicativo "listas" para solicitações que correspondem com a(s) rota(s) e método(s) especificado(s), e quando ela detecta uma correspondência, ela chama a função de retorno de chamada especificado.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. Em outras palavras, o aplicativo "listas" para solicitações que correspondem com a(s) rota(s) e método(s) especificado(s), e quando ela detecta uma correspondência, ela chama a função de retorno de chamada especificado.
Na verdade, os métodos de roteamento podem ter mais de uma função de callback como argumentos.
Com múltiplas funções de callback, é importante fornecer `next` como um argumento para a função de callback e então chamar `next()` dentro do corpo da função para liberar o controle
@@ -21,7 +21,7 @@ para a próxima callback.
O código a seguir é um exemplo de uma rota muito básica.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Métodos de rota
Um método de route é derivado de um dos métodos HTTP e é anexado a uma instância da classe 'express'.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Expresso suporta métodos que correspondem a todos os métodos de requisição HTTP: `get`, `post`, e assim por diante.
-Para uma lista completa, consulte [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
Há um método de roteamento especial, `app.all()`, usado para carregar funções de middleware em um caminho para os métodos de requisição HTTP. Por exemplo, o seguinte manipulador é executado para solicitações para a rota `"/secre"` usando `GET`, `POST`, `PUT`, `DELETE`, ou qualquer outro método de solicitação HTTP suportado no [módulo http](https://nodejs.org/api/http.html#http_http_methods).
@@ -92,7 +103,7 @@ app.get('/random.text', (req, res) => {
});
```
-### Caracteres curinga
+### Wildcards
Caracteres curinga correspondem a qualquer caminho após um prefixo. Eles devem ter um nome, assim como os parâmetros de rota, e são capturados como matrizes dos segmentos de caminho.
@@ -292,17 +303,17 @@ app.get(
Os métodos no objeto de resposta ('res') na tabela a seguir podem enviar uma resposta para o cliente e encerrar o ciclo de resposta de solicitação. Se nenhum destes métodos for chamado de um manipulador de redes, a solicitação do cliente será deixada em suspenso.
-| Método | Descrição: |
-| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Solicite que um arquivo seja baixado. |
-| [res.end()](/api/response#resenddata-encoding-callback) | Encerrar o processo de resposta. |
-| [res.json()](/api/response#resjsonbody) | Enviar uma resposta JSON. |
-| [res.jsonp()](/api/response#resjsonpbody) | Envie uma resposta JSON com suporte a JSONP. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirecionar uma requisição. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Renderizar um modelo de visão. |
-| [res.send()](/api/response#ressendbody) | Envie uma resposta de vários tipos. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Envia um arquivo como uma transmissão octet. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Defina o código de status da resposta e envie sua representação de string como o corpo da resposta. |
+| Método | Descrição: |
+| ----------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Solicite que um arquivo seja baixado. |
+| [res.end()](/api/response#resend) | Encerrar o processo de resposta. |
+| [res.json()](/api/response#resjson) | Enviar uma resposta JSON. |
+| [res.jsonp()](/api/response#resjsonp) | Envie uma resposta JSON com suporte a JSONP. |
+| [res.redirect()](/api/response#resredirect) | Redirecionar uma requisição. |
+| [res.render()](/api/response#resrender) | Renderizar um modelo de visão. |
+| [res.send()](/api/response#ressend) | Envie uma resposta de vários tipos. |
+| [res.sendFile()](/api/response#ressendfile) | Envia um arquivo como uma transmissão octet. |
+| [res.sendStatus()](/api/response#ressendstatus) | Defina o código de status da resposta e envie sua representação de string como o corpo da resposta. |
## app.route()
@@ -325,7 +336,7 @@ app
});
```
-## expressão.Roteador
+## express.Router
Use a classe 'express.Router' para criar módulo, manipuladores de rotas montáveis. Uma instância `Router` é um sistema completo de middleware e roteamento; por este motivo, é muitas vezes referido como um "mini-app".
@@ -333,7 +344,7 @@ O exemplo a seguir cria um roteador como um módulo, carrega uma função middle
Crie um arquivo de roteador chamado `birds.js` no diretório de aplicativos, com o seguinte conteúdo:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -356,9 +367,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Em seguida, carregue o módulo do roteador no aplicativo:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -366,9 +401,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
O aplicativo agora poderá lidar com pedidos para `/birds` e `/birds/about`, Além de chamar a função middleware `timeLog` que é específica da rota.
-Mas se a rota pai `/birds` tiver parâmetros de caminho, ela não será acessível por padrão nas sub-rotas. Para torná-lo acessível, você precisará passar a opção `mergeParams` para o construtor do roteador [reference](/api/application#appusepath-callback--callback).
+Mas se a rota pai `/birds` tiver parâmetros de caminho, ela não será acessível por padrão nas sub-rotas. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/pt-br/5x/guide/using-middleware.mdx b/src/content/docs/pt-br/5x/guide/using-middleware.mdx
index 286690492d..0a60894404 100644
--- a/src/content/docs/pt-br/5x/guide/using-middleware.mdx
+++ b/src/content/docs/pt-br/5x/guide/using-middleware.mdx
@@ -4,6 +4,7 @@ description: Aprenda a usar o middleware em aplicativos do Express.js, incluindo
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express é uma web framework de roteamento e middleware que tem a funcionalidade mínima de sua própria funcionalidade: Um aplicativo Express é essencialmente uma série de chamadas de função middleware.
@@ -35,7 +36,7 @@ Vincular aplicativo de nível middleware a uma instância do [objeto de aplicati
Este exemplo mostra uma função middleware sem caminho de montagem. A função é executada toda vez que o aplicativo recebe uma solicitação.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
Este exemplo mostra uma função middleware montada no caminho `/user/:id`. A função é executada para qualquer tipo de solicitação HTTP
no caminho `/user/:id`.
@@ -167,7 +179,7 @@ Carregue o middleware no nível de roteador usando as funções `router.use()` e
O código a seguir replica o sistema middleware que é mostrado acima para o middleware no nível de aplicativos, usando o middleware no nível de roteador:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
Para ignorar o resto das funções de middleware do roteador, chame `next('router')`
para passar o controle de volta para fora da instância do roteador.
Este exemplo mostra uma sub-pilha de middleware que lida com requisições GET para o caminho `/user/:id`.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Midddleware com erro manipulado
@@ -271,9 +355,9 @@ funções que foram previamente incluídas com Express estão agora em módulos
O Express tem as seguintes funções de middleware incorporadas:
-- [express.static](/api#express.static) serve como arquivos estáticos, como arquivos HTML, imagens e assim por diante.
-- [express.json](/api#express.json) analisa solicitações recebidas com carga JSON. **NOTA: Disponível com Expresso 4.16.0+**
-- [express.urlencoded](/api#express.urlencoded) analisa solicitações recebidas com payloads codificados por URL. **NOTA: Disponível com Expresso 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTA: Disponível com Expresso 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTA: Disponível com Expresso 4.16.0+**
## Midddleware de terceiros
@@ -283,11 +367,9 @@ Instale o módulo Node.js para a funcionalidade requerida e, em seguida, carregu
O exemplo a seguir ilustra a instalação e o carregamento da função middleware de análise de cookie-parser\`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
Para uma lista parcial de funções intermediárias de terceiros que são comumente usadas com Express, veja: [middleware de terceiros](/resources/middleware).
diff --git a/src/content/docs/pt-br/5x/guide/using-template-engines.mdx b/src/content/docs/pt-br/5x/guide/using-template-engines.mdx
index 463772e308..4082c75bb7 100644
--- a/src/content/docs/pt-br/5x/guide/using-template-engines.mdx
+++ b/src/content/docs/pt-br/5x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Descubra como integrar e usar mecanismos de modelos como Pug, Handl
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Um _motor de template_ permite que você use arquivos de template estáticos na sua aplicação. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ Esta abordagem torna mais fácil projetar uma página HTML.
O [gerador de aplicação Expressa](/starter/generator) usa [Pug](https://pugjs.org/api/getting-started.html) como seu padrão, mas também apoia [Handlebars](https://www.npmjs.com/package/handlebars), e [EJS](https://www.npmjs.com/package/ejs), entre outros.
-Para renderizar arquivos de template, defina as seguintes [propriedades de configuração da aplicação](/4x/api#app.set), no `app.js` padrão criado pelo gerador:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, o diretório onde se localizam os arquivos de template. Ex: `app.set('views', './views')`.
Isto é padrão para o diretório `views` no diretório raiz do aplicativo.
@@ -19,9 +20,7 @@ Para renderizar arquivos de template, defina as seguintes [propriedades de confi
Então instale o correspondente mecanismo de template do npm pacote; por exemplo, para instalar o Pug:
-```bash
-$ npm install pug --save
-```
+
Mecanismos de template compatíveis com o código, como Pug exporta uma função chamada `__express(filePath, opções, callback)`,
diff --git a/src/content/docs/pt-br/5x/guide/writing-middleware.mdx b/src/content/docs/pt-br/5x/guide/writing-middleware.mdx
index 346d49616c..b9babd9ef6 100644
--- a/src/content/docs/pt-br/5x/guide/writing-middleware.mdx
+++ b/src/content/docs/pt-br/5x/guide/writing-middleware.mdx
@@ -29,7 +29,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -40,6 +40,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Função Middleware myLogger
Aqui está um exemplo simples de uma função de middleware chamada "myLogger". Essa função apenas imprime
@@ -65,7 +77,7 @@ mas por convenção é sempre chamada de "next". Para evitar confusões, utilize
Para carregar a função middleware, chame `app.use()`, especificando a função middleware.
Por exemplo, o código a seguir carrega a função `myLogger` middleware antes da rota para o caminho raiz (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -83,6 +95,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Toda vez que o aplicativo recebe uma solicitação, ele imprime a mensagem "LOGGED" no terminal.
A ordem do carregamento do middleware é importante: as funções de middleware que são carregadas primeiro também são executadas primeiro.
@@ -105,7 +136,7 @@ const requestTime = function (req, res, next) {
O aplicativo agora usa a função middleware `requestTime`. Além disso, a função de retorno de chamada da rota raiz usa a propriedade que a função middleware adiciona a `req` (o objeto de solicitação).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -125,6 +156,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
Quando você faz uma solicitação na raiz do aplicativo, o aplicativo agora mostra a marcação de hora da sua solicitação no navegador.
### Função Middleware validateCookies
@@ -143,9 +195,9 @@ async function cookieValidator(cookies) {
}
```
-Aqui, usamos o [`cookie-parser`](/resources/middleware/cookie-parser) middleware para analisar cookies recebidos do objeto `req` e passá-los para a nossa função `cookieValidator`. O middleware 'validateCookies' retorna a promessa de que, após a rejeição, irá automaticamente acionar o nosso manipulador de erros.
+O middleware 'validateCookies' retorna a promessa de que, após a rejeição, irá automaticamente acionar o nosso manipulador de erros. Aqui, usamos o [`cookie-parser`](/resources/middleware/cookie-parser) middleware para analisar cookies recebidos do objeto `req` e passá-los para a nossa função `cookieValidator`.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -169,6 +221,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Observe como `next()` é chamado depois `await cookieValidator(req.cookies)`. Isto garante que se
@@ -187,9 +263,7 @@ Para mais informações sobre Express middleware, veja: [Usando Express middlewa
Se precisar de seu middleware para ser configurável, exporte uma função que aceite um objeto de opções ou outros parâmetros, que então retorna a implementação intermediária com base nos parâmetros de entrada.
-Arquivo: `meu-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -198,10 +272,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
O middleware agora pode ser usado como mostrado abaixo.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/pt-br/5x/starter/examples.mdx b/src/content/docs/pt-br/5x/starter/examples.mdx
index d7c62b03ab..1a16d43692 100644
--- a/src/content/docs/pt-br/5x/starter/examples.mdx
+++ b/src/content/docs/pt-br/5x/starter/examples.mdx
@@ -45,5 +45,4 @@ Expressjs.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Aplicativo Fullstack com Express and Next.js usando [Prisma](https://www.npmjs.com/package/prisma) como ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - API REST com Express in TypeScript usando [Prisma](https://www.npmjs.com/package/prisma) como ORM
diff --git a/src/content/docs/pt-br/5x/starter/faq.md b/src/content/docs/pt-br/5x/starter/faq.md
index 6b47dae605..b21d1ca0d3 100644
--- a/src/content/docs/pt-br/5x/starter/faq.md
+++ b/src/content/docs/pt-br/5x/starter/faq.md
@@ -10,8 +10,8 @@ da escala do seu aplicativo e da equipe que está envolvida. Para ser o mais fle
flexível, Express não faz suposições em termos de estrutura.
Rotas e outras lógicas específicas do aplicativo podem viver em quantos arquivos
-você quiser, em qualquer estrutura de diretório que preferir. View the following
-examples for inspiration:
+você quiser, em qualquer estrutura de diretório que preferir. Veja os seguintes exemplos
+de inspiração:
- [Lista de rotas](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
- [Mapa de rotas](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
@@ -23,9 +23,9 @@ Além disso, existem extensões para o Express, que simplificam alguns desses pa
## Como faço para definir modelos?
-Expresso não tem noção de um banco de dados. This concept is
-left up to third-party Node modules, allowing you to
-interface with nearly any database.
+Expresso não tem noção de um banco de dados. Este conceito é
+deixado para módulos de Nó de terceiros, permitindo a você
+interface com quase qualquer banco de dados.
Veja [LoopBack](http://loopback.io) para um framework baseado em Express que é centralizado em torno de modelos.
diff --git a/src/content/docs/pt-br/5x/starter/hello-world.mdx b/src/content/docs/pt-br/5x/starter/hello-world.mdx
index 9d04256d65..8eef8f5e61 100644
--- a/src/content/docs/pt-br/5x/starter/hello-world.mdx
+++ b/src/content/docs/pt-br/5x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ para vários fins.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
Este aplicativo inicia um servidor e escuta na porta 3000 para conexões. O aplicativo responde com "Olá Mundo!" para solicitações
para a URL raiz (`/`) ou _route_. Para todos os outros caminhos, responderá com um **404 Não Encontrado**.
diff --git a/src/content/docs/pt-br/5x/starter/installing.mdx b/src/content/docs/pt-br/5x/starter/installing.mdx
index c86d5c60f3..f1de8a51bc 100644
--- a/src/content/docs/pt-br/5x/starter/installing.mdx
+++ b/src/content/docs/pt-br/5x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Aprenda a instalar o Express.js no seu ambiente Node.js, incluindo
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Antes de começar, certifique-se de ter [Node.js](https://nodejs.org/) 18 ou superior instalado. Em seguida, crie um diretório para a sua aplicação e navegue até ele.
@@ -15,9 +16,7 @@ cd myapp
Use o comando `npm init` para criar um arquivo `package.json` para sua aplicação.
Para obter mais informações sobre como funciona o arquivo `package.json`, veja [Especificações da manipulação do package.json do npm](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
Este comando avisa você para várias coisas, como o nome e a versão de seu aplicativo.
Por enquanto, você simplesmente pode clicar em RETURN para aceitar os padrões para a maioria deles, com a seguinte exceção:
@@ -30,12 +29,8 @@ Digite `app.js`, ou o que quiser que o nome do arquivo principal seja. Se você
Agora, instale o Express no diretório `myapp` e salve-o na lista de dependências. Por exemplo:
-```bash
-npm install express
-```
+
Para instalar o Express temporariamente e não adicioná-lo à lista de dependências:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/pt-br/5x/starter/static-files.mdx b/src/content/docs/pt-br/5x/starter/static-files.mdx
index 83d9b9753a..ccbcc4619c 100644
--- a/src/content/docs/pt-br/5x/starter/static-files.mdx
+++ b/src/content/docs/pt-br/5x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
O argumento `root` especifica o diretório raiz do qual se destinam os assets estáticos.
-Para obter mais informações sobre o argumento `options`, consulte [express.static](/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
Por exemplo, use o seguinte código para servir imagens, arquivos CSS e arquivos JavaScript em um diretório chamado `public`:
@@ -56,7 +56,7 @@ servindo ativos estáticos.
-Para criar um prefixo de caminho virtual (onde o caminho não existe realmente no sistema de arquivos) para arquivos que são servidos pelo `express. função tática`, [especifique um caminho de montagem](/api#app.use) para o diretório estático, conforme mostrado abaixo:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
No entanto, o caminho que você fornece para a função `express.static` é relativo ao diretório de onde você inicia seu processo `node`. Se você executar o aplicativo expresso a partir de outro diretório, é mais seguro usar o caminho absoluto do diretório que você deseja servir:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
Para mais detalhes sobre a função `serve-static` e suas opções, consulte [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/zh-cn/4x/advanced/developing-template-engines.md b/src/content/docs/zh-cn/4x/advanced/developing-template-engines.md
index 6e9710fbc5..e5d2858638 100644
--- a/src/content/docs/zh-cn/4x/advanced/developing-template-engines.md
+++ b/src/content/docs/zh-cn/4x/advanced/developing-template-engines.md
@@ -1,11 +1,11 @@
---
-title: Developing template engines for Express
-description: Learn how to develop custom template engines for Express.js using app.engine(), with examples on creating and integrating your own template rendering logic.
+title: 为 Express 开发模板引擎
+description: 学习如何使用 app.engine() 为 Express.js 开发自定义模板引擎,并通过示例讲解如何创建和集成自定义模板渲染逻辑。
---
-Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.
+使用 `app.engine(ext, callback)` 方法创建自定义模板引擎。 `ext` 表示文件扩展名,`callback` 是模板引擎函数,它接收以下参数:文件路径、选项对象以及回调函数。
-The following code is an example of implementing a very simple template engine for rendering `.ntl` files.
+以下代码示例实现了一个极简的模板引擎,用于渲染 `.ntl` 文件。
```js
const fs = require('fs'); // this engine requires the fs module
@@ -25,14 +25,14 @@ app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine
```
-Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content.
+你的应用现在将能够渲染 `.ntl` 文件。 在 `views` 目录中创建一个名为 `index.ntl` 的文件,并写入以下内容。
```pug
#title#
#message#
```
-Then, create the following route in your app.
+然后在你的应用中创建如下路由。
```js
app.get('/', (req, res) => {
@@ -40,4 +40,4 @@ app.get('/', (req, res) => {
});
```
-When you make a request to the home page, `index.ntl` will be rendered as HTML.
+当你向主页发起请求时,`index.ntl` 文件会被渲染为 HTML。
diff --git a/src/content/docs/zh-cn/4x/guide/behind-proxies.mdx b/src/content/docs/zh-cn/4x/guide/behind-proxies.mdx
index 86568424e4..b86d705e8e 100644
--- a/src/content/docs/zh-cn/4x/guide/behind-proxies.mdx
+++ b/src/content/docs/zh-cn/4x/guide/behind-proxies.mdx
@@ -1,21 +1,19 @@
---
-title: Express behind proxies
-description: Learn how to configure Express.js applications to work correctly behind reverse proxies, including using the trust proxy setting to handle client IP addresses.
+title: 运行在反向代理后的 Express 应用
+description: 学习如何配置 Express.js 应用使其在反向代理后正常工作,包括使用 **trust proxy** 设置来获取客户端真实 IP 地址。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client's IP address may instead show an internal IP address of the reverse proxy.
+在反向代理后运行 Express 应用时,部分 Express API 的返回值可能与预期不符。 为此可配置应用设置项 `trust proxy` ,让 Express 接口能够获取反向代理转发的请求信息。 最常见的问题是,用于获取客户端IP的Express接口,获取到的IP实为反向代理的内网地址。
-When configuring the `trust proxy` setting, it is important to understand the exact setup of the
-reverse proxy. Since this setting will trust values provided in the request, it is important that
-the combination of the setting in Express matches how the reverse proxy operates.
+配置`trust proxy`设置时,务必清楚反向代理的具体部署架构。 由于该配置会信任请求中携带的参数值,因此Express中的配置必须与反向代理的运行方式完全匹配,这一点至关重要。
-The application setting `trust proxy` may be set to one of the values listed in the following table.
+应用设置项 `trust proxy` 可设置为下表所列值之一。
| Type | Value |
@@ -23,25 +21,25 @@ The application setting `trust proxy` may be set to one of the values listed in
| Boolean |
-If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-For` header.
+若设为 `true`,客户端IP地址将被认定为`X-Forwarded-For`请求头中最左侧的条目。
-If `false`, the app is understood as directly facing the client and the client's IP address is derived from `req.socket.remoteAddress`. This is the default setting.
+若设为 `false`,表示应用直接面向客户端,客户端IP地址取自 `req.socket.remoteAddress`。 该值为默认配置。
-
-When setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`, otherwise it may be possible for the client to provide any value.
+
+将此项设为 `true` 时,务必确保最后一级受信反向代理会**移除/覆盖**以下所有HTTP请求头:`X-Forwarded-For`、`X-Forwarded-Host` 和 `X-Forwarded-Proto`,否则客户端可能伪造任意值。
|
| IP addresses |
-An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:
+可配置为一个IP地址、一个子网,或由多个IP地址和子网组成的数组,用于指定可信任的反向代理。 以下列表展示了预配置的子网名称:
- loopback - `127.0.0.1/8`, `::1/128`
- linklocal - `169.254.0.0/16`, `fe80::/10`
- uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
-You can set IP addresses in any of the following ways:
+你可通过以下任意方式设置IP地址:
```js
app.set('trust proxy', 'loopback'); // specify a single subnet
@@ -50,24 +48,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal'); // specify multiple
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); // specify multiple subnets as an array
```
-When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address.
+指定后,这些IP地址或子网将被排除在地址判定流程之外,最靠近应用服务器的非受信IP将被认定为客户端IP地址。 其工作原理是检查 `req.socket.remoteAddress` 是否为可信任地址。 若为可信地址,则从右向左检查`X-Forwarded-For`中的每个地址,直至找到第一个非可信地址。
|
| Number |
-Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy.
+使用距离 Express 应用不超过 n 个网络跳数的地址。 `req.socket.remoteAddress` 为第一跳,其余地址从`X-Forwarded-For`请求头中从右向左查找。 取值为 `0` 表示:第一个非可信地址就是 `req.socket.remoteAddress`,即不存在反向代理。
-
-When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value.
+
+使用该配置时,必须确保不存在多条长度不同的路径到达 Express 应用,避免客户端与服务的跳数少于配置值,否则客户端可能伪造任意值。
|
| Function |
-Custom trust implementation.
+自定义信任实现。
```js
app.set('trust proxy', (ip) => {
@@ -82,7 +80,7 @@ app.set('trust proxy', (ip) => {
|
-Enabling `trust proxy` will have the following impact:
+启用 `trust proxy` 会产生以下影响:
-
@@ -90,8 +88,8 @@ Enabling `trust proxy` will have the following impact:
`X-Forwarded-Host` header, which can be set by the client or by the proxy.
-
- `X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or
- `http` or even an invalid name. This value is reflected by [req.protocol](/api#req.protocol).
+ 反向代理可通过设置`X-Forwarded-Proto`请求头,告知应用当前请求协议是`https`、`http`,或是非法协议标识。
+ This value is reflected by [req.protocol](/api#req.protocol).
-
The [req.ip](/api#req.ip) and [req.ips](/api#req.ips) values are populated based on the socket
@@ -99,4 +97,4 @@ Enabling `trust proxy` will have the following impact:
-The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
+`trust proxy` 配置项依托[proxy-addr](https://www.npmjs.com/package/proxy-addr)包实现。 更多详情请参阅该模块文档。
diff --git a/src/content/docs/zh-cn/4x/guide/debugging.mdx b/src/content/docs/zh-cn/4x/guide/debugging.mdx
index 24bbce3510..beb9dc3f3b 100644
--- a/src/content/docs/zh-cn/4x/guide/debugging.mdx
+++ b/src/content/docs/zh-cn/4x/guide/debugging.mdx
@@ -1,18 +1,17 @@
---
-title: Debugging Express
-description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting.
+title: 调试 Express
+description: 通过设置 DEBUG 环境变量来开启并使用 Express.js 应用的调试日志,以便更好地排查问题。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-To see all the internal logs used in Express, set the `DEBUG` environment variable to
-`express:*` when launching your app.
+若要查看 Express 中使用的所有内部日志,请在启动应用时将 `DEBUG` 环境变量设置为 `express:*`。
```bash
$ DEBUG=express:* node index.js
```
-On Windows, use the corresponding command.
+在 Windows 系统上,请使用对应的命令。
```bash
> $env:DEBUG = "express:*"; node index.js
@@ -64,7 +63,7 @@ $ DEBUG=express:* node ./bin/www
express:router:layer new / +0ms
```
-When a request is then made to the app, you will see the logs specified in the Express code:
+随后向该应用发送请求时,你会看到 Express 代码中指定的日志:
```bash
express:router dispatching GET / +4h
@@ -84,40 +83,39 @@ When a request is then made to the app, you will see the logs specified in the E
express:view render "/projects/example/views/index.pug" +1ms
```
-To see the logs only from the router implementation, set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on.
+若仅查看来自路由实现的日志,请将 `DEBUG` 的值设置为 `express:router`。 同理,若仅查看来自应用实现的日志,请将 `DEBUG` 的值设置为 `express:application`,以此类推。
-## Applications generated by `express`
+## 由 `express` 生成的应用
-An application generated by the `express` command uses the `debug` module and its debug namespace is scoped to the name of the application.
+由 `express` 命令生成的应用会使用 `debug` 模块,且其调试命名空间的作用域限定为应用名称。
-For example, if you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:
+例如,如果你使用 `$ express sample-app` 命令生成了应用,可以通过以下命令启用调试语句:
```bash
$ DEBUG=sample-app:* node ./bin/www
```
-You can specify more than one debug namespace by assigning a comma-separated list of names:
+你可以通过指定以英文逗号分隔的名称列表,来启用多个调试命名空间:
```bash
$ DEBUG=http,mail,express:* node index.js
```
-## Advanced options
+## 高级选项
-When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:
+在通过 Node.js 运行时,你可以设置若干环境变量来更改调试日志的行为:
-| Name | Purpose |
-| ------------------- | ------------------------------------------------- |
-| `DEBUG` | Enables/disables specific debugging namespaces. |
-| `DEBUG_COLORS` | Whether or not to use colors in the debug output. |
-| `DEBUG_DEPTH` | Object inspection depth. |
-| `DEBUG_FD` | File descriptor to write debug output to. |
-| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
+| Name | Purpose |
+| ------------------- | ------------------------------ |
+| `DEBUG` | 启用或禁用特定的调试命名空间。 |
+| `DEBUG_COLORS` | 是否在调试输出中使用彩色显示。 |
+| `DEBUG_DEPTH` | 对象检查深度。 |
+| `DEBUG_FD` | 用于写入调试输出的文件描述符。 |
+| `DEBUG_SHOW_HIDDEN` | 显示被检查对象的隐藏属性。 |
-The environment variables beginning with `DEBUG_` end up being converted into an Options object
-that gets used with `%o`/`%O` formatters. See the Node.js documentation for
+以 `DEBUG_` 开头的环境变量最终会被转换为一个选项对象,供 `%o`/`%O` 格式化符使用。 See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) for the complete
list.
diff --git a/src/content/docs/zh-cn/4x/guide/error-handling.mdx b/src/content/docs/zh-cn/4x/guide/error-handling.mdx
index 507232b013..c9200134dc 100644
--- a/src/content/docs/zh-cn/4x/guide/error-handling.mdx
+++ b/src/content/docs/zh-cn/4x/guide/error-handling.mdx
@@ -1,22 +1,17 @@
---
-title: Error Handling
-description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications.
+title: 错误处理
+description: 了解 Express.js 如何处理同步和异步代码中的错误,并学习为你的应用实现自定义错误处理中间件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Error Handling_ refers to how Express catches and processes errors that
-occur both synchronously and asynchronously. Express comes with a default error
-handler so you don't need to write your own to get started.
+错误处理是指 Express 如何捕获并处理同步代码与异步代码中发生的错误。 Express 自带默认错误处理器,因此你在开发初期无需自行编写。
-## Catching Errors
+## 错误捕获
-It's important to ensure that Express catches all errors that occur while
-running route handlers and middleware.
+确保 Express 能够捕获路由处理器和中间件运行时发生的所有错误,这一点至关重要。
-Errors that occur in synchronous code inside route handlers and middleware
-require no extra work. If synchronous code throws an error, then Express will
-catch and process it. For example:
+路由处理函数与中间件内同步代码产生的错误无需额外处理。 倘若同步代码抛出错误,Express 会捕获并处理该错误。 举个例子:
```js
app.get('/', (req, res) => {
@@ -24,9 +19,7 @@ app.get('/', (req, res) => {
});
```
-For errors returned from asynchronous functions invoked by route handlers
-and middleware, you must pass them to the `next()` function, where Express will
-catch and process them. For example:
+对于路由处理函数和中间件调用的异步函数所返回的错误,你必须将它们传递给 `next()` 函数,Express 会在该函数中捕获并处理这些错误。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -40,9 +33,8 @@ app.get('/', (req, res, next) => {
});
```
-Starting with Express 5, route handlers and middleware that return a Promise
-will call `next(value)` automatically when they reject or throw an error.
-For example:
+从 Express 5 开始,返回 Promise 的路由处理程序和中间件在拒绝(reject)或抛出错误时,将自动调用 `next(value)`。
+举个例子:
```js
app.get('/user/:id', async (req, res, next) => {
@@ -51,16 +43,11 @@ app.get('/user/:id', async (req, res, next) => {
});
```
-If `getUserById` throws an error or rejects, `next` will be called with either
-the thrown error or the rejected value. If no rejected value is provided, `next`
-will be called with a default Error object provided by the Express router.
+如果 `getUserById` 抛出错误或被拒绝(reject),`next` 将会使用抛出的错误或被拒绝的值来调用。 如果未提供拒绝值,则会使用 Express 路由内置的默认错误对象调用 `next`。
-If you pass anything to the `next()` function (except the string `'route'`),
-Express regards the current request as being an error and will skip any
-remaining non-error handling routing and middleware functions.
+如果向 `next()` 传入任意参数(字符串 `'route'` 除外),Express 会将当前请求视作出错,并跳过后续所有非错误处理的路由与中间件函数。
-If the callback in a sequence provides no data, only errors, you can simplify
-this code as follows:
+如果序列中的回调函数不返回数据、仅返回错误,你可以将代码简化如下:
```js
app.get('/', [
@@ -73,12 +60,9 @@ app.get('/', [
]);
```
-In the above example, `next` is provided as the callback for `fs.writeFile`,
-which is called with or without errors. If there is no error, the second
-handler is executed, otherwise Express catches and processes the error.
+在上述示例中,`next` 被作为 `fs.writeFile` 的回调函数传入,无论是否存在错误都会被调用。 若无错误,则执行第二个处理函数;否则 Express 会捕获并处理该错误。
-You must catch errors that occur in asynchronous code invoked by route handlers or
-middleware and pass them to Express for processing. For example:
+你必须捕获在路由处理程序或中间件中调用的异步代码里发生的错误,并将它们传递给 Express 进行处理。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -92,13 +76,9 @@ app.get('/', (req, res, next) => {
});
```
-The above example uses a `try...catch` block to catch errors in the
-asynchronous code and pass them to Express. If the `try...catch`
-block were omitted, Express would not catch the error since it is not part of the synchronous
-handler code.
+上述示例使用 `try...catch` 代码块捕获异步代码中的错误,并将其传递给 Express。 如果省略 `try...catch` 代码块,Express 将无法捕获该错误,因为它不属于同步处理程序代码的一部分。
-Use promises to avoid the overhead of the `try...catch` block or when using functions
-that return promises. For example:
+使用 Promise 来避免 `try...catch` 代码块的开销,或在使用返回 Promise 的函数时采用此方式。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -110,12 +90,9 @@ app.get('/', (req, res, next) => {
});
```
-Since promises automatically catch both synchronous errors and rejected promises,
-you can simply provide `next` as the final catch handler and Express will catch errors,
-because the catch handler is given the error as the first argument.
+由于 Promise 会自动捕获同步错误和被拒绝的 Promise,你只需将 `next` 作为最终的 catch 处理程序传入即可,Express 会捕获错误,因为 catch 处理程序会将错误作为第一个参数传入。
-You could also use a chain of handlers to rely on synchronous error
-catching, by reducing the asynchronous code to something trivial. For example:
+你也可以使用处理程序链,将异步代码简化为简单逻辑,从而依靠同步错误捕获机制。 举个例子:
```js
app.get('/', [
@@ -132,50 +109,32 @@ app.get('/', [
]);
```
-The above example has a couple of trivial statements from the `readFile`
-call. If `readFile` causes an error, then it passes the error to Express, otherwise you
-quickly return to the world of synchronous error handling in the next handler
-in the chain. Then, the example above tries to process the data. If this fails, then the
-synchronous error handler will catch it. If you had done this processing inside
-the `readFile` callback, then the application might exit and the Express error
-handlers would not run.
+上述示例包含几条来自 `readFile` 调用的简单语句。 如果 `readFile` 引发错误,则会将错误传递给 Express;否则你将迅速回到处理程序链中下一个处理函数的同步错误处理流程。 然后,上述示例会尝试处理数据。 如果此过程失败,同步错误处理程序将会捕获该错误。 如果你将此处理逻辑写在 `readFile` 回调函数内部,应用程序可能会直接退出,Express 错误处理程序将无法执行。
-Whichever method you use, if you want Express error handlers to be called in and the
-application to survive, you must ensure that Express receives the error.
+无论你使用哪种方法,若希望 Express 错误处理程序被调用且应用程序持续运行,必须确保 Express 能够接收到错误。
-## The default error handler
+## 默认错误处理程序
-Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
+Express 内置了错误处理程序,可处理应用中可能出现的所有错误。 这个默认的错误处理中间件函数会被添加到中间件函数栈的末尾。
-If you pass an error to `next()` and you do not handle it in a custom error
-handler, it will be handled by the built-in error handler; the error will be
-written to the client with the stack trace. The stack trace is not included
-in the production environment.
+如果你将错误传递给 `next()`,但未在自定义错误处理程序中处理它,该错误将由内置错误处理程序处理;错误信息和堆栈追踪信息会被返回给客户端。 生产环境中不会包含堆栈追踪信息。
-Set the environment variable `NODE_ENV` to `production`, to run the app in production mode.
+将环境变量 `NODE_ENV` 设置为 `production`,即可在生产模式下运行应用。
-When an error is written, the following information is added to the
-response:
+当错误信息被输出时,响应中会附加以下信息:
-- The `res.statusCode` is set from `err.status` (or `err.statusCode`). If
- this value is outside the 4xx or 5xx range, it will be set to 500.
-- The `res.statusMessage` is set according to the status code.
-- The body will be the HTML of the status code message when in production
- environment, otherwise will be `err.stack`.
-- Any headers specified in an `err.headers` object.
+- `res.statusCode` 会从 `err.status`(或 `err.statusCode`)中获取设置。 如果该值不在 4xx 或 5xx 范围内,则会被设置为 500。
+- `res.statusMessage` 会根据状态码自动设置。
+- 生产环境中,响应主体会展示状态码信息的 HTML 页面;其他环境下则会展示 `err.stack` 堆栈信息。
+- `err.headers` 对象中定义的所有响应头。
-If you call `next()` with an error after you have started writing the
-response (for example, if you encounter an error while streaming the
-response to the client), the Express default error handler closes the
-connection and fails the request.
+如果在开始向客户端写入响应数据后调用带错误参数的`next()`(例如向客户端流式返回响应时出错),Express 默认错误处理程序会关闭连接并终止本次请求。
-So when you add a custom error handler, you must delegate to
-the default Express error handler, when the headers
-have already been sent to the client:
+因此,当你添加自定义错误处理程序时,若响应头已发送至客户端,必须将错误委托给 Express 默认错误处理程序处理:
```js
function errorHandler(err, req, res, next) {
@@ -187,16 +146,14 @@ function errorHandler(err, req, res, next) {
}
```
-Note that the default error handler can get triggered if you call `next()` with an error
-in your code more than once, even if custom error handling middleware is in place.
+注意:即便已配置自定义错误处理中间件,若代码中多次传入错误调用`next()`,仍可能触发默认错误处理程序。
Other error handling middleware can be found at [Express middleware](/resources/middleware).
-## Writing error handlers
+## 编写错误处理程序
-Define error-handling middleware functions in the same way as other middleware functions,
-except error-handling functions have four arguments instead of three:
-`(err, req, res, next)`. For example:
+错误处理中间件函数的定义方式与其他中间件函数基本相同,区别在于错误处理函数包含四个参数而非三个:
+`(err, req, res, next)`。 举个例子:
```js
app.use((err, req, res, next) => {
@@ -205,9 +162,9 @@ app.use((err, req, res, next) => {
});
```
-You define error-handling middleware last, after other `app.use()` and routes calls; for example:
+你需要在其他 `app.use()` 调用和路由之后,最后定义错误处理中间件;例如:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,14 +180,27 @@ app.use((err, req, res, next) => {
});
```
-Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
-For organizational (and higher-level framework) purposes, you can define
-several error-handling middleware functions, much as you would with
-regular middleware functions. For example, to define an error-handler
-for requests made by using `XHR` and those without:
+中间件函数内的响应可以是任意格式,例如 HTML 错误页面、简单消息或 JSON 字符串。
-```js
+出于组织结构(以及高级框架)的目的,你可以定义多个错误处理中间件函数,这与你使用常规中间件函数的方式非常相似。 例如,为使用 `XHR` 发起的请求和未使用 `XHR` 发起的请求分别定义错误处理程序:
+
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +216,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
@@ -279,7 +265,7 @@ function errorHandler(err, req, res, next) {
}
```
-If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. For example:
+If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. 举个例子:
```js
app.get(
diff --git a/src/content/docs/zh-cn/4x/guide/overriding-express-api.md b/src/content/docs/zh-cn/4x/guide/overriding-express-api.md
index ac0953c945..8027e5c644 100644
--- a/src/content/docs/zh-cn/4x/guide/overriding-express-api.md
+++ b/src/content/docs/zh-cn/4x/guide/overriding-express-api.md
@@ -1,20 +1,20 @@
---
-title: Overriding the Express API
-description: Discover how to customize and extend the Express.js API by overriding methods and properties on the request and response objects using prototypes.
+title: 重写Express API
+description: 了解如何通过原型重写请求和响应对象上的方法与属性,来自定义并扩展 Express.js API。
---
-The Express API consists of various methods and properties on the request and response objects. These are inherited by prototype. There are two extension points for the Express API:
+Express API 由请求对象和响应对象上的多种方法与属性组成。 这些内容通过原型继承。 Express API 有两个扩展点:
-1. The global prototypes at `express.request` and `express.response`.
-2. App-specific prototypes at `app.request` and `app.response`.
+1. `express.request` 和 `express.response` 上的全局原型。
+2. 应用专属原型位于 `app.request` 和 `app.response`。
-Altering the global prototypes will affect all loaded Express apps in the same process. If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app.
+修改全局原型会影响同一进程中所有已加载的 Express 应用。 如果需要,你可以在创建新应用后仅修改应用专属原型,从而实现仅针对当前应用的修改。
## Methods
-You can override the signature and behavior of existing methods with your own, by assigning a custom function.
+你可以通过分配自定义函数,使用自己的实现重写现有方法的签名和行为。
-Following is an example of overriding the behavior of [res.sendStatus](/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
@@ -23,9 +23,9 @@ app.response.sendStatus = function (statusCode, type, message) {
};
```
-The above implementation completely changes the original signature of `res.sendStatus`. It now accepts a status code, encoding type, and the message to be sent to the client.
+上述实现彻底更改了`res.sendStatus`原本的方法签名。 该方法现在可接收状态码、编码类型以及要发送给客户端的消息。
-The overridden method may now be used this way:
+重写后的方法现在可以这样使用:
```js
res.sendStatus(404, 'application/json', '{"error":"resource not found"}');
@@ -33,16 +33,16 @@ res.sendStatus(404, 'application/json', '{"error":"resource not found"}');
## Properties
-Properties in the Express API are either:
+Express API 中的属性分为两类:
-1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`)
-2. Defined as getters (ex: `req.secure`, `req.ip`)
+1. 赋值属性(例如:`req.baseUrl`、`req.originalUrl`)
+2. 取值器定义属性(例如:`req.secure`、`req.ip`)
-Since properties under category 1 are dynamically assigned on the `request` and `response` objects in the context of the current request-response cycle, their behavior cannot be overridden.
+由于第一类属性是在当前请求-响应周期的上下文中动态赋值到`request`和`response`对象上的,因此无法重写其行为。
-Properties under category 2 can be overwritten using the Express API extensions API.
+第二类属性可通过 Express API 扩展接口进行重写。
-The following code rewrites how the value of `req.ip` is to be derived. Now, it simply returns the value of the `Client-IP` request header.
+以下代码重写了`req.ip`值的获取方式。 现在,它仅返回 `Client-IP` 请求头的值。
```js
Object.defineProperty(app.request, 'ip', {
@@ -56,9 +56,9 @@ Object.defineProperty(app.request, 'ip', {
## Prototype
-In order to provide the Express API, the request/response objects passed to Express (via `app(req, res)`, for example) need to inherit from the same prototype chain. By default, this is `http.IncomingRequest.prototype` for the request and `http.ServerResponse.prototype` for the response.
+为了提供 Express API,传递给 Express 的请求/响应对象(例如通过 `app(req, res)`)需要继承自相同的原型链。 默认情况下,请求对象继承自 `http.IncomingRequest.prototype`,响应对象继承自 `http.ServerResponse.prototype`。
-Unless necessary, it is recommended that this be done only at the application level, rather than globally. Also, take care that the prototype that is being used matches the functionality as closely as possible to the default prototypes.
+除非必要,否则建议仅在应用层面执行此操作,而非全局层面。 此外,请注意所使用的原型需尽可能与默认原型的功能保持一致。
```js
// Use FakeRequest and FakeResponse in place of http.IncomingRequest and http.ServerResponse
diff --git a/src/content/docs/zh-cn/4x/guide/routing.mdx b/src/content/docs/zh-cn/4x/guide/routing.mdx
index b795b146ba..cd0b0ff968 100644
--- a/src/content/docs/zh-cn/4x/guide/routing.mdx
+++ b/src/content/docs/zh-cn/4x/guide/routing.mdx
@@ -1,27 +1,26 @@
---
title: Routing
-description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing.
+description: 学习如何在 Express.js 应用中定义和使用路由,包括路由方法、路由路径、参数,以及使用 Router 实现模块化路由。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Routing_ refers to how an application's endpoints (URIs) respond to client requests.
+**路由**是指应用程序的端点(URI)如何响应客户端的请求。
For an introduction to routing, see [Basic routing](/starter/basic-routing).
-You define routing using methods of the Express `app` object that correspond to HTTP methods;
-for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+你可以使用 Express `app` 对象中与 HTTP 方法对应的方法来定义路由;
+例如,`app.get()` 处理 GET 请求,`app.post` 处理 POST 请求。 For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. 换句话说,应用程序会“监听”匹配指定路由和方法的请求,当检测到匹配时,就会调用指定的回调函数。
-In fact, the routing methods can have more than one callback function as arguments.
-With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
-to the next callback.
+事实上,路由方法可以接受多个回调函数作为参数。
+对于多个回调函数,务必在回调函数中传入`next`作为参数,然后在函数体内调用`next()`,将控制权传递给下一个回调函数。
-The following code is an example of a very basic route.
+以下代码是一个非常基础的路由示例。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,11 +30,22 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
-A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
+路由方法源于 HTTP 方法之一,附加在 `express` 类的实例上。
-The following code is an example of routes that are defined for the `GET` and the `POST` methods to the root of the app.
+以下代码示例展示了为应用根路径定义的 `GET` 和 `POST` 方法路由。
```js
// GET method route
@@ -49,10 +59,10 @@ app.post('/', (req, res) => {
});
```
-Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+Express 支持对应于所有 HTTP 请求方法的方法:get、post 等。
+For a full list, see [app.METHOD](/api/application#appmethod).
-There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
+有一种特殊的路由方法 **app.all()**,用于为某一路径加载所有 HTTP 请求方法通用的中间件函数。 例如,无论使用 `GET`、`POST`、`PUT`、`DELETE` 还是 [http 模块](https://nodejs.org/api/http.html#http_http_methods)。
```js
app.all('/secret', (req, res, next) => {
@@ -63,20 +73,20 @@ app.all('/secret', (req, res, next) => {
## Route paths
-Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
+路由路径与请求方法结合,定义了可以接收请求的端点。 路由路径可以是字符串、字符串模式或正则表达式。
-Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.
-[Express Playground Router](https://bjohansebas.github.io/playground-router/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
+Express 使用 [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) 匹配路由路径;有关定义路由路径的所有可用方式,请参阅 path-to-regexp 文档。
+[Express Playground Router](https://bjohansebas.github.io/playground-router/) 是一款便捷的 Express 基础路由在线测试工具,但该工具不支持路由规则匹配。
-### Route paths based on strings
+### 基于字符串的路由路径
-Query strings are not part of the route path.
+查询字符串不属于路由路径的一部分
-This route path will match requests to the root route, `/`.
+此路由路径将匹配对根路由 `/` 的请求。
```js
app.get('/', (req, res) => {
@@ -84,7 +94,7 @@ app.get('/', (req, res) => {
});
```
-This route path will match requests to `/about`.
+此路由路径将匹配对 `/about` 的请求。
```js
app.get('/about', (req, res) => {
@@ -92,7 +102,7 @@ app.get('/about', (req, res) => {
});
```
-This route path will match requests to `/random.text`.
+此路由路径将匹配对 `/random.text` 的请求。
```js
app.get('/random.text', (req, res) => {
@@ -100,9 +110,9 @@ app.get('/random.text', (req, res) => {
});
```
-### Route paths based on string patterns
+### 基于字符串模式的路由路径
-This route path will match `acd` and `abcd`.
+此路由路径将匹配 `acd` 和 `abcd` 。
```js
app.get('/ab?cd', (req, res) => {
@@ -110,7 +120,7 @@ app.get('/ab?cd', (req, res) => {
});
```
-This route path will match `abcd`, `abbcd`, `abbbcd`, and so on.
+此路由路径将匹配 `abcd`、`abbcd`、`abbbcd` 等路径。
```js
app.get('/ab+cd', (req, res) => {
@@ -118,7 +128,7 @@ app.get('/ab+cd', (req, res) => {
});
```
-This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on.
+此路由路径将匹配 `abcd`、`abxcd`、`abRANDOMcd`、`ab123cd` 等路径。
```js
app.get('/ab*cd', (req, res) => {
@@ -126,7 +136,7 @@ app.get('/ab*cd', (req, res) => {
});
```
-This route path will match `/abe` and `/abcde`.
+此路由路径将匹配 `/abe` 和 `/abcde`。
```js
app.get('/ab(cd)?e', (req, res) => {
@@ -134,15 +144,15 @@ app.get('/ab(cd)?e', (req, res) => {
});
```
-### Route paths based on regular expressions
+### 基于正则表达式的路由路径
-Regular expression characters such as `$` need to be escaped with a `\`.
+正则表达式中的特殊字符如 `$`需要使用反斜杠 `\` 进行转义。
-This route path will match anything with an "a" in it.
+此路由路径将匹配任何包含字母 "a" 的路径。
```js
app.get(/a/, (req, res) => {
@@ -150,7 +160,7 @@ app.get(/a/, (req, res) => {
});
```
-This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on.
+此路由路径将匹配 `butterfly` 和 `dragonfly`,但不会匹配 `butterflyman`、`dragonflyman` 等路径。
```js
app.get(/.*fly$/, (req, res) => {
@@ -160,7 +170,7 @@ app.get(/.*fly$/, (req, res) => {
## Route parameters
-Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys.
+路由参数是命名式URL片段,用于捕获URL中对应位置所指定的值。 捕获的值会存入`req.params`对象,路径中定义的路由参数名作为该对象对应的键名。
```
Route path: /users/:userId/books/:bookId
@@ -168,7 +178,7 @@ Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
```
-To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
+若要使用路由参数定义路由,只需如下所示在路由路径中指定路由参数即可。
```js
app.get('/users/:userId/books/:bookId', (req, res) => {
@@ -178,11 +188,11 @@ app.get('/users/:userId/books/:bookId', (req, res) => {
-The name of route parameters must be made up of "word characters" ([A-Za-z0-9_]).
+路由参数的名称必须由“单词字符”([A-Za-z0-9_])组成。
-Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes.
+由于连字符(`-`)和点号(`.`)按字面解析,因此可结合路由参数实现实用的匹配需求。
```
Route path: /flights/:from-:to
@@ -196,7 +206,7 @@ Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
```
-To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (`()`):
+要更精准地控制路由参数可匹配的精确字符串,可以在圆括号(`()`)内追加正则表达式:
```
Route path: /user/:userId(\d+)
@@ -204,20 +214,20 @@ Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
```
-
+
Because the regular expression is usually part of a literal string, be sure to escape any `\`
characters with an additional backslash, for example `\d+`.
-
-The `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`.
+
+The [`*`](https://github.com/expressjs/express/issues/2495) character in regular expressions is not interpreted in the usual way. 作为替代方案,可用`{0,}`替代`*`。
## Route handlers
-You can provide multiple callback functions that behave like [middleware](/guide/using-middleware) to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
+You can provide multiple callback functions that behave like [middleware](/guide/using-middleware) to handle a request. 唯一的例外是这些回调函数可以调用 `next('route')` 来跳过剩余的路由回调。 你可以通过这种机制为路由施加前置条件,如果没有理由继续执行当前路由,则将控制权传递给后续路由。
```js
app.get('/user/:id', (req, res, next) => {
@@ -232,14 +242,14 @@ app.get('/user/:id', (req, res) => {
});
```
-In this example:
+在本示例中:
-- `GET /user/5` → handled by first route → sends "User 5"
-- `GET /user/0` → first route calls `next('route')`, skipping to the next matching `/user/:id` route
+- `GET /user/5` → 由第一个路由处理 → 返回 "User 5"
+- `GET /user/0` → 第一个路由调用 `next('route')`,跳转到下一个匹配的 `/user/:id` 路由
-Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
+路由处理程序可以采用函数、函数数组或二者结合的形式,如下示例所示。
-A single callback function can handle a route. For example:
+单个回调函数即可处理一个路由。 举个例子:
```js
app.get('/example/a', (req, res) => {
@@ -247,7 +257,7 @@ app.get('/example/a', (req, res) => {
});
```
-More than one callback function can handle a route (make sure you specify the `next` object). For example:
+多个回调函数可以处理同一个路由(请确保你指定了 `next` 对象)。 举个例子:
```js
app.get(
@@ -262,7 +272,7 @@ app.get(
);
```
-An array of callback functions can handle a route. For example:
+一个回调函数数组可以处理一个路由。 举个例子:
```js
const cb0 = function (req, res, next) {
@@ -282,7 +292,7 @@ const cb2 = function (req, res) {
app.get('/example/c', [cb0, cb1, cb2]);
```
-A combination of independent functions and arrays of functions can handle a route. For example:
+独立函数与函数数组组合使用即可处理一个路由。 举个例子:
```js
const cb0 = function (req, res, next) {
@@ -310,26 +320,26 @@ app.get(
## Response methods
-The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
+下表中的响应对象(`res`)方法可向客户端发送响应,并终止请求-响应循环。 如果路由处理程序未调用这些方法中的任何一个,客户端请求将一直处于挂起状态。
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | 描述 |
+| ----------------------------------------------- | ---------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | 提示客户端下载一个文件。 |
+| [res.end()](/api/response#resend) | 结束响应流程。 |
+| [res.json()](/api/response#resjson) | 发送 JSON 响应。 |
+| [res.jsonp()](/api/response#resjsonp) | 发送支持 JSONP 的 JSON 响应。 |
+| [res.redirect()](/api/response#resredirect) | 重定向请求。 |
+| [res.render()](/api/response#resrender) | 渲染视图模板。 |
+| [res.send()](/api/response#ressend) | 发送多种类型的响应。 |
+| [res.sendFile()](/api/response#ressendfile) | 以八位字节流的形式发送文件。 |
+| [res.sendStatus()](/api/response#ressendstatus) | 设置响应状态码,并将其字符串表示形式作为响应体发送。 |
## app.route()
-You can create chainable route handlers for a route path by using `app.route()`.
-Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](/api/router).
+你可以使用 `app.route()` 为路由路径创建可链式调用的路由处理程序。
+由于路径在单个位置指定,因此创建模块化路由十分有用,同时还能减少冗余和拼写错误。 For more information about routes, see: [Router() documentation](/api/router).
-Here is an example of chained route handlers that are defined by using `app.route()`.
+以下是使用 `app.route()` 定义的链式路由处理程序示例。
```js
app
@@ -347,13 +357,13 @@ app
## express.Router
-Use the `express.Router` class to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app".
+使用 `express.Router` 类创建模块化、可挂载的路由处理程序。 `Router` 实例是一个完整的中间件和路由系统;因此,它通常被称为“迷你应用”。
-The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
+以下示例创建一个路由模块,在其中加载中间件函数、定义若干路由,并将该路由模块挂载到主应用的指定路径上。
-Create a router file named `birds.js` in the app directory, with the following content:
+在应用目录中创建一个名为 `birds.js` 的路由文件,内容如下:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -376,9 +386,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
-Then, load the router module in the app:
+```mjs title="birds.mjs"
+import express from 'express';
-```js
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
+然后,在应用程序中加载路由模块:
+
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -386,9 +420,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
-The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
+应用现在将能够处理指向 `/birds` 和 `/birds/about` 的请求,同时会调用该路由专用的 `timeLog` 中间件函数。
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+但如果父路由 `/birds` 包含路径参数,默认情况下子路由无法访问这些参数。 To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/zh-cn/4x/guide/using-middleware.mdx b/src/content/docs/zh-cn/4x/guide/using-middleware.mdx
index 1372e8ca17..794140f237 100644
--- a/src/content/docs/zh-cn/4x/guide/using-middleware.mdx
+++ b/src/content/docs/zh-cn/4x/guide/using-middleware.mdx
@@ -1,24 +1,25 @@
---
-title: Using middleware
-description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware.
+title: 使用中间件
+description: 了解如何在 Express.js 应用中使用中间件,包括应用级和路由级中间件、错误处理以及集成第三方中间件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
+Express 是一款路由与中间件 Web 框架,自身仅提供极简的基础功能:一个 Express 应用本质上就是一连串中间件函数的调用。
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the next middleware function in the application's request-response cycle. 下一个中间件函数通常使用名为`next`的变量来表示。
-Middleware functions can perform the following tasks:
+中间件函数可执行下列任务:
-- Execute any code.
-- Make changes to the request and the response objects.
-- End the request-response cycle.
-- Call the next middleware function in the stack.
+- 执行任意代码。
+- 修改请求对象与响应对象。
+- 终止请求-响应周期。
+- 调用栈中的下一个中间件函数。
-If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
+如果当前中间件函数没有终止请求-响应周期,它必须调用 `next()` 以将控制权传递给下一个中间件函数。 否则,请求将会被挂起。
-An Express application can use the following types of middleware:
+Express 应用可以使用以下类型的中间件:
- [Application-level middleware](#middleware.application)
- [Router-level middleware](#middleware.router)
@@ -26,16 +27,16 @@ An Express application can use the following types of middleware:
- [Built-in middleware](#middleware.built-in)
- [Third-party middleware](#middleware.third-party)
-You can load application-level and router-level middleware with an optional mount path.
-You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
+你可以通过可选的挂载路径加载应用级中间件和路由级中间件。
+你也可以同时加载一系列中间件函数,这会在挂载点处创建中间件系统的一个子栈。
-## Application-level middleware
+## 应用级中间件
-Bind application-level middleware to an instance of the [app object](/5x/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
+Bind application-level middleware to an instance of the [app object](/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
-This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
+本示例展示了一个没有挂载路径的中间件函数。 每当应用接收请求时,该函数都会被执行。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,8 +46,18 @@ app.use((req, res, next) => {
});
```
-This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
-HTTP request on the `/user/:id` path.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
+本示例展示了一个挂载在 `/user/:id` 路径上的中间件函数。 只要是发往 `/user/:id` 路径的任意类型 HTTP 请求,都会执行该中间件函数。
```js
app.use('/user/:id', (req, res, next) => {
@@ -55,7 +66,7 @@ app.use('/user/:id', (req, res, next) => {
});
```
-This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path.
+该示例展示了一条路由及其处理函数(中间件体系)。 该函数处理指向 `/user/:id` 路径的 GET 请求。
```js
app.get('/user/:id', (req, res, next) => {
@@ -63,8 +74,8 @@ app.get('/user/:id', (req, res, next) => {
});
```
-Here is an example of loading a series of middleware functions at a mount point, with a mount path.
-It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
+下面是在指定挂载路径的挂载点加载一系列中间件函数的示例。
+该示例演示了一个中间件子栈,会对所有访问 `/user/:id` 路径的各类 HTTP 请求打印请求信息。
```js
app.use(
@@ -80,9 +91,9 @@ app.use(
);
```
-Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
+路由处理程序支持为同一个路径定义多条路由。 下面的示例为 `/user/:id` 路径的 GET 请求定义了两条路由。 第二条路由不会报错,但永远不会被执行,因为第一条路由已经结束了请求-响应周期。
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
app.get(
@@ -102,16 +113,15 @@ app.get('/user/:id', (req, res, next) => {
});
```
-To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route.
+若要跳过路由中间件栈中剩余的中间件函数,调用 `next('route')` 即可将控制权传递给下一条路由。
-`next('route')` will work only in middleware functions that were loaded by using the
-`app.METHOD()` or `router.METHOD()` functions.
+`next('route')` 仅在通过 `app.METHOD()` 或 `router.METHOD()` 函数加载的中间件函数中生效。
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
app.get(
@@ -134,9 +144,9 @@ app.get('/user/:id', (req, res, next) => {
});
```
-Middleware can also be declared in an array for reusability.
+中间件也可以定义在数组中,实现复用。
-This example shows an array with a middleware sub-stack that handles GET requests to the `/user/:id` path
+该示例展示了一个使用数组封装的中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
function logOriginalUrl(req, res, next) {
@@ -155,19 +165,19 @@ app.get('/user/:id', logStuff, (req, res, next) => {
});
```
-## Router-level middleware
+## 路由级中间件
-Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`.
+路由级中间件的工作方式与应用级中间件完全相同,唯一区别是它绑定到 `express.Router()` 的实例上。
```js
const router = express.Router();
```
-Load router-level middleware by using the `router.use()` and `router.METHOD()` functions.
+通过 `router.use()` 和 `router.METHOD()` 函数加载路由级中间件。
-The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
+下面的示例代码通过路由级中间件,复刻了上方展示的应用级中间件的中间件体系:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +226,61 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
-To skip the rest of the router's middleware functions, call `next('router')`
-to pass control back out of the router instance.
+```mjs title="index.mjs"
+import express from 'express';
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+const app = express();
+const router = express.Router();
-```js
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
+若要跳过当前路由实例中剩余的中间件函数,调用 `next('router')` 即可将控制权交回给路由实例。
+
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
+
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,18 +301,37 @@ app.use('/admin', router, (req, res) => {
});
```
-## Error-handling middleware
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
+## 错误处理中间件
-Error-handling middleware always takes _four_ arguments. You must provide four arguments to
-identify it as an error-handling middleware function. Even if you don't need to use the `next`
-object, you must specify it to maintain the signature. Otherwise, the `next` object will be
-interpreted as regular middleware and will fail to handle errors.
+错误处理中间件始终接收**四个**参数。 你必须传入**四个参数**,才能将其标识为错误处理中间件函数。 即使你不需要使用 `next` 对象,也必须声明它,以保持函数签名不变。 否则,`next` 对象会被解析为常规中间件,从而无法处理错误。
-Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`:
+定义错误处理中间件函数的方式与其他中间件一致,唯一区别是它接收四个参数而非三个,标准函数签名为:`(err, req, res, next)`。
```js
app.use((err, req, res, next) => {
@@ -264,30 +342,27 @@ app.use((err, req, res, next) => {
For details about error-handling middleware, see: [Error handling](/guide/error-handling).
-## Built-in middleware
+## 内置中间件
-Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). The middleware
-functions that were previously included with Express are now in separate modules; see [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
+从 4.x 版本开始,Express 不再依赖 [Connect](https://github.com/senchalabs/connect)。 之前包含在 Express 中的中间件函数,现在已经拆分到独立的模块中;查看[中间件函数列表](https://github.com/senchalabs/connect#middleware)。
-Express has the following built-in middleware functions:
+Express 包含以下内置中间件函数:
-- [express.static](/5x/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/5x/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/5x/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **注意:此功能仅在 Express 4.16.0 及以上版本可用**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **注意:此功能仅在 Express 4.16.0 及以上版本可用**
-## Third-party middleware
+## 第三方中间件
-Use third-party middleware to add functionality to Express apps.
+使用第三方中间件可以为 Express 应用拓展功能。
-Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.
+先安装实现所需功能的 Node.js 模块,之后在应用级别或路由级别将其引入项目。
-The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
+下面的示例演示了如何安装并加载 cookie 解析中间件 `cookie-parser`。
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +371,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
-For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
+如需查看可配合 Express 使用的常用第三方中间件部分清单,请参阅:[第三方中间件](/resources/middleware)。
diff --git a/src/content/docs/zh-cn/4x/guide/using-template-engines.mdx b/src/content/docs/zh-cn/4x/guide/using-template-engines.mdx
index 0f660ddbb2..c99f896488 100644
--- a/src/content/docs/zh-cn/4x/guide/using-template-engines.mdx
+++ b/src/content/docs/zh-cn/4x/guide/using-template-engines.mdx
@@ -1,45 +1,41 @@
---
-title: Using template engines with Express
-description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently.
+title: 在 Express 中使用模板引擎
+description: 了解如何在 Express.js 中集成并使用 Pug、Handlebars、EJS 等模板引擎,高效渲染动态 HTML 页面。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
-variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
-This approach makes it easier to design an HTML page.
+模板引擎能够让你在应用中使用静态模板文件。 运行时,模板引擎会将模板文件中的变量替换为实际值,并把模板转换成HTML文件发送至客户端。
+这种方式能够简化HTML页面的开发。
-The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
+[Express应用生成器](/en/starter/generator)默认使用[Pug](https://pugjs.org/api/getting-started.html),同时也支持[Handlebars](https://www.npmjs.com/package/handlebars)、[EJS](https://www.npmjs.com/package/ejs)等模板引擎。
-To render template files, set the following [application setting properties](/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
-- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
- This defaults to the `views` directory in the application root directory.
-- `view engine`, the template engine to use. For example, to use the Pug template engine: `app.set('view engine', 'pug')`.
+- `views`,模板文件所在的目录。 例如:`app.set('views', './views')`。
+ 该配置默认为应用根目录下的`views`目录。
+- `view engine`,要使用的模板引擎。 例如,要使用 Pug 模板引擎:`app.set('view engine', 'pug')`。
-Then install the corresponding template engine npm package; for example to install Pug:
+然后安装对应的模板引擎 npm 包;例如要安装 Pug:
-```bash
-$ npm install pug --save
-```
+
-Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
-which `res.render()` calls to render the template code.
+符合 Express 规范的模板引擎如 Pug会导出一个名为`__express(filePath, options, callback)`的函数,`res.render()`会调用该函数来渲染模板代码。
-Some template engines do not follow this convention. The [@ladjs/consolidate](https://www.npmjs.com/package/@ladjs/consolidate)
-library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express.
+有些模板引擎并不遵循此规范。 [@ladjs/consolidate](https://www.npmjs.com/package/@ladjs/consolidate)库遵循此规范,对所有主流Node.js模板引擎进行了统一封装,因此可在Express中无缝使用。
-After the view engine is set, you don't have to specify the engine or load the template engine module in your app;
-Express loads the module internally, for example:
+设置视图引擎后,你无需在应用中指定引擎或加载模板引擎模块;
+Express 会在内部自动加载该模块,例如:
```js
app.set('view engine', 'pug');
```
-Then, create a Pug template file named `index.pug` in the `views` directory, with the following content:
+然后,在`views`目录中创建一个名为`index.pug`的Pug模板文件,内容如下:
```pug
html
@@ -49,8 +45,7 @@ html
h1= message
```
-Create a route to render the `index.pug` file. If the `view engine` property is not set,
-you must specify the extension of the `view` file. Otherwise, you can omit it.
+创建一条路由来渲染`index.pug`文件。 如果未配置`view engine`属性,则必须指明视图文件的后缀名。 否则可以省略文件后缀。
```js
app.get('/', (req, res) => {
@@ -58,6 +53,6 @@ app.get('/', (req, res) => {
});
```
-When you make a request to the home page, the `index.pug` file will be rendered as HTML.
+当访问首页时,`index.pug` 文件会被渲染成 HTML。
-The view engine cache does not cache the contents of the template's output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on.
+视图引擎缓存不会缓存模板渲染后的输出内容,仅缓存原始模板文件本身。 即便开启缓存,每次请求视图仍会重新渲染。
diff --git a/src/content/docs/zh-cn/4x/guide/writing-middleware.mdx b/src/content/docs/zh-cn/4x/guide/writing-middleware.mdx
index ae0eeaf7f0..14790a1a4f 100644
--- a/src/content/docs/zh-cn/4x/guide/writing-middleware.mdx
+++ b/src/content/docs/zh-cn/4x/guide/writing-middleware.mdx
@@ -1,22 +1,22 @@
---
-title: Writing middleware for use in Express apps
-description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling.
+title: 编写 Express 应用使用的中间件
+description: 学习如何为 Express.js 应用编写自定义中间件函数,包含用于增强请求和响应处理的示例与最佳实践。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the `next` function in the application's request-response cycle. `next` 函数是 Express 路由器中的一个函数,调用该函数时,会执行当前中间件之后的下一个中间件。
-Middleware functions can perform the following tasks:
+中间件函数可执行下列任务:
-- Execute any code.
-- Make changes to the request and the response objects.
-- End the request-response cycle.
-- Call the next middleware in the stack.
+- 执行任意代码。
+- 修改请求对象与响应对象。
+- 终止请求-响应周期。
+- 调用堆栈中的下一个中间件。
-If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
+如果当前中间件函数没有终止请求-响应周期,它必须调用 `next()` 以将控制权传递给下一个中间件函数。 否则,请求将会被挂起。
-The following figure shows the elements of a middleware function call:
+下图展示了中间件函数调用的组成要素:
-Starting with Express 5, middleware functions that return a Promise will call `next(value)` when they reject or throw an error. `next` will be called with either the rejected value or the thrown Error.
+从 Express 5 开始,返回 Promise 的中间件函数在被拒绝或抛出错误时,会自动调用 `next(value)`。 `next` 函数将以被拒绝的值或抛出的错误对象作为参数被调用。
-## Example
+## 示例
-Here is an example of a simple "Hello World" Express application.
-The remainder of this article will define and add three middleware functions to the application:
-one called `myLogger` that prints a simple log message, one called `requestTime` that
-displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
+以下是一个简单的 Express “Hello World” 应用示例。
+本文的后续部分将为该应用定义并添加三个中间件函数:
+一个名为 `myLogger`,用于打印简单的日志信息;一个名为 `requestTime`,用于显示 HTTP 请求的时间戳;还有一个名为 `validateCookies`,用于验证传入的 Cookie。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -70,11 +68,21 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-### Middleware function myLogger
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
+### 中间件函数 myLogger
-Here is a simple example of a middleware function called "myLogger". This function just prints
-"LOGGED" when a request to the app passes through it. The middleware function is assigned to a
-variable named `myLogger`.
+以下是一个名为 `myLogger` 的简单中间件函数示例。 当对应用的请求经过该函数时,它只会打印 "LOGGED"。 该中间件函数被赋值给了一个名为 `myLogger` 的变量。
```js
const myLogger = function (req, res, next) {
@@ -85,17 +93,14 @@ const myLogger = function (req, res, next) {
-Notice the call above to `next()`. Calling this function invokes the next middleware function in
-the app. The `next()` function is not a part of the Node.js or Express API, but is the third
-argument that is passed to the middleware function. The `next()` function could be named anything,
-but by convention it is always named "next". To avoid confusion, always use this convention.
+注意上述代码中对 `next()` 的调用。 调用该函数会执行应用中的下一个中间件函数。 `next()` 函数并非 Node.js 或 Express API 的一部分,而是传递给中间件函数的第三个参数。 `next()` 函数可以被命名为任意名称,但按照惯例,它始终被命名为 `next`。 为避免混淆,请始终遵循此命名惯例。
-To load the middleware function, call `app.use()`, specifying the middleware function.
-For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
+加载中间件函数时,需调用 `app.use()` 并传入该中间件函数。
+例如,以下代码在根路径(/)路由之前加载 `myLogger` 中间件函数。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -113,18 +118,36 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-Every time the app receives a request, it prints the message "LOGGED" to the terminal.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
+每当应用接收到请求时,都会在终端中打印消息 "LOGGED"。
-The order of middleware loading is important: middleware functions that are loaded first are also executed first.
+中间件的加载顺序至关重要:先加载的中间件会先执行。
-If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn't print "LOGGED", because the route handler of the root path terminates the request-response cycle.
+如果 `myLogger` 在根路径路由之后加载,请求永远不会到达该中间件,应用也不会打印 "LOGGED",因为根路径的路由处理程序会终止请求-响应循环。
-The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function.
+中间件函数 `myLogger` 仅打印一条消息,然后通过调用 `next()` 函数将请求传递给栈中的下一个中间件函数。
-### Middleware function requestTime
+### 中间件函数 requestTime
-Next, we'll create a middleware function called "requestTime" and add a property called `requestTime`
-to the request object.
+接下来,我们将创建一个名为 `requestTime` 的中间件函数,并向请求对象添加一个名为 `requestTime` 的属性。
```js
const requestTime = function (req, res, next) {
@@ -133,9 +156,9 @@ const requestTime = function (req, res, next) {
};
```
-The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
+该应用现在使用了 `requestTime` 中间件函数。 此外,根路径路由的回调函数使用了中间件函数挂载到`req`(请求对象)上的属性。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -155,13 +178,34 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
+向应用根路径发起请求后,应用便会在浏览器中展示本次请求的时间戳。
-### Middleware function validateCookies
+### 中间件函数 validateCookies
-Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.
+最后,我们将创建一个中间件函数来验证传入的 Cookie,如果 Cookie 无效,则返回 400 响应。
-Here's an example function that validates cookies with an external async service.
+下面是一个示例函数,它通过外部异步服务验证 Cookie。
```js
async function cookieValidator(cookies) {
@@ -173,9 +217,9 @@ async function cookieValidator(cookies) {
}
```
-Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
+此处我们使用 [`cookie-parser`](/en/resources/middleware/cookie-parser) 中间件从 `req` 对象中解析传入的 Cookie,并将其传给 `cookieValidator` 函数。 `validateCookies` 中间件会返回一个 Promise,该 Promise 被拒绝时将自动触发我们的错误处理程序。
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -199,27 +243,45 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
-Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
-`cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything
-to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
-request as being an error and will skip any remaining non-error handling routing and middleware
-functions.
+注意 `next()` 是在 `await cookieValidator(req.cookies)` 之后调用的。 这能确保如果 `cookieValidator` 状态变为已兑现,堆栈中的下一个中间件将会被调用。 如果你向 `next()` 函数传入任何内容(字符串 `'route'` 或 `'router'` 除外),Express 会将当前请求视为错误,并跳过所有剩余的非错误处理路由和中间件函数。
-Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.
+由于你可以访问请求对象、响应对象、堆栈中的下一个中间件函数以及整个 Node.js API,因此中间件函数的用途是无限的。
For more information about Express middleware, see: [Using Express middleware](/guide/using-middleware).
-## Configurable middleware
-
-If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
+## 可配置中间件
-File: `my-middleware.js`
+如果需要让你的中间件具备可配置性,可导出一个接收选项对象或其他参数的函数,该函数会根据输入参数返回对应的中间件实现。
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -228,12 +290,27 @@ module.exports = function (options) {
};
```
-The middleware can now be used as shown below.
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
-```js
-const mw = require('./my-middleware.js');
+该中间件现在可如下所示使用。
+
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
-Refer to [cookie-session](https://github.com/expressjs/cookie-session) and [compression](https://github.com/expressjs/compression) for examples of configurable middleware.
+有关可配置中间件的示例,请参考 [cookie-session](https://github.com/expressjs/cookie-session) 和 [compression](https://github.com/expressjs/compression)。
diff --git a/src/content/docs/zh-cn/4x/starter/basic-routing.mdx b/src/content/docs/zh-cn/4x/starter/basic-routing.mdx
index f14af2a5de..5780e52d70 100644
--- a/src/content/docs/zh-cn/4x/starter/basic-routing.mdx
+++ b/src/content/docs/zh-cn/4x/starter/basic-routing.mdx
@@ -1,38 +1,37 @@
---
-title: Basic routing
-description: Learn the fundamentals of routing in Express.js applications, including how to define routes, handle HTTP methods, and create route handlers for your web server.
+title: 基本路由
+description: 学习 Express.js 应用程序中路由的基础知识,包括如何定义路由、处理 HTTP 方法以及为 Web 服务器创建路由处理程序。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Routing_ refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
+路由用于定义应用程序如何响应客户端对指定端点的请求;端点由统一资源标识符(URI,或称路径)和具体的 HTTP 请求方法(GET、POST 等)组成。
-Each route can have one or more handler functions, which are executed when the route is matched.
+每条路由可配置一个或多个处理函数,匹配到该路由时就会执行这些函数。
-Route definition takes the following structure:
+路由的定义格式如下:
```js
app.METHOD(PATH, HANDLER);
```
-Where:
+其中:
-- `app` is an instance of `express`.
-- `METHOD` is an [HTTP request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods), in lowercase.
-- `PATH` is a path on the server.
-- `HANDLER` is the function executed when the route is matched.
+- `app` 是 `express` 的实例。
+- `METHOD` 是小写形式的 [HTTP 请求方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Reference/Methods)。
+- `PATH` 是服务器上的路径。
+- `HANDLER` 是路由匹配时执行的函数。
-This tutorial assumes that an instance of `express` named `app` is created and the server is
-running. If you are not familiar with creating an app and starting it, see the Hello world
+本教程假设已创建一个名为 `app` 的 `express` 实例,且服务器正在运行。 If you are not familiar with creating an app and starting it, see the Hello world
example.
-The following examples illustrate defining simple routes.
+以下示例演示如何定义简单路由。
-Respond with `Hello World!` on the homepage:
+在主页响应 `Hello World!`:
```js
app.get('/', (req, res) => {
@@ -40,7 +39,7 @@ app.get('/', (req, res) => {
});
```
-Respond to a POST request on the root route (`/`), the application's home page:
+响应根路由(/)应用的主页的 POST 请求:
```js
app.post('/', (req, res) => {
@@ -48,7 +47,7 @@ app.post('/', (req, res) => {
});
```
-Respond to a PUT request to the `/user` route:
+响应 `/user` 路由的 PUT 请求:
```js
app.put('/user', (req, res) => {
@@ -56,7 +55,7 @@ app.put('/user', (req, res) => {
});
```
-Respond to a DELETE request to the `/user` route:
+响应 `/user` 路由的 DELETE 请求:
```js
app.delete('/user', (req, res) => {
diff --git a/src/content/docs/zh-cn/4x/starter/examples.mdx b/src/content/docs/zh-cn/4x/starter/examples.mdx
index 6685b9cbe4..e4c31a74ea 100644
--- a/src/content/docs/zh-cn/4x/starter/examples.mdx
+++ b/src/content/docs/zh-cn/4x/starter/examples.mdx
@@ -1,45 +1,43 @@
---
-title: Express examples
-description: Explore a collection of Express.js application examples covering various use cases, integrations, and advanced configurations to help you learn and build your projects.
+title: Express 示例
+description: 浏览一系列 Express.js 应用示例,涵盖不同的使用场景、集成方式以及高级配置,帮助你学习并构建自己的项目。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-- [auth](https://github.com/expressjs/express/tree/4.x/examples/auth) - Authentication with login and password
-- [content-negotiation](https://github.com/expressjs/express/tree/4.x/examples/content-negotiation) - HTTP content negotiation
-- [cookie-sessions](https://github.com/expressjs/express/tree/4.x/examples/cookie-sessions) - Working with cookie-based sessions
-- [cookies](https://github.com/expressjs/express/tree/4.x/examples/cookies) - Working with cookies
-- [downloads](https://github.com/expressjs/express/tree/4.x/examples/downloads) - Transferring files to client
-- [ejs](https://github.com/expressjs/express/tree/4.x/examples/ejs) - Working with Embedded JavaScript templating (ejs)
-- [error-pages](https://github.com/expressjs/express/tree/4.x/examples/error-pages) - Creating error pages
-- [error](https://github.com/expressjs/express/tree/4.x/examples/error) - Working with error middleware
-- [hello-world](https://github.com/expressjs/express/tree/4.x/examples/hello-world) - Simple request handler
-- [markdown](https://github.com/expressjs/express/tree/4.x/examples/markdown) - Markdown as template engine
-- [multi-router](https://github.com/expressjs/express/tree/4.x/examples/multi-router) - Working with multiple Express routers
-- [mvc](https://github.com/expressjs/express/tree/4.x/examples/mvc) - MVC-style controllers
-- [online](https://github.com/expressjs/express/tree/4.x/examples/online) - Tracking online user activity with `online` and `redis` packages
-- [params](https://github.com/expressjs/express/tree/4.x/examples/params) - Working with route parameters
-- [resource](https://github.com/expressjs/express/tree/4.x/examples/resource) - Multiple HTTP operations on the same resource
-- [route-map](https://github.com/expressjs/express/tree/4.x/examples/route-map) - Organizing routes using a map
-- [route-middleware](https://github.com/expressjs/express/tree/4.x/examples/route-middleware) - Working with route middleware
-- [route-separation](https://github.com/expressjs/express/tree/4.x/examples/route-separation) - Organizing routes per each resource
-- [search](https://github.com/expressjs/express/tree/4.x/examples/search) - Search API
-- [session](https://github.com/expressjs/express/tree/4.x/examples/session) - User sessions
-- [static-files](https://github.com/expressjs/express/tree/4.x/examples/static-files) - Serving static files
-- [vhost](https://github.com/expressjs/express/tree/4.x/examples/vhost) - Working with virtual hosts
-- [view-constructor](https://github.com/expressjs/express/tree/4.x/examples/view-constructor) - Rendering views dynamically
-- [view-locals](https://github.com/expressjs/express/tree/4.x/examples/view-locals) - Saving data in request object between middleware calls
-- [web-service](https://github.com/expressjs/express/tree/4.x/examples/web-service) - Simple API service
+- [auth](https://github.com/expressjs/express/tree/4.x/examples/auth) - 基于用户名和密码的身份验证
+- [content-negotiation](https://github.com/expressjs/express/tree/4.x/examples/content-negotiation) - HTTP 内容协商
+- [cookie-sessions](https://github.com/expressjs/express/tree/4.x/examples/cookie-sessions) - 基于 Cookie 的会话处理
+- [cookies](https://github.com/expressjs/express/tree/4.x/examples/cookies) - Cookie 的使用
+- [downloads](https://github.com/expressjs/express/tree/4.x/examples/downloads) - 向客户端传输文件
+- [ejs](https://github.com/expressjs/express/tree/4.x/examples/ejs) - 使用 Embedded JavaScript(ejs)模板引擎
+- [error-pages](https://github.com/expressjs/express/tree/4.x/examples/error-pages) - 创建错误页面
+- [error](https://github.com/expressjs/express/tree/4.x/examples/error) - 使用错误处理中间件
+- [hello-world](https://github.com/expressjs/express/tree/4.x/examples/hello-world) - 简单的请求处理示例
+- [markdown](https://github.com/expressjs/express/tree/4.x/examples/markdown) - 使用 Markdown 作为模板引擎
+- [multi-router](https://github.com/expressjs/express/tree/4.x/examples/multi-router) - 使用多个 Express Router
+- [mvc](https://github.com/expressjs/express/tree/4.x/examples/mvc) - MVC 风格的控制器示例
+- [online](https://github.com/expressjs/express/tree/4.x/examples/online) - 使用 `online` 和 `redis` 包跟踪用户在线状态
+- [params](https://github.com/expressjs/express/tree/4.x/examples/params) - 路由参数的使用
+- [resource](https://github.com/expressjs/express/tree/4.x/examples/resource) - 在同一资源上执行多种 HTTP 操作
+- [route-map](https://github.com/expressjs/express/tree/4.x/examples/route-map) - 使用映射结构组织路由
+- [route-middleware](https://github.com/expressjs/express/tree/4.x/examples/route-middleware) - 路由级中间件的使用
+- [route-separation](https://github.com/expressjs/express/tree/4.x/examples/route-separation) - 按资源对路由进行组织
+- [search](https://github.com/expressjs/express/tree/4.x/examples/search) - 搜索 API
+- [session](https://github.com/expressjs/express/tree/4.x/examples/session) - 用户会话管理
+- [static-files](https://github.com/expressjs/express/tree/4.x/examples/static-files) - 提供静态文件服务
+- [vhost](https://github.com/expressjs/express/tree/4.x/examples/vhost) - 使用虚拟主机
+- [view-constructor](https://github.com/expressjs/express/tree/4.x/examples/view-constructor) - 动态渲染视图
+- [view-locals](https://github.com/expressjs/express/tree/4.x/examples/view-locals) - 在中间件调用之间将数据保存在请求对象中
+- [web-service](https://github.com/expressjs/express/tree/4.x/examples/web-service) - 简单的 API 服务
-## Additional examples
+## 更多示例
-These are some additional examples with more extensive integrations.
+以下是一些包含更复杂集成的示例。
-
- This information refers to third-party sites, products, or modules that are not maintained by the
- Expressjs team. Listing here does not constitute an endorsement or recommendation from the
- Expressjs project team.
+
+ 这些信息指的是第三方站点、产品或模块,它们不是由Expressjs团队维护的。 此处的罗列并不代表 Express
+ 项目团队的认可或推荐。
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
-- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
+- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - 使用 TypeScript 的 Express REST API,并使用 [Prisma](https://www.npmjs.com/package/prisma) 作为 ORM
diff --git a/src/content/docs/zh-cn/4x/starter/faq.md b/src/content/docs/zh-cn/4x/starter/faq.md
index 6da7f23881..aa85913868 100644
--- a/src/content/docs/zh-cn/4x/starter/faq.md
+++ b/src/content/docs/zh-cn/4x/starter/faq.md
@@ -1,58 +1,43 @@
---
-title: FAQ
-description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more.
+title: FAQ 常见问题解答
+description: 查找有关 Express.js 的常见问题解答,涵盖应用程序架构、数据模型、身份验证、模板引擎、错误处理等相关主题。
---
-## How should I structure my application?
+## 我应该如何组织我的应用程序?
-There is no definitive answer to this question. The answer depends
-on the scale of your application and the team that is involved. To be as
-flexible as possible, Express makes no assumptions in terms of structure.
+这个问题没有标准答案。 答案取决于你的应用规模以及参与开发的团队。 为实现最大限度的灵活性,Express 不会对项目结构做任何强制限定。
-Routes and other application-specific logic can live in as many files
-as you wish, in any directory structure you prefer. View the following
-examples for inspiration:
+路由和其他应用专属逻辑可拆分至任意数量文件,并采用你偏好的任意目录结构存放。 可参考下方示例获取项目结构设计思路:
- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
- [Route map](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
- [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc)
-Also, there are third-party extensions for Express, which simplify some of these patterns:
+此外,Express 拥有各类第三方扩展,能够简化部分开发架构范式:
- [Resourceful routing](https://github.com/expressjs/express-resource)
-## How do I define models?
+## 如何定义模型?
-Express has no notion of a database. This concept is
-left up to third-party Node modules, allowing you to
-interface with nearly any database.
+Express 本身不包含数据库相关概念。 这一概念交由第三方 Node 模块实现,让你能够与几乎所有数据库进行交互。
See [LoopBack](http://loopback.io) for an Express-based framework that is centered around models.
-## How can I authenticate users?
+## 如何实现用户身份验证?
-Authentication is another opinionated area that Express does not
-venture into. You may use any authentication scheme you wish.
-For a simple username / password scheme, see [this example](https://github.com/expressjs/express/tree/master/examples/auth).
+身份验证同样是一项带有主观选型倾向的功能,Express 并未涉足该领域。 你可以选用任意你想要的身份验证方案。
+如需实现简易的用户名/密码验证方案,可参考[该示例](https://github.com/expressjs/express/tree/master/examples/auth)。
-## Which template engines does Express support?
+## Express 支持哪些模板引擎?
-Express supports any template engine that conforms with the `(path, locals, callback)` signature.
-To normalize template engine interfaces and caching, see the
-[consolidate.js](https://github.com/visionmedia/consolidate.js)
-project for support. Unlisted template engines might still support the Express signature.
+Express 支持所有符合 `(path, locals, callback)` 入参规范的模板引擎。
+如需统一各类模板引擎的接口与缓存机制,可查看 [consolidate.js](https://github.com/visionmedia/consolidate.js) 项目以获取相关支持。 未列入清单的模板引擎也可能兼容 Express 的调用规范。
For more information, see [Using template engines with Express](/guide/using-template-engines).
-## How do I handle 404 responses?
+## 如何处理 404 响应?
-In Express, 404 responses are not the result of an error, so
-the error-handler middleware will not capture them. This behavior is
-because a 404 response simply indicates the absence of additional work to do;
-in other words, Express has executed all middleware functions and routes,
-and found that none of them responded. All you need to
-do is add a middleware function at the very bottom of the stack (below all other functions)
-to handle a 404 response:
+在 Express 中,404 响应并非由错误导致,因此错误处理中间件不会捕获这类响应。 出现这种行为的原因是,404 响应仅表示没有其他待执行的操作;换言之,Express 已执行完所有中间件函数和路由,但未找到任何能够响应请求的处理逻辑。 你只需在中间件栈的最底部(所有其他函数之后)添加一个中间件函数来处理 404 响应即可:
```js
app.use((req, res, next) => {
@@ -60,13 +45,11 @@ app.use((req, res, next) => {
});
```
-Add routes dynamically at runtime on an instance of `express.Router()`
-so the routes are not superseded by a middleware function.
+在运行时通过 `express.Router()` 实例动态添加路由,确保路由不会被中间件函数覆盖。
-## How do I setup an error handler?
+## 如何设置错误处理程序?
-You define error-handling middleware in the same way as other middleware,
-except with four arguments instead of three; specifically with the signature `(err, req, res, next)`:
+错误处理中间件的定义方式与其他中间件相同,区别在于它使用四个参数而非三个;具体的函数签名为 `(err, req, res, next)`:
```js
app.use((err, req, res, next) => {
@@ -77,14 +60,13 @@ app.use((err, req, res, next) => {
For more information, see [Error handling](/guide/error-handling).
-## How do I render plain HTML?
+## 如何渲染纯 HTML?
-You don't! There's no need to "render" HTML with the `res.render()` function.
-If you have a specific file, use the `res.sendFile()` function.
-If you are serving many assets from a directory, use the `express.static()`
-middleware function.
+无需额外操作! 无需使用 `res.render()` 函数来“渲染” HTML。
+如果你需要响应指定的文件,请使用 `res.sendFile()` 函数。
+如果你要从一个目录提供多个静态资源,请使用 `express.static()` 中间件函数。
-## What version of Node.js does Express require?
+## Express 需要哪个版本的 Node.js?
- [Express 4.x](/api) requires Node.js 0.10 or higher.
- [Express 5.x](/5x/api) requires Node.js 18 or higher.
diff --git a/src/content/docs/zh-cn/4x/starter/generator.mdx b/src/content/docs/zh-cn/4x/starter/generator.mdx
index 4f22665f43..1bbc4ad151 100644
--- a/src/content/docs/zh-cn/4x/starter/generator.mdx
+++ b/src/content/docs/zh-cn/4x/starter/generator.mdx
@@ -1,26 +1,26 @@
---
-title: Express application generator
-description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration.
+title: Express 应用生成器
+description: 学习如何使用 Express 应用生成器工具快速创建 Express.js 应用骨架,简化初始化与配置工作。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-Use the application generator tool, `express-generator`, to quickly create an application skeleton.
+使用应用生成器工具 `express-generator` 可以快速创建应用骨架。
-You can run the application generator with the `npx` command (available in Node.js 8.2.0).
+你可以使用 `npx` 命令(Node.js 8.2.0 及以上版本可用)运行应用生成器。
```bash
$ npx express-generator
```
-For earlier Node versions, install the application generator as a global npm package and then launch it:
+对于早期的 Node 版本,请将应用生成器作为全局 npm 包安装,然后启动它:
```bash
$ npm install -g express-generator
$ express
```
-Display the command options with the `-h` option:
+使用 `-h` 选项查看命令选项:
```bash
$ express -h
@@ -42,7 +42,7 @@ $ express -h
-f, --force force on non-empty directory
```
-For example, the following creates an Express app named _myapp_. The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug:
+例如,以下命令会创建一个名为 _myapp_ 的 Express 应用。 此应用将创建在当前工作目录下名为 _myapp_ 的文件夹中,并且视图引擎将设置为 Pug:
```bash
$ express --view=pug myapp
@@ -66,34 +66,34 @@ $ express --view=pug myapp
create : myapp/bin/www
```
-Then install dependencies:
+然后安装依赖项:
```bash
$ cd myapp
$ npm install
```
-On MacOS or Linux, run the app with this command:
+在 macOS 或 Linux 系统上,使用此命令运行应用:
```bash
$ DEBUG=myapp:* npm start
```
-On Windows Command Prompt, use this command:
+在 Windows 命令提示符中,使用此命令:
```bash
> set DEBUG=myapp:* & npm start
```
-On Windows PowerShell, use this command:
+在 Windows PowerShell 中,使用此命令:
```bash
PS> $env:DEBUG='myapp:*'; npm start
```
-Then, load `http://localhost:3000/` in your browser to access the app.
+然后在浏览器中加载 `http://localhost:3000/` 以访问该应用。
-The generated app has the following directory structure:
+生成的应用具有以下目录结构:
```bash
.
@@ -119,7 +119,7 @@ The generated app has the following directory structure:
-The app structure created by the generator is just one of many ways to structure Express apps.
-Feel free to use this structure or modify it to best suit your needs.
+生成器创建的应用结构只是 Express 应用多种结构方案中的一种。
+你可以随意使用此结构,或根据你的需求对其进行修改。
diff --git a/src/content/docs/zh-cn/4x/starter/hello-world.mdx b/src/content/docs/zh-cn/4x/starter/hello-world.mdx
index 629d697721..4ecf64e0b0 100644
--- a/src/content/docs/zh-cn/4x/starter/hello-world.mdx
+++ b/src/content/docs/zh-cn/4x/starter/hello-world.mdx
@@ -1,20 +1,17 @@
---
-title: Hello world example
-description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners.
+title: Hello world 示例
+description: 通过构建一个简单的“Hello World”应用来入门 Express.js,展示基础的配置和服务器创建过程,适合初学者学习。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-Embedded below is essentially the simplest Express app you can create. It is a single file app
-— _not_ what you'd get if you use the [Express generator](/starter/generator), which
-creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and
-sub-directories for various purposes.
+下面展示的是一个本质上最简单的 Express 应用。 这是一个单文件应用—而不是使用 [Express 生成器](/en/starter/generator) 所生成的项目结构,后者会创建一个完整应用的脚手架,包含多个 JavaScript 文件、Jade 模板,以及用于不同用途的子目录。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,27 +25,39 @@ app.listen(port, () => {
});
```
-This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
-to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
+```mjs title="index.mjs"
+import express from 'express';
-## Running Locally
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
+该应用启动一个服务器,并在 3000 端口监听连接请求。 当请求根 URL(`/`)或“ _route_”时,该应用会返回“Hello World!”。 对于其他所有路径,它都会返回 **404 Not Found**。
+
+## 本地运行
-First create a directory named `myapp`, change to it and run `npm init`. Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
+首先创建一个名为 `myapp` 的目录,进入该目录并运行 `npm init`。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
-In the `myapp` directory, create a file named `app.js` and copy the code from the example above.
+在 `myapp` 目录中创建一个名为 `app.js` 的文件,并复制上方示例中的代码。
-The `req` (request) and `res` (response) are the exact same objects that Node provides, so you can
-invoke `req.pipe()`, `req.on('data', callback)`, and anything else you would do without Express
-involved.
+`req`(请求)和 `res`(响应)就是 Node 本身提供的同一对象,因此你可以调用 `req.pipe()`、`req.on('data', callback)`,以及在不使用 Express 时会用到的任何其他方法。
-Run the app with the following command:
+使用以下命令运行应用:
```bash
$ node app.js
```
-Then, load `http://localhost:3000/` in a browser to see the output.
+然后,在浏览器中打开 `http://localhost:3000/` 查看输出结果。
diff --git a/src/content/docs/zh-cn/4x/starter/installing.mdx b/src/content/docs/zh-cn/4x/starter/installing.mdx
index fc66c7f9df..059a58b708 100644
--- a/src/content/docs/zh-cn/4x/starter/installing.mdx
+++ b/src/content/docs/zh-cn/4x/starter/installing.mdx
@@ -1,50 +1,42 @@
---
-title: Installing
-description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm.
+title: 安装
+description: 学习如何在 Node.js 环境中安装 Express.js,包括创建项目目录以及使用 npm 管理依赖项。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Before you begin, make sure you have [Node.js](https://nodejs.org/) 0.10 or higher installed. Then, create a directory for your application and navigate into it.
+开始之前,请确保已安装 [Node.js](https://nodejs.org/) 0.10 或更高版本。 然后,为你的应用创建一个目录并进入该目录。
```bash
mkdir myapp
cd myapp
```
-Use the `npm init` command to create a `package.json` file for your application.
-For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
+使用 `npm init` 命令为你的应用创建一个 `package.json` 文件。
+有关 `package.json` 工作机制的更多信息,请参阅 [npm 的 package.json 处理细则](https://docs.npmjs.com/files/package.json)。
-```bash
-npm init
-```
+
-This command prompts you for a number of things, such as the name and version of your application.
-For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
+该命令会提示你输入一些信息,例如应用的名称和版本号。
+目前,你可以直接按回车键接受大多数默认值,但以下情况除外:
```
entry point: (index.js)
```
-Enter `app.js`, or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name.
+输入 `app.js`,或者你希望作为主文件的其他名称。 如果希望使用 `index.js`,直接按回车键接受系统建议的默认文件名即可。
-Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
+现在,在 `myapp` 目录中安装 Express,并将其保存到依赖列表中。 举个例子:
-```bash
-npm install express
-```
+
-To install Express temporarily and not add it to the dependencies list:
+如果只是临时安装 Express,而不将其加入依赖列表:
-```bash
-npm install express --no-save
-```
+
-By default with version npm 5.0+, `npm install` adds the module to the `dependencies` list in the
-`package.json` file; with earlier versions of npm, you must specify the `--save` option
-explicitly. Then, afterwards, running `npm install` in the app directory will automatically
-install modules in the dependencies list.
+默认情况下,在 npm 5.0 及以上版本中,`npm install` 会将模块添加到 `dependencies` 列表中。 之后,在应用目录中运行 `npm install` 将会自动安装 `dependencies` 列表中的模块。
diff --git a/src/content/docs/zh-cn/4x/starter/static-files.mdx b/src/content/docs/zh-cn/4x/starter/static-files.mdx
index 0f2c8280b1..81262e4ac3 100644
--- a/src/content/docs/zh-cn/4x/starter/static-files.mdx
+++ b/src/content/docs/zh-cn/4x/starter/static-files.mdx
@@ -1,28 +1,28 @@
---
-title: Serving static files in Express
-description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware.
+title: 在 Express 中托管静态文件
+description: 了解如何在 Express.js 应用中使用内置的 `static` 中间件托管图片、CSS 和 JavaScript 等静态文件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express.
+要托管图片、CSS 文件和 JavaScript 文件等静态文件,需使用 Express 内置的 `express.static` 中间件函数。
-The function signature is:
+该函数的签名为:
```js
express.static(root, [options]);
```
-The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/5x/api#express.static).
+`root` 参数用于指定托管静态资源的根目录。
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
-For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
+例如,使用以下代码来托管 `public` 目录中的图片、CSS 文件和 JavaScript 文件:
```js
app.use(express.static('public'));
```
-Now, you can load the files that are in the `public` directory:
+现在,你就可以加载 `public` 目录中的文件了:
```text
http://localhost:3000/images/kitten.jpg
@@ -34,19 +34,18 @@ http://localhost:3000/hello.html
-Express looks up the files relative to the static directory, so the name of the static directory
-is not part of the URL.
+Express 查找文件时是相对于静态目录的,因此静态目录名称不会出现在 URL 中。
-To use multiple static assets directories, call the `express.static` middleware function multiple times:
+若要使用多个静态资源目录,需多次调用 `express.static` 中间件函数:
```js
app.use(express.static('public'));
app.use(express.static('files'));
```
-Express looks up the files in the order in which you set the static directories with the `express.static` middleware function.
+Express 会按照你使用 `express.static` 中间件设置静态目录的**顺序**来查找文件。
@@ -56,13 +55,13 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/5x/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
```
-Now, you can load the files that are in the `public` directory from the `/static` path prefix.
+现在,你可以通过 `/static` 路径前缀加载存放在 `public` 目录中的文件。
```text
http://localhost:3000/static/images/kitten.jpg
@@ -72,11 +71,17 @@ http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
```
-However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
+但是,你提供给 `express.static` 函数的路径是相对于你启动 `node` 进程的目录而言的。 如果你从其他目录启动 Express 应用,使用你要托管的目录的绝对路径会更安全:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/zh-cn/5x/advanced/developing-template-engines.md b/src/content/docs/zh-cn/5x/advanced/developing-template-engines.md
index 6e9710fbc5..e5d2858638 100644
--- a/src/content/docs/zh-cn/5x/advanced/developing-template-engines.md
+++ b/src/content/docs/zh-cn/5x/advanced/developing-template-engines.md
@@ -1,11 +1,11 @@
---
-title: Developing template engines for Express
-description: Learn how to develop custom template engines for Express.js using app.engine(), with examples on creating and integrating your own template rendering logic.
+title: 为 Express 开发模板引擎
+description: 学习如何使用 app.engine() 为 Express.js 开发自定义模板引擎,并通过示例讲解如何创建和集成自定义模板渲染逻辑。
---
-Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.
+使用 `app.engine(ext, callback)` 方法创建自定义模板引擎。 `ext` 表示文件扩展名,`callback` 是模板引擎函数,它接收以下参数:文件路径、选项对象以及回调函数。
-The following code is an example of implementing a very simple template engine for rendering `.ntl` files.
+以下代码示例实现了一个极简的模板引擎,用于渲染 `.ntl` 文件。
```js
const fs = require('fs'); // this engine requires the fs module
@@ -25,14 +25,14 @@ app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine
```
-Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content.
+你的应用现在将能够渲染 `.ntl` 文件。 在 `views` 目录中创建一个名为 `index.ntl` 的文件,并写入以下内容。
```pug
#title#
#message#
```
-Then, create the following route in your app.
+然后在你的应用中创建如下路由。
```js
app.get('/', (req, res) => {
@@ -40,4 +40,4 @@ app.get('/', (req, res) => {
});
```
-When you make a request to the home page, `index.ntl` will be rendered as HTML.
+当你向主页发起请求时,`index.ntl` 文件会被渲染为 HTML。
diff --git a/src/content/docs/zh-cn/5x/guide/behind-proxies.mdx b/src/content/docs/zh-cn/5x/guide/behind-proxies.mdx
index 86568424e4..b86d705e8e 100644
--- a/src/content/docs/zh-cn/5x/guide/behind-proxies.mdx
+++ b/src/content/docs/zh-cn/5x/guide/behind-proxies.mdx
@@ -1,21 +1,19 @@
---
-title: Express behind proxies
-description: Learn how to configure Express.js applications to work correctly behind reverse proxies, including using the trust proxy setting to handle client IP addresses.
+title: 运行在反向代理后的 Express 应用
+description: 学习如何配置 Express.js 应用使其在反向代理后正常工作,包括使用 **trust proxy** 设置来获取客户端真实 IP 地址。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client's IP address may instead show an internal IP address of the reverse proxy.
+在反向代理后运行 Express 应用时,部分 Express API 的返回值可能与预期不符。 为此可配置应用设置项 `trust proxy` ,让 Express 接口能够获取反向代理转发的请求信息。 最常见的问题是,用于获取客户端IP的Express接口,获取到的IP实为反向代理的内网地址。
-When configuring the `trust proxy` setting, it is important to understand the exact setup of the
-reverse proxy. Since this setting will trust values provided in the request, it is important that
-the combination of the setting in Express matches how the reverse proxy operates.
+配置`trust proxy`设置时,务必清楚反向代理的具体部署架构。 由于该配置会信任请求中携带的参数值,因此Express中的配置必须与反向代理的运行方式完全匹配,这一点至关重要。
-The application setting `trust proxy` may be set to one of the values listed in the following table.
+应用设置项 `trust proxy` 可设置为下表所列值之一。
| Type | Value |
@@ -23,25 +21,25 @@ The application setting `trust proxy` may be set to one of the values listed in
| Boolean |
-If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-For` header.
+若设为 `true`,客户端IP地址将被认定为`X-Forwarded-For`请求头中最左侧的条目。
-If `false`, the app is understood as directly facing the client and the client's IP address is derived from `req.socket.remoteAddress`. This is the default setting.
+若设为 `false`,表示应用直接面向客户端,客户端IP地址取自 `req.socket.remoteAddress`。 该值为默认配置。
-
-When setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`, otherwise it may be possible for the client to provide any value.
+
+将此项设为 `true` 时,务必确保最后一级受信反向代理会**移除/覆盖**以下所有HTTP请求头:`X-Forwarded-For`、`X-Forwarded-Host` 和 `X-Forwarded-Proto`,否则客户端可能伪造任意值。
|
| IP addresses |
-An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:
+可配置为一个IP地址、一个子网,或由多个IP地址和子网组成的数组,用于指定可信任的反向代理。 以下列表展示了预配置的子网名称:
- loopback - `127.0.0.1/8`, `::1/128`
- linklocal - `169.254.0.0/16`, `fe80::/10`
- uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
-You can set IP addresses in any of the following ways:
+你可通过以下任意方式设置IP地址:
```js
app.set('trust proxy', 'loopback'); // specify a single subnet
@@ -50,24 +48,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal'); // specify multiple
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); // specify multiple subnets as an array
```
-When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address.
+指定后,这些IP地址或子网将被排除在地址判定流程之外,最靠近应用服务器的非受信IP将被认定为客户端IP地址。 其工作原理是检查 `req.socket.remoteAddress` 是否为可信任地址。 若为可信地址,则从右向左检查`X-Forwarded-For`中的每个地址,直至找到第一个非可信地址。
|
| Number |
-Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy.
+使用距离 Express 应用不超过 n 个网络跳数的地址。 `req.socket.remoteAddress` 为第一跳,其余地址从`X-Forwarded-For`请求头中从右向左查找。 取值为 `0` 表示:第一个非可信地址就是 `req.socket.remoteAddress`,即不存在反向代理。
-
-When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value.
+
+使用该配置时,必须确保不存在多条长度不同的路径到达 Express 应用,避免客户端与服务的跳数少于配置值,否则客户端可能伪造任意值。
|
| Function |
-Custom trust implementation.
+自定义信任实现。
```js
app.set('trust proxy', (ip) => {
@@ -82,7 +80,7 @@ app.set('trust proxy', (ip) => {
|
-Enabling `trust proxy` will have the following impact:
+启用 `trust proxy` 会产生以下影响:
-
@@ -90,8 +88,8 @@ Enabling `trust proxy` will have the following impact:
`X-Forwarded-Host` header, which can be set by the client or by the proxy.
-
- `X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or
- `http` or even an invalid name. This value is reflected by [req.protocol](/api#req.protocol).
+ 反向代理可通过设置`X-Forwarded-Proto`请求头,告知应用当前请求协议是`https`、`http`,或是非法协议标识。
+ This value is reflected by [req.protocol](/api#req.protocol).
-
The [req.ip](/api#req.ip) and [req.ips](/api#req.ips) values are populated based on the socket
@@ -99,4 +97,4 @@ Enabling `trust proxy` will have the following impact:
-The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
+`trust proxy` 配置项依托[proxy-addr](https://www.npmjs.com/package/proxy-addr)包实现。 更多详情请参阅该模块文档。
diff --git a/src/content/docs/zh-cn/5x/guide/debugging.mdx b/src/content/docs/zh-cn/5x/guide/debugging.mdx
index 24bbce3510..beb9dc3f3b 100644
--- a/src/content/docs/zh-cn/5x/guide/debugging.mdx
+++ b/src/content/docs/zh-cn/5x/guide/debugging.mdx
@@ -1,18 +1,17 @@
---
-title: Debugging Express
-description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting.
+title: 调试 Express
+description: 通过设置 DEBUG 环境变量来开启并使用 Express.js 应用的调试日志,以便更好地排查问题。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-To see all the internal logs used in Express, set the `DEBUG` environment variable to
-`express:*` when launching your app.
+若要查看 Express 中使用的所有内部日志,请在启动应用时将 `DEBUG` 环境变量设置为 `express:*`。
```bash
$ DEBUG=express:* node index.js
```
-On Windows, use the corresponding command.
+在 Windows 系统上,请使用对应的命令。
```bash
> $env:DEBUG = "express:*"; node index.js
@@ -64,7 +63,7 @@ $ DEBUG=express:* node ./bin/www
express:router:layer new / +0ms
```
-When a request is then made to the app, you will see the logs specified in the Express code:
+随后向该应用发送请求时,你会看到 Express 代码中指定的日志:
```bash
express:router dispatching GET / +4h
@@ -84,40 +83,39 @@ When a request is then made to the app, you will see the logs specified in the E
express:view render "/projects/example/views/index.pug" +1ms
```
-To see the logs only from the router implementation, set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on.
+若仅查看来自路由实现的日志,请将 `DEBUG` 的值设置为 `express:router`。 同理,若仅查看来自应用实现的日志,请将 `DEBUG` 的值设置为 `express:application`,以此类推。
-## Applications generated by `express`
+## 由 `express` 生成的应用
-An application generated by the `express` command uses the `debug` module and its debug namespace is scoped to the name of the application.
+由 `express` 命令生成的应用会使用 `debug` 模块,且其调试命名空间的作用域限定为应用名称。
-For example, if you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:
+例如,如果你使用 `$ express sample-app` 命令生成了应用,可以通过以下命令启用调试语句:
```bash
$ DEBUG=sample-app:* node ./bin/www
```
-You can specify more than one debug namespace by assigning a comma-separated list of names:
+你可以通过指定以英文逗号分隔的名称列表,来启用多个调试命名空间:
```bash
$ DEBUG=http,mail,express:* node index.js
```
-## Advanced options
+## 高级选项
-When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:
+在通过 Node.js 运行时,你可以设置若干环境变量来更改调试日志的行为:
-| Name | Purpose |
-| ------------------- | ------------------------------------------------- |
-| `DEBUG` | Enables/disables specific debugging namespaces. |
-| `DEBUG_COLORS` | Whether or not to use colors in the debug output. |
-| `DEBUG_DEPTH` | Object inspection depth. |
-| `DEBUG_FD` | File descriptor to write debug output to. |
-| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
+| Name | Purpose |
+| ------------------- | ------------------------------ |
+| `DEBUG` | 启用或禁用特定的调试命名空间。 |
+| `DEBUG_COLORS` | 是否在调试输出中使用彩色显示。 |
+| `DEBUG_DEPTH` | 对象检查深度。 |
+| `DEBUG_FD` | 用于写入调试输出的文件描述符。 |
+| `DEBUG_SHOW_HIDDEN` | 显示被检查对象的隐藏属性。 |
-The environment variables beginning with `DEBUG_` end up being converted into an Options object
-that gets used with `%o`/`%O` formatters. See the Node.js documentation for
+以 `DEBUG_` 开头的环境变量最终会被转换为一个选项对象,供 `%o`/`%O` 格式化符使用。 See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) for the complete
list.
diff --git a/src/content/docs/zh-cn/5x/guide/error-handling.mdx b/src/content/docs/zh-cn/5x/guide/error-handling.mdx
index 507232b013..c9200134dc 100644
--- a/src/content/docs/zh-cn/5x/guide/error-handling.mdx
+++ b/src/content/docs/zh-cn/5x/guide/error-handling.mdx
@@ -1,22 +1,17 @@
---
-title: Error Handling
-description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications.
+title: 错误处理
+description: 了解 Express.js 如何处理同步和异步代码中的错误,并学习为你的应用实现自定义错误处理中间件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Error Handling_ refers to how Express catches and processes errors that
-occur both synchronously and asynchronously. Express comes with a default error
-handler so you don't need to write your own to get started.
+错误处理是指 Express 如何捕获并处理同步代码与异步代码中发生的错误。 Express 自带默认错误处理器,因此你在开发初期无需自行编写。
-## Catching Errors
+## 错误捕获
-It's important to ensure that Express catches all errors that occur while
-running route handlers and middleware.
+确保 Express 能够捕获路由处理器和中间件运行时发生的所有错误,这一点至关重要。
-Errors that occur in synchronous code inside route handlers and middleware
-require no extra work. If synchronous code throws an error, then Express will
-catch and process it. For example:
+路由处理函数与中间件内同步代码产生的错误无需额外处理。 倘若同步代码抛出错误,Express 会捕获并处理该错误。 举个例子:
```js
app.get('/', (req, res) => {
@@ -24,9 +19,7 @@ app.get('/', (req, res) => {
});
```
-For errors returned from asynchronous functions invoked by route handlers
-and middleware, you must pass them to the `next()` function, where Express will
-catch and process them. For example:
+对于路由处理函数和中间件调用的异步函数所返回的错误,你必须将它们传递给 `next()` 函数,Express 会在该函数中捕获并处理这些错误。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -40,9 +33,8 @@ app.get('/', (req, res, next) => {
});
```
-Starting with Express 5, route handlers and middleware that return a Promise
-will call `next(value)` automatically when they reject or throw an error.
-For example:
+从 Express 5 开始,返回 Promise 的路由处理程序和中间件在拒绝(reject)或抛出错误时,将自动调用 `next(value)`。
+举个例子:
```js
app.get('/user/:id', async (req, res, next) => {
@@ -51,16 +43,11 @@ app.get('/user/:id', async (req, res, next) => {
});
```
-If `getUserById` throws an error or rejects, `next` will be called with either
-the thrown error or the rejected value. If no rejected value is provided, `next`
-will be called with a default Error object provided by the Express router.
+如果 `getUserById` 抛出错误或被拒绝(reject),`next` 将会使用抛出的错误或被拒绝的值来调用。 如果未提供拒绝值,则会使用 Express 路由内置的默认错误对象调用 `next`。
-If you pass anything to the `next()` function (except the string `'route'`),
-Express regards the current request as being an error and will skip any
-remaining non-error handling routing and middleware functions.
+如果向 `next()` 传入任意参数(字符串 `'route'` 除外),Express 会将当前请求视作出错,并跳过后续所有非错误处理的路由与中间件函数。
-If the callback in a sequence provides no data, only errors, you can simplify
-this code as follows:
+如果序列中的回调函数不返回数据、仅返回错误,你可以将代码简化如下:
```js
app.get('/', [
@@ -73,12 +60,9 @@ app.get('/', [
]);
```
-In the above example, `next` is provided as the callback for `fs.writeFile`,
-which is called with or without errors. If there is no error, the second
-handler is executed, otherwise Express catches and processes the error.
+在上述示例中,`next` 被作为 `fs.writeFile` 的回调函数传入,无论是否存在错误都会被调用。 若无错误,则执行第二个处理函数;否则 Express 会捕获并处理该错误。
-You must catch errors that occur in asynchronous code invoked by route handlers or
-middleware and pass them to Express for processing. For example:
+你必须捕获在路由处理程序或中间件中调用的异步代码里发生的错误,并将它们传递给 Express 进行处理。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -92,13 +76,9 @@ app.get('/', (req, res, next) => {
});
```
-The above example uses a `try...catch` block to catch errors in the
-asynchronous code and pass them to Express. If the `try...catch`
-block were omitted, Express would not catch the error since it is not part of the synchronous
-handler code.
+上述示例使用 `try...catch` 代码块捕获异步代码中的错误,并将其传递给 Express。 如果省略 `try...catch` 代码块,Express 将无法捕获该错误,因为它不属于同步处理程序代码的一部分。
-Use promises to avoid the overhead of the `try...catch` block or when using functions
-that return promises. For example:
+使用 Promise 来避免 `try...catch` 代码块的开销,或在使用返回 Promise 的函数时采用此方式。 举个例子:
```js
app.get('/', (req, res, next) => {
@@ -110,12 +90,9 @@ app.get('/', (req, res, next) => {
});
```
-Since promises automatically catch both synchronous errors and rejected promises,
-you can simply provide `next` as the final catch handler and Express will catch errors,
-because the catch handler is given the error as the first argument.
+由于 Promise 会自动捕获同步错误和被拒绝的 Promise,你只需将 `next` 作为最终的 catch 处理程序传入即可,Express 会捕获错误,因为 catch 处理程序会将错误作为第一个参数传入。
-You could also use a chain of handlers to rely on synchronous error
-catching, by reducing the asynchronous code to something trivial. For example:
+你也可以使用处理程序链,将异步代码简化为简单逻辑,从而依靠同步错误捕获机制。 举个例子:
```js
app.get('/', [
@@ -132,50 +109,32 @@ app.get('/', [
]);
```
-The above example has a couple of trivial statements from the `readFile`
-call. If `readFile` causes an error, then it passes the error to Express, otherwise you
-quickly return to the world of synchronous error handling in the next handler
-in the chain. Then, the example above tries to process the data. If this fails, then the
-synchronous error handler will catch it. If you had done this processing inside
-the `readFile` callback, then the application might exit and the Express error
-handlers would not run.
+上述示例包含几条来自 `readFile` 调用的简单语句。 如果 `readFile` 引发错误,则会将错误传递给 Express;否则你将迅速回到处理程序链中下一个处理函数的同步错误处理流程。 然后,上述示例会尝试处理数据。 如果此过程失败,同步错误处理程序将会捕获该错误。 如果你将此处理逻辑写在 `readFile` 回调函数内部,应用程序可能会直接退出,Express 错误处理程序将无法执行。
-Whichever method you use, if you want Express error handlers to be called in and the
-application to survive, you must ensure that Express receives the error.
+无论你使用哪种方法,若希望 Express 错误处理程序被调用且应用程序持续运行,必须确保 Express 能够接收到错误。
-## The default error handler
+## 默认错误处理程序
-Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
+Express 内置了错误处理程序,可处理应用中可能出现的所有错误。 这个默认的错误处理中间件函数会被添加到中间件函数栈的末尾。
-If you pass an error to `next()` and you do not handle it in a custom error
-handler, it will be handled by the built-in error handler; the error will be
-written to the client with the stack trace. The stack trace is not included
-in the production environment.
+如果你将错误传递给 `next()`,但未在自定义错误处理程序中处理它,该错误将由内置错误处理程序处理;错误信息和堆栈追踪信息会被返回给客户端。 生产环境中不会包含堆栈追踪信息。
-Set the environment variable `NODE_ENV` to `production`, to run the app in production mode.
+将环境变量 `NODE_ENV` 设置为 `production`,即可在生产模式下运行应用。
-When an error is written, the following information is added to the
-response:
+当错误信息被输出时,响应中会附加以下信息:
-- The `res.statusCode` is set from `err.status` (or `err.statusCode`). If
- this value is outside the 4xx or 5xx range, it will be set to 500.
-- The `res.statusMessage` is set according to the status code.
-- The body will be the HTML of the status code message when in production
- environment, otherwise will be `err.stack`.
-- Any headers specified in an `err.headers` object.
+- `res.statusCode` 会从 `err.status`(或 `err.statusCode`)中获取设置。 如果该值不在 4xx 或 5xx 范围内,则会被设置为 500。
+- `res.statusMessage` 会根据状态码自动设置。
+- 生产环境中,响应主体会展示状态码信息的 HTML 页面;其他环境下则会展示 `err.stack` 堆栈信息。
+- `err.headers` 对象中定义的所有响应头。
-If you call `next()` with an error after you have started writing the
-response (for example, if you encounter an error while streaming the
-response to the client), the Express default error handler closes the
-connection and fails the request.
+如果在开始向客户端写入响应数据后调用带错误参数的`next()`(例如向客户端流式返回响应时出错),Express 默认错误处理程序会关闭连接并终止本次请求。
-So when you add a custom error handler, you must delegate to
-the default Express error handler, when the headers
-have already been sent to the client:
+因此,当你添加自定义错误处理程序时,若响应头已发送至客户端,必须将错误委托给 Express 默认错误处理程序处理:
```js
function errorHandler(err, req, res, next) {
@@ -187,16 +146,14 @@ function errorHandler(err, req, res, next) {
}
```
-Note that the default error handler can get triggered if you call `next()` with an error
-in your code more than once, even if custom error handling middleware is in place.
+注意:即便已配置自定义错误处理中间件,若代码中多次传入错误调用`next()`,仍可能触发默认错误处理程序。
Other error handling middleware can be found at [Express middleware](/resources/middleware).
-## Writing error handlers
+## 编写错误处理程序
-Define error-handling middleware functions in the same way as other middleware functions,
-except error-handling functions have four arguments instead of three:
-`(err, req, res, next)`. For example:
+错误处理中间件函数的定义方式与其他中间件函数基本相同,区别在于错误处理函数包含四个参数而非三个:
+`(err, req, res, next)`。 举个例子:
```js
app.use((err, req, res, next) => {
@@ -205,9 +162,9 @@ app.use((err, req, res, next) => {
});
```
-You define error-handling middleware last, after other `app.use()` and routes calls; for example:
+你需要在其他 `app.use()` 调用和路由之后,最后定义错误处理中间件;例如:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,14 +180,27 @@ app.use((err, req, res, next) => {
});
```
-Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
-For organizational (and higher-level framework) purposes, you can define
-several error-handling middleware functions, much as you would with
-regular middleware functions. For example, to define an error-handler
-for requests made by using `XHR` and those without:
+中间件函数内的响应可以是任意格式,例如 HTML 错误页面、简单消息或 JSON 字符串。
-```js
+出于组织结构(以及高级框架)的目的,你可以定义多个错误处理中间件函数,这与你使用常规中间件函数的方式非常相似。 例如,为使用 `XHR` 发起的请求和未使用 `XHR` 发起的请求分别定义错误处理程序:
+
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +216,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
@@ -279,7 +265,7 @@ function errorHandler(err, req, res, next) {
}
```
-If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. For example:
+If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. 举个例子:
```js
app.get(
diff --git a/src/content/docs/zh-cn/5x/guide/overriding-express-api.md b/src/content/docs/zh-cn/5x/guide/overriding-express-api.md
index 6167938c4d..8027e5c644 100644
--- a/src/content/docs/zh-cn/5x/guide/overriding-express-api.md
+++ b/src/content/docs/zh-cn/5x/guide/overriding-express-api.md
@@ -1,20 +1,20 @@
---
-title: Overriding the Express API
-description: Discover how to customize and extend the Express.js API by overriding methods and properties on the request and response objects using prototypes.
+title: 重写Express API
+description: 了解如何通过原型重写请求和响应对象上的方法与属性,来自定义并扩展 Express.js API。
---
-The Express API consists of various methods and properties on the request and response objects. These are inherited by prototype. There are two extension points for the Express API:
+Express API 由请求对象和响应对象上的多种方法与属性组成。 这些内容通过原型继承。 Express API 有两个扩展点:
-1. The global prototypes at `express.request` and `express.response`.
-2. App-specific prototypes at `app.request` and `app.response`.
+1. `express.request` 和 `express.response` 上的全局原型。
+2. 应用专属原型位于 `app.request` 和 `app.response`。
-Altering the global prototypes will affect all loaded Express apps in the same process. If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app.
+修改全局原型会影响同一进程中所有已加载的 Express 应用。 如果需要,你可以在创建新应用后仅修改应用专属原型,从而实现仅针对当前应用的修改。
## Methods
-You can override the signature and behavior of existing methods with your own, by assigning a custom function.
+你可以通过分配自定义函数,使用自己的实现重写现有方法的签名和行为。
-Following is an example of overriding the behavior of [res.sendStatus](/4x/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
@@ -23,9 +23,9 @@ app.response.sendStatus = function (statusCode, type, message) {
};
```
-The above implementation completely changes the original signature of `res.sendStatus`. It now accepts a status code, encoding type, and the message to be sent to the client.
+上述实现彻底更改了`res.sendStatus`原本的方法签名。 该方法现在可接收状态码、编码类型以及要发送给客户端的消息。
-The overridden method may now be used this way:
+重写后的方法现在可以这样使用:
```js
res.sendStatus(404, 'application/json', '{"error":"resource not found"}');
@@ -33,16 +33,16 @@ res.sendStatus(404, 'application/json', '{"error":"resource not found"}');
## Properties
-Properties in the Express API are either:
+Express API 中的属性分为两类:
-1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`)
-2. Defined as getters (ex: `req.secure`, `req.ip`)
+1. 赋值属性(例如:`req.baseUrl`、`req.originalUrl`)
+2. 取值器定义属性(例如:`req.secure`、`req.ip`)
-Since properties under category 1 are dynamically assigned on the `request` and `response` objects in the context of the current request-response cycle, their behavior cannot be overridden.
+由于第一类属性是在当前请求-响应周期的上下文中动态赋值到`request`和`response`对象上的,因此无法重写其行为。
-Properties under category 2 can be overwritten using the Express API extensions API.
+第二类属性可通过 Express API 扩展接口进行重写。
-The following code rewrites how the value of `req.ip` is to be derived. Now, it simply returns the value of the `Client-IP` request header.
+以下代码重写了`req.ip`值的获取方式。 现在,它仅返回 `Client-IP` 请求头的值。
```js
Object.defineProperty(app.request, 'ip', {
@@ -56,9 +56,9 @@ Object.defineProperty(app.request, 'ip', {
## Prototype
-In order to provide the Express API, the request/response objects passed to Express (via `app(req, res)`, for example) need to inherit from the same prototype chain. By default, this is `http.IncomingRequest.prototype` for the request and `http.ServerResponse.prototype` for the response.
+为了提供 Express API,传递给 Express 的请求/响应对象(例如通过 `app(req, res)`)需要继承自相同的原型链。 默认情况下,请求对象继承自 `http.IncomingRequest.prototype`,响应对象继承自 `http.ServerResponse.prototype`。
-Unless necessary, it is recommended that this be done only at the application level, rather than globally. Also, take care that the prototype that is being used matches the functionality as closely as possible to the default prototypes.
+除非必要,否则建议仅在应用层面执行此操作,而非全局层面。 此外,请注意所使用的原型需尽可能与默认原型的功能保持一致。
```js
// Use FakeRequest and FakeResponse in place of http.IncomingRequest and http.ServerResponse
diff --git a/src/content/docs/zh-cn/5x/guide/routing.mdx b/src/content/docs/zh-cn/5x/guide/routing.mdx
index c24b1f6395..90eae89762 100644
--- a/src/content/docs/zh-cn/5x/guide/routing.mdx
+++ b/src/content/docs/zh-cn/5x/guide/routing.mdx
@@ -1,27 +1,26 @@
---
title: Routing
-description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing.
+description: 学习如何在 Express.js 应用中定义和使用路由,包括路由方法、路由路径、参数,以及使用 Router 实现模块化路由。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Routing_ refers to how an application's endpoints (URIs) respond to client requests.
+**路由**是指应用程序的端点(URI)如何响应客户端的请求。
For an introduction to routing, see [Basic routing](/starter/basic-routing).
-You define routing using methods of the Express `app` object that correspond to HTTP methods;
-for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+你可以使用 Express `app` 对象中与 HTTP 方法对应的方法来定义路由;
+例如,`app.get()` 处理 GET 请求,`app.post` 处理 POST 请求。 For a full list,
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. 换句话说,应用程序会“监听”匹配指定路由和方法的请求,当检测到匹配时,就会调用指定的回调函数。
-In fact, the routing methods can have more than one callback function as arguments.
-With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
-to the next callback.
+事实上,路由方法可以接受多个回调函数作为参数。
+对于多个回调函数,务必在回调函数中传入`next`作为参数,然后在函数体内调用`next()`,将控制权传递给下一个回调函数。
-The following code is an example of a very basic route.
+以下代码是一个非常基础的路由示例。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,11 +30,22 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
-A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
+路由方法源于 HTTP 方法之一,附加在 `express` 类的实例上。
-The following code is an example of routes that are defined for the `GET` and the `POST` methods to the root of the app.
+以下代码示例展示了为应用根路径定义的 `GET` 和 `POST` 方法路由。
```js
// GET method route
@@ -49,10 +59,10 @@ app.post('/', (req, res) => {
});
```
-Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+Express 支持对应于所有 HTTP 请求方法的方法:get、post 等。
+For a full list, see [app.METHOD](/api/application#appmethod).
-There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
+有一种特殊的路由方法 **app.all()**,用于为某一路径加载所有 HTTP 请求方法通用的中间件函数。 例如,无论使用 `GET`、`POST`、`PUT`、`DELETE` 还是 [http 模块](https://nodejs.org/api/http.html#http_http_methods)。
```js
app.all('/secret', (req, res, next) => {
@@ -63,20 +73,20 @@ app.all('/secret', (req, res, next) => {
## Route paths
-Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings or regular expressions.
+路由路径与请求方法结合,定义了可以接收请求的端点。 路由路径可以是字符串或正则表达式。
-Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) v8 for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.
-[Express Playground Router](https://bjohansebas.github.io/playground-router/) is a handy tool for testing basic Express routes, although it does not support pattern matching.
+Express 使用 [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) v8 匹配路由路径;有关定义路由路径的所有可用方式,请参阅 path-to-regexp 文档。
+[Express Playground Router](https://bjohansebas.github.io/playground-router/) 是一款便捷的 Express 基础路由在线测试工具,但该工具不支持路由规则匹配。
### String paths
-String paths match requests exactly. The dot (`.`) and hyphen (`-`) are interpreted literally.
+字符串路径会精确匹配请求。 点(`.`)和连字符(`-`)会按字面含义解析。
-Query strings are not part of the route path.
+查询字符串不属于路由路径的一部分
```js
app.get('/', (req, res) => {
@@ -94,7 +104,7 @@ app.get('/random.text', (req, res) => {
### Wildcards
-Wildcards match any path after a prefix. They must have a name, just like route parameters, and are captured as arrays of path segments.
+通配符可以匹配前缀后的任意路径。 它们必须像路由参数一样拥有名称,并且会被捕获为**路径片段组成的数组**。
```js
app.get('/files/*filepath', (req, res) => {
@@ -105,7 +115,7 @@ app.get('/files/*filepath', (req, res) => {
});
```
-To also match the root path, wrap the wildcard in braces:
+若要同时匹配根路径,请将通配符用花括号包裹:
```js
// Matches / , /foo , /foo/bar , etc.
@@ -118,7 +128,7 @@ app.get('/{*splat}', (req, res) => {
### Optional segments
-Use braces to define optional segments in a route path. When the segment is not present, the parameter is omitted from `req.params`.
+使用花括号在路由路径中定义可选片段。 当该片段不存在时,该参数会从 `req.params` 中省略。
```js
app.get('/:file{.:ext}', (req, res) => {
@@ -130,13 +140,13 @@ app.get('/:file{.:ext}', (req, res) => {
-The characters `?`, `+`, `*`, `[]`, and `()` are reserved and cannot be used as literal characters in route paths. Use `\` to escape them if needed.
+字符 `?`、`+`、`*`、`[]` 和 `()` 为保留字符,不能在路由路径中用作字面字符。 如有需要,可使用`\`对其进行转义。
### Regular expressions
-You can also use regular expressions as route paths. This is useful when you need more complex matching logic.
+你也可以将正则表达式用作路由路径。 当你需要更复杂的匹配逻辑时,这种方式十分实用。
```js
// Matches any path containing "a"
@@ -152,7 +162,7 @@ app.get(/.*fly$/, (req, res) => {
## Route parameters
-Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys.
+路由参数是命名式URL片段,用于捕获URL中对应位置所指定的值。 捕获的值会存入`req.params`对象,路径中定义的路由参数名作为该对象对应的键名。
```
Route path: /users/:userId/books/:bookId
@@ -160,7 +170,7 @@ Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
```
-To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
+若要使用路由参数定义路由,只需如下所示在路由路径中指定路由参数即可。
```js
app.get('/users/:userId/books/:bookId', (req, res) => {
@@ -170,11 +180,11 @@ app.get('/users/:userId/books/:bookId', (req, res) => {
-The name of route parameters must be made up of "word characters" ([A-Za-z0-9_]).
+路由参数的名称必须由“单词字符”([A-Za-z0-9_])组成。
-Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes.
+由于连字符(`-`)和点号(`.`)按字面解析,因此可结合路由参数实现实用的匹配需求。
```
Route path: /flights/:from-:to
@@ -190,14 +200,14 @@ req.params: { "genus": "Prunus", "species": "persica" }
-Regexp characters are not supported in route paths. Use an array of paths or regular expressions instead.
+路由路径中不支持正则表达式字符。 请改用路径数组或正则表达式。
See the [path route matching syntax](/guide/migrating-5#path-syntax) for more information.
## Route handlers
-You can provide multiple callback functions that behave like [middleware](/guide/using-middleware) to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
+You can provide multiple callback functions that behave like [middleware](/guide/using-middleware) to handle a request. 唯一的例外是这些回调函数可以调用 `next('route')` 来跳过剩余的路由回调。 你可以通过这种机制为路由施加前置条件,如果没有理由继续执行当前路由,则将控制权传递给后续路由。
```js
app.get('/user/:id', (req, res, next) => {
@@ -212,14 +222,14 @@ app.get('/user/:id', (req, res) => {
});
```
-In this example:
+在本示例中:
-- `GET /user/5` → handled by first route → sends "User 5"
-- `GET /user/0` → first route calls `next('route')`, skipping to the next matching `/user/:id` route
+- `GET /user/5` → 由第一个路由处理 → 返回 "User 5"
+- `GET /user/0` → 第一个路由调用 `next('route')`,跳转到下一个匹配的 `/user/:id` 路由
-Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
+路由处理程序可以采用函数、函数数组或二者结合的形式,如下示例所示。
-A single callback function can handle a route. For example:
+单个回调函数即可处理一个路由。 举个例子:
```js
app.get('/example/a', (req, res) => {
@@ -227,7 +237,7 @@ app.get('/example/a', (req, res) => {
});
```
-More than one callback function can handle a route (make sure you specify the `next` object). For example:
+多个回调函数可以处理同一个路由(请确保你指定了 `next` 对象)。 举个例子:
```js
app.get(
@@ -242,7 +252,7 @@ app.get(
);
```
-An array of callback functions can handle a route. For example:
+一个回调函数数组可以处理一个路由。 举个例子:
```js
const cb0 = function (req, res, next) {
@@ -262,7 +272,7 @@ const cb2 = function (req, res) {
app.get('/example/c', [cb0, cb1, cb2]);
```
-A combination of independent functions and arrays of functions can handle a route. For example:
+独立函数与函数数组组合使用即可处理一个路由。 举个例子:
```js
const cb0 = function (req, res, next) {
@@ -290,26 +300,26 @@ app.get(
## Response methods
-The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
+下表中的响应对象(`res`)方法可向客户端发送响应,并终止请求-响应循环。 如果路由处理程序未调用这些方法中的任何一个,客户端请求将一直处于挂起状态。
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | 描述 |
+| ----------------------------------------------- | ---------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | 提示客户端下载一个文件。 |
+| [res.end()](/api/response#resend) | 结束响应流程。 |
+| [res.json()](/api/response#resjson) | 发送 JSON 响应。 |
+| [res.jsonp()](/api/response#resjsonp) | 发送支持 JSONP 的 JSON 响应。 |
+| [res.redirect()](/api/response#resredirect) | 重定向请求。 |
+| [res.render()](/api/response#resrender) | 渲染视图模板。 |
+| [res.send()](/api/response#ressend) | 发送多种类型的响应。 |
+| [res.sendFile()](/api/response#ressendfile) | 以八位字节流的形式发送文件。 |
+| [res.sendStatus()](/api/response#ressendstatus) | 设置响应状态码,并将其字符串表示形式作为响应体发送。 |
## app.route()
-You can create chainable route handlers for a route path by using `app.route()`.
-Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: [Router() documentation](/api/router).
+你可以使用 `app.route()` 为路由路径创建可链式调用的路由处理程序。
+由于路径在单个位置指定,因此创建模块化路由十分有用,同时还能减少冗余和拼写错误。 For more information about routes, see: [Router() documentation](/api/router).
-Here is an example of chained route handlers that are defined by using `app.route()`.
+以下是使用 `app.route()` 定义的链式路由处理程序示例。
```js
app
@@ -327,13 +337,13 @@ app
## express.Router
-Use the `express.Router` class to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app".
+使用 `express.Router` 类创建模块化、可挂载的路由处理程序。 `Router` 实例是一个完整的中间件和路由系统;因此,它通常被称为“迷你应用”。
-The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
+以下示例创建一个路由模块,在其中加载中间件函数、定义若干路由,并将该路由模块挂载到主应用的指定路径上。
-Create a router file named `birds.js` in the app directory, with the following content:
+在应用目录中创建一个名为 `birds.js` 的路由文件,内容如下:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -356,9 +366,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
-Then, load the router module in the app:
+```mjs title="birds.mjs"
+import express from 'express';
-```js
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
+然后,在应用程序中加载路由模块:
+
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -366,9 +400,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
-The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
+应用现在将能够处理指向 `/birds` 和 `/birds/about` 的请求,同时会调用该路由专用的 `timeLog` 中间件函数。
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+但如果父路由 `/birds` 包含路径参数,默认情况下子路由无法访问这些参数。 To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/zh-cn/5x/guide/using-middleware.mdx b/src/content/docs/zh-cn/5x/guide/using-middleware.mdx
index e6b97dd47f..794140f237 100644
--- a/src/content/docs/zh-cn/5x/guide/using-middleware.mdx
+++ b/src/content/docs/zh-cn/5x/guide/using-middleware.mdx
@@ -1,24 +1,25 @@
---
-title: Using middleware
-description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware.
+title: 使用中间件
+description: 了解如何在 Express.js 应用中使用中间件,包括应用级和路由级中间件、错误处理以及集成第三方中间件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
+Express 是一款路由与中间件 Web 框架,自身仅提供极简的基础功能:一个 Express 应用本质上就是一连串中间件函数的调用。
-_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the next middleware function in the application's request-response cycle. 下一个中间件函数通常使用名为`next`的变量来表示。
-Middleware functions can perform the following tasks:
+中间件函数可执行下列任务:
-- Execute any code.
-- Make changes to the request and the response objects.
-- End the request-response cycle.
-- Call the next middleware function in the stack.
+- 执行任意代码。
+- 修改请求对象与响应对象。
+- 终止请求-响应周期。
+- 调用栈中的下一个中间件函数。
-If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
+如果当前中间件函数没有终止请求-响应周期,它必须调用 `next()` 以将控制权传递给下一个中间件函数。 否则,请求将会被挂起。
-An Express application can use the following types of middleware:
+Express 应用可以使用以下类型的中间件:
- [Application-level middleware](#middleware.application)
- [Router-level middleware](#middleware.router)
@@ -26,16 +27,16 @@ An Express application can use the following types of middleware:
- [Built-in middleware](#middleware.built-in)
- [Third-party middleware](#middleware.third-party)
-You can load application-level and router-level middleware with an optional mount path.
-You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
+你可以通过可选的挂载路径加载应用级中间件和路由级中间件。
+你也可以同时加载一系列中间件函数,这会在挂载点处创建中间件系统的一个子栈。
-## Application-level middleware
+## 应用级中间件
Bind application-level middleware to an instance of the [app object](/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
-This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
+本示例展示了一个没有挂载路径的中间件函数。 每当应用接收请求时,该函数都会被执行。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,8 +46,18 @@ app.use((req, res, next) => {
});
```
-This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
-HTTP request on the `/user/:id` path.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
+本示例展示了一个挂载在 `/user/:id` 路径上的中间件函数。 只要是发往 `/user/:id` 路径的任意类型 HTTP 请求,都会执行该中间件函数。
```js
app.use('/user/:id', (req, res, next) => {
@@ -55,7 +66,7 @@ app.use('/user/:id', (req, res, next) => {
});
```
-This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path.
+该示例展示了一条路由及其处理函数(中间件体系)。 该函数处理指向 `/user/:id` 路径的 GET 请求。
```js
app.get('/user/:id', (req, res, next) => {
@@ -63,8 +74,8 @@ app.get('/user/:id', (req, res, next) => {
});
```
-Here is an example of loading a series of middleware functions at a mount point, with a mount path.
-It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path.
+下面是在指定挂载路径的挂载点加载一系列中间件函数的示例。
+该示例演示了一个中间件子栈,会对所有访问 `/user/:id` 路径的各类 HTTP 请求打印请求信息。
```js
app.use(
@@ -80,9 +91,9 @@ app.use(
);
```
-Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.
+路由处理程序支持为同一个路径定义多条路由。 下面的示例为 `/user/:id` 路径的 GET 请求定义了两条路由。 第二条路由不会报错,但永远不会被执行,因为第一条路由已经结束了请求-响应周期。
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
app.get(
@@ -102,16 +113,15 @@ app.get('/user/:id', (req, res, next) => {
});
```
-To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route.
+若要跳过路由中间件栈中剩余的中间件函数,调用 `next('route')` 即可将控制权传递给下一条路由。
-`next('route')` will work only in middleware functions that were loaded by using the
-`app.METHOD()` or `router.METHOD()` functions.
+`next('route')` 仅在通过 `app.METHOD()` 或 `router.METHOD()` 函数加载的中间件函数中生效。
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
app.get(
@@ -134,9 +144,9 @@ app.get('/user/:id', (req, res, next) => {
});
```
-Middleware can also be declared in an array for reusability.
+中间件也可以定义在数组中,实现复用。
-This example shows an array with a middleware sub-stack that handles GET requests to the `/user/:id` path
+该示例展示了一个使用数组封装的中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
```js
function logOriginalUrl(req, res, next) {
@@ -155,19 +165,19 @@ app.get('/user/:id', logStuff, (req, res, next) => {
});
```
-## Router-level middleware
+## 路由级中间件
-Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`.
+路由级中间件的工作方式与应用级中间件完全相同,唯一区别是它绑定到 `express.Router()` 的实例上。
```js
const router = express.Router();
```
-Load router-level middleware by using the `router.use()` and `router.METHOD()` functions.
+通过 `router.use()` 和 `router.METHOD()` 函数加载路由级中间件。
-The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
+下面的示例代码通过路由级中间件,复刻了上方展示的应用级中间件的中间件体系:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +226,61 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
-To skip the rest of the router's middleware functions, call `next('router')`
-to pass control back out of the router instance.
+```mjs title="index.mjs"
+import express from 'express';
-This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
+const app = express();
+const router = express.Router();
-```js
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
+若要跳过当前路由实例中剩余的中间件函数,调用 `next('router')` 即可将控制权交回给路由实例。
+
+该示例展示了一个中间件子栈,用于处理 `/user/:id` 路径的 GET 请求。
+
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,18 +301,37 @@ app.use('/admin', router, (req, res) => {
});
```
-## Error-handling middleware
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
+## 错误处理中间件
-Error-handling middleware always takes _four_ arguments. You must provide four arguments to
-identify it as an error-handling middleware function. Even if you don't need to use the `next`
-object, you must specify it to maintain the signature. Otherwise, the `next` object will be
-interpreted as regular middleware and will fail to handle errors.
+错误处理中间件始终接收**四个**参数。 你必须传入**四个参数**,才能将其标识为错误处理中间件函数。 即使你不需要使用 `next` 对象,也必须声明它,以保持函数签名不变。 否则,`next` 对象会被解析为常规中间件,从而无法处理错误。
-Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`:
+定义错误处理中间件函数的方式与其他中间件一致,唯一区别是它接收四个参数而非三个,标准函数签名为:`(err, req, res, next)`。
```js
app.use((err, req, res, next) => {
@@ -264,30 +342,27 @@ app.use((err, req, res, next) => {
For details about error-handling middleware, see: [Error handling](/guide/error-handling).
-## Built-in middleware
+## 内置中间件
-Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). The middleware
-functions that were previously included with Express are now in separate modules; see [the list of middleware functions](https://github.com/senchalabs/connect#middleware).
+从 4.x 版本开始,Express 不再依赖 [Connect](https://github.com/senchalabs/connect)。 之前包含在 Express 中的中间件函数,现在已经拆分到独立的模块中;查看[中间件函数列表](https://github.com/senchalabs/connect#middleware)。
-Express has the following built-in middleware functions:
+Express 包含以下内置中间件函数:
-- [express.static](/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **注意:此功能仅在 Express 4.16.0 及以上版本可用**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **注意:此功能仅在 Express 4.16.0 及以上版本可用**
-## Third-party middleware
+## 第三方中间件
-Use third-party middleware to add functionality to Express apps.
+使用第三方中间件可以为 Express 应用拓展功能。
-Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.
+先安装实现所需功能的 Node.js 模块,之后在应用级别或路由级别将其引入项目。
-The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
+下面的示例演示了如何安装并加载 cookie 解析中间件 `cookie-parser`。
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +371,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
-For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
+如需查看可配合 Express 使用的常用第三方中间件部分清单,请参阅:[第三方中间件](/resources/middleware)。
diff --git a/src/content/docs/zh-cn/5x/guide/using-template-engines.mdx b/src/content/docs/zh-cn/5x/guide/using-template-engines.mdx
index 6b74b66f11..c99f896488 100644
--- a/src/content/docs/zh-cn/5x/guide/using-template-engines.mdx
+++ b/src/content/docs/zh-cn/5x/guide/using-template-engines.mdx
@@ -1,45 +1,41 @@
---
-title: Using template engines with Express
-description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently.
+title: 在 Express 中使用模板引擎
+description: 了解如何在 Express.js 中集成并使用 Pug、Handlebars、EJS 等模板引擎,高效渲染动态 HTML 页面。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
-variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
-This approach makes it easier to design an HTML page.
+模板引擎能够让你在应用中使用静态模板文件。 运行时,模板引擎会将模板文件中的变量替换为实际值,并把模板转换成HTML文件发送至客户端。
+这种方式能够简化HTML页面的开发。
-The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
+[Express应用生成器](/en/starter/generator)默认使用[Pug](https://pugjs.org/api/getting-started.html),同时也支持[Handlebars](https://www.npmjs.com/package/handlebars)、[EJS](https://www.npmjs.com/package/ejs)等模板引擎。
-To render template files, set the following [application setting properties](/4x/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
-- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
- This defaults to the `views` directory in the application root directory.
-- `view engine`, the template engine to use. For example, to use the Pug template engine: `app.set('view engine', 'pug')`.
+- `views`,模板文件所在的目录。 例如:`app.set('views', './views')`。
+ 该配置默认为应用根目录下的`views`目录。
+- `view engine`,要使用的模板引擎。 例如,要使用 Pug 模板引擎:`app.set('view engine', 'pug')`。
-Then install the corresponding template engine npm package; for example to install Pug:
+然后安装对应的模板引擎 npm 包;例如要安装 Pug:
-```bash
-$ npm install pug --save
-```
+
-Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
-which `res.render()` calls to render the template code.
+符合 Express 规范的模板引擎如 Pug会导出一个名为`__express(filePath, options, callback)`的函数,`res.render()`会调用该函数来渲染模板代码。
-Some template engines do not follow this convention. The [@ladjs/consolidate](https://www.npmjs.com/package/@ladjs/consolidate)
-library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express.
+有些模板引擎并不遵循此规范。 [@ladjs/consolidate](https://www.npmjs.com/package/@ladjs/consolidate)库遵循此规范,对所有主流Node.js模板引擎进行了统一封装,因此可在Express中无缝使用。
-After the view engine is set, you don't have to specify the engine or load the template engine module in your app;
-Express loads the module internally, for example:
+设置视图引擎后,你无需在应用中指定引擎或加载模板引擎模块;
+Express 会在内部自动加载该模块,例如:
```js
app.set('view engine', 'pug');
```
-Then, create a Pug template file named `index.pug` in the `views` directory, with the following content:
+然后,在`views`目录中创建一个名为`index.pug`的Pug模板文件,内容如下:
```pug
html
@@ -49,8 +45,7 @@ html
h1= message
```
-Create a route to render the `index.pug` file. If the `view engine` property is not set,
-you must specify the extension of the `view` file. Otherwise, you can omit it.
+创建一条路由来渲染`index.pug`文件。 如果未配置`view engine`属性,则必须指明视图文件的后缀名。 否则可以省略文件后缀。
```js
app.get('/', (req, res) => {
@@ -58,6 +53,6 @@ app.get('/', (req, res) => {
});
```
-When you make a request to the home page, the `index.pug` file will be rendered as HTML.
+当访问首页时,`index.pug` 文件会被渲染成 HTML。
-The view engine cache does not cache the contents of the template's output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on.
+视图引擎缓存不会缓存模板渲染后的输出内容,仅缓存原始模板文件本身。 即便开启缓存,每次请求视图仍会重新渲染。
diff --git a/src/content/docs/zh-cn/5x/guide/writing-middleware.mdx b/src/content/docs/zh-cn/5x/guide/writing-middleware.mdx
index de62911dd9..509a9be121 100644
--- a/src/content/docs/zh-cn/5x/guide/writing-middleware.mdx
+++ b/src/content/docs/zh-cn/5x/guide/writing-middleware.mdx
@@ -1,35 +1,34 @@
---
-title: Writing middleware for use in Express apps
-description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling.
+title: 编写 Express 应用使用的中间件
+description: 学习如何为 Express.js 应用编写自定义中间件函数,包含用于增强请求和响应处理的示例与最佳实践。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the `next` function in the application's request-response cycle. `next` 函数是 Express 路由器中的一个函数,调用该函数时,会执行当前中间件之后的下一个中间件。
-Middleware functions can perform the following tasks:
+中间件函数可执行下列任务:
-- Execute any code.
-- Make changes to the request and the response objects.
-- End the request-response cycle.
-- Call the next middleware in the stack.
+- 执行任意代码。
+- 修改请求对象与响应对象。
+- 终止请求-响应周期。
+- 调用堆栈中的下一个中间件。
-If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging.
+如果当前中间件函数没有终止请求-响应周期,它必须调用 `next()` 以将控制权传递给下一个中间件函数。 否则,请求将会被挂起。
-The following figure shows the elements of a middleware function call:
+下图展示了中间件函数调用的组成要素:

-Starting with Express 5, middleware functions that return a Promise will call `next(value)` when they reject or throw an error. `next` will be called with either the rejected value or the thrown Error.
+从 Express 5 开始,返回 Promise 的中间件函数在被拒绝或抛出错误时,会自动调用 `next(value)`。 `next` 函数将以被拒绝的值或抛出的错误对象作为参数被调用。
-## Example
+## 示例
-Here is an example of a simple "Hello World" Express application.
-The remainder of this article will define and add three middleware functions to the application:
-one called `myLogger` that prints a simple log message, one called `requestTime` that
-displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
+以下是一个简单的 Express “Hello World” 应用示例。
+本文的后续部分将为该应用定义并添加三个中间件函数:
+一个名为 `myLogger`,用于打印简单的日志信息;一个名为 `requestTime`,用于显示 HTTP 请求的时间戳;还有一个名为 `validateCookies`,用于验证传入的 Cookie。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -40,11 +39,21 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-### Middleware function myLogger
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
+### 中间件函数 myLogger
-Here is a simple example of a middleware function called "myLogger". This function just prints
-"LOGGED" when a request to the app passes through it. The middleware function is assigned to a
-variable named `myLogger`.
+以下是一个名为 `myLogger` 的简单中间件函数示例。 当对应用的请求经过该函数时,它只会打印 "LOGGED"。 该中间件函数被赋值给了一个名为 `myLogger` 的变量。
```js
const myLogger = function (req, res, next) {
@@ -55,17 +64,14 @@ const myLogger = function (req, res, next) {
-Notice the call above to `next()`. Calling this function invokes the next middleware function in
-the app. The `next()` function is not a part of the Node.js or Express API, but is the third
-argument that is passed to the middleware function. The `next()` function could be named anything,
-but by convention it is always named "next". To avoid confusion, always use this convention.
+注意上述代码中对 `next()` 的调用。 调用该函数会执行应用中的下一个中间件函数。 `next()` 函数并非 Node.js 或 Express API 的一部分,而是传递给中间件函数的第三个参数。 `next()` 函数可以被命名为任意名称,但按照惯例,它始终被命名为 `next`。 为避免混淆,请始终遵循此命名惯例。
-To load the middleware function, call `app.use()`, specifying the middleware function.
-For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
+加载中间件函数时,需调用 `app.use()` 并传入该中间件函数。
+例如,以下代码在根路径(/)路由之前加载 `myLogger` 中间件函数。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -83,18 +89,36 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-Every time the app receives a request, it prints the message "LOGGED" to the terminal.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
+每当应用接收到请求时,都会在终端中打印消息 "LOGGED"。
-The order of middleware loading is important: middleware functions that are loaded first are also executed first.
+中间件的加载顺序至关重要:先加载的中间件会先执行。
-If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn't print "LOGGED", because the route handler of the root path terminates the request-response cycle.
+如果 `myLogger` 在根路径路由之后加载,请求永远不会到达该中间件,应用也不会打印 "LOGGED",因为根路径的路由处理程序会终止请求-响应循环。
-The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function.
+中间件函数 `myLogger` 仅打印一条消息,然后通过调用 `next()` 函数将请求传递给栈中的下一个中间件函数。
-### Middleware function requestTime
+### 中间件函数 requestTime
-Next, we'll create a middleware function called "requestTime" and add a property called `requestTime`
-to the request object.
+接下来,我们将创建一个名为 `requestTime` 的中间件函数,并向请求对象添加一个名为 `requestTime` 的属性。
```js
const requestTime = function (req, res, next) {
@@ -103,9 +127,9 @@ const requestTime = function (req, res, next) {
};
```
-The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
+该应用现在使用了 `requestTime` 中间件函数。 此外,根路径路由的回调函数使用了中间件函数挂载到`req`(请求对象)上的属性。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -125,13 +149,34 @@ app.get('/', (req, res) => {
app.listen(3000);
```
-When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
+向应用根路径发起请求后,应用便会在浏览器中展示本次请求的时间戳。
-### Middleware function validateCookies
+### 中间件函数 validateCookies
-Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.
+最后,我们将创建一个中间件函数来验证传入的 Cookie,如果 Cookie 无效,则返回 400 响应。
-Here's an example function that validates cookies with an external async service.
+下面是一个示例函数,它通过外部异步服务验证 Cookie。
```js
async function cookieValidator(cookies) {
@@ -143,9 +188,9 @@ async function cookieValidator(cookies) {
}
```
-Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
+此处我们使用 [`cookie-parser`](/en/resources/middleware/cookie-parser) 中间件从 `req` 对象中解析传入的 Cookie,并将其传给 `cookieValidator` 函数。 `validateCookies` 中间件会返回一个 Promise,该 Promise 被拒绝时将自动触发我们的错误处理程序。
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -169,27 +214,45 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
-Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
-`cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything
-to the `next()` function (except the string `'route'` or `'router'`), Express regards the current
-request as being an error and will skip any remaining non-error handling routing and middleware
-functions.
+注意 `next()` 是在 `await cookieValidator(req.cookies)` 之后调用的。 这能确保如果 `cookieValidator` 状态变为已兑现,堆栈中的下一个中间件将会被调用。 如果你向 `next()` 函数传入任何内容(字符串 `'route'` 或 `'router'` 除外),Express 会将当前请求视为错误,并跳过所有剩余的非错误处理路由和中间件函数。
-Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.
+由于你可以访问请求对象、响应对象、堆栈中的下一个中间件函数以及整个 Node.js API,因此中间件函数的用途是无限的。
For more information about Express middleware, see: [Using Express middleware](/guide/using-middleware).
-## Configurable middleware
-
-If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
+## 可配置中间件
-File: `my-middleware.js`
+如果需要让你的中间件具备可配置性,可导出一个接收选项对象或其他参数的函数,该函数会根据输入参数返回对应的中间件实现。
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -198,12 +261,27 @@ module.exports = function (options) {
};
```
-The middleware can now be used as shown below.
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
-```js
-const mw = require('./my-middleware.js');
+该中间件现在可如下所示使用。
+
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
-Refer to [cookie-session](https://github.com/expressjs/cookie-session) and [compression](https://github.com/expressjs/compression) for examples of configurable middleware.
+有关可配置中间件的示例,请参考 [cookie-session](https://github.com/expressjs/cookie-session) 和 [compression](https://github.com/expressjs/compression)。
diff --git a/src/content/docs/zh-cn/5x/starter/basic-routing.mdx b/src/content/docs/zh-cn/5x/starter/basic-routing.mdx
index f14af2a5de..5780e52d70 100644
--- a/src/content/docs/zh-cn/5x/starter/basic-routing.mdx
+++ b/src/content/docs/zh-cn/5x/starter/basic-routing.mdx
@@ -1,38 +1,37 @@
---
-title: Basic routing
-description: Learn the fundamentals of routing in Express.js applications, including how to define routes, handle HTTP methods, and create route handlers for your web server.
+title: 基本路由
+description: 学习 Express.js 应用程序中路由的基础知识,包括如何定义路由、处理 HTTP 方法以及为 Web 服务器创建路由处理程序。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-_Routing_ refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
+路由用于定义应用程序如何响应客户端对指定端点的请求;端点由统一资源标识符(URI,或称路径)和具体的 HTTP 请求方法(GET、POST 等)组成。
-Each route can have one or more handler functions, which are executed when the route is matched.
+每条路由可配置一个或多个处理函数,匹配到该路由时就会执行这些函数。
-Route definition takes the following structure:
+路由的定义格式如下:
```js
app.METHOD(PATH, HANDLER);
```
-Where:
+其中:
-- `app` is an instance of `express`.
-- `METHOD` is an [HTTP request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods), in lowercase.
-- `PATH` is a path on the server.
-- `HANDLER` is the function executed when the route is matched.
+- `app` 是 `express` 的实例。
+- `METHOD` 是小写形式的 [HTTP 请求方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Reference/Methods)。
+- `PATH` 是服务器上的路径。
+- `HANDLER` 是路由匹配时执行的函数。
-This tutorial assumes that an instance of `express` named `app` is created and the server is
-running. If you are not familiar with creating an app and starting it, see the Hello world
+本教程假设已创建一个名为 `app` 的 `express` 实例,且服务器正在运行。 If you are not familiar with creating an app and starting it, see the Hello world
example.
-The following examples illustrate defining simple routes.
+以下示例演示如何定义简单路由。
-Respond with `Hello World!` on the homepage:
+在主页响应 `Hello World!`:
```js
app.get('/', (req, res) => {
@@ -40,7 +39,7 @@ app.get('/', (req, res) => {
});
```
-Respond to a POST request on the root route (`/`), the application's home page:
+响应根路由(/)应用的主页的 POST 请求:
```js
app.post('/', (req, res) => {
@@ -48,7 +47,7 @@ app.post('/', (req, res) => {
});
```
-Respond to a PUT request to the `/user` route:
+响应 `/user` 路由的 PUT 请求:
```js
app.put('/user', (req, res) => {
@@ -56,7 +55,7 @@ app.put('/user', (req, res) => {
});
```
-Respond to a DELETE request to the `/user` route:
+响应 `/user` 路由的 DELETE 请求:
```js
app.delete('/user', (req, res) => {
diff --git a/src/content/docs/zh-cn/5x/starter/examples.mdx b/src/content/docs/zh-cn/5x/starter/examples.mdx
index 69f410e908..5e731014f9 100644
--- a/src/content/docs/zh-cn/5x/starter/examples.mdx
+++ b/src/content/docs/zh-cn/5x/starter/examples.mdx
@@ -1,49 +1,46 @@
---
-title: Express examples
-description: Explore a collection of Express.js application examples covering various use cases, integrations, and advanced configurations to help you learn and build your projects.
+title: Express 示例
+description: 浏览一系列 Express.js 应用示例,涵盖不同的使用场景、集成方式以及高级配置,帮助你学习并构建自己的项目。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-This page contains list of examples using Express.
-
-- [auth](https://github.com/expressjs/express/tree/master/examples/auth) - Authentication with login and password
-- [content-negotiation](https://github.com/expressjs/express/tree/master/examples/content-negotiation) - HTTP content negotiation
-- [cookie-sessions](https://github.com/expressjs/express/tree/master/examples/cookie-sessions) - Working with cookie-based sessions
-- [cookies](https://github.com/expressjs/express/tree/master/examples/cookies) - Working with cookies
-- [downloads](https://github.com/expressjs/express/tree/master/examples/downloads) - Transferring files to client
-- [ejs](https://github.com/expressjs/express/tree/master/examples/ejs) - Working with Embedded JavaScript templating (ejs)
-- [error-pages](https://github.com/expressjs/express/tree/master/examples/error-pages) - Creating error pages
-- [error](https://github.com/expressjs/express/tree/master/examples/error) - Working with error middleware
-- [hello-world](https://github.com/expressjs/express/tree/master/examples/hello-world) - Simple request handler
-- [markdown](https://github.com/expressjs/express/tree/master/examples/markdown) - Markdown as template engine
-- [multi-router](https://github.com/expressjs/express/tree/master/examples/multi-router) - Working with multiple Express routers
-- [mvc](https://github.com/expressjs/express/tree/master/examples/mvc) - MVC-style controllers
-- [online](https://github.com/expressjs/express/tree/master/examples/online) - Tracking online user activity with `online` and `redis` packages
-- [params](https://github.com/expressjs/express/tree/master/examples/params) - Working with route parameters
-- [resource](https://github.com/expressjs/express/tree/master/examples/resource) - Multiple HTTP operations on the same resource
-- [route-map](https://github.com/expressjs/express/tree/master/examples/route-map) - Organizing routes using a map
-- [route-middleware](https://github.com/expressjs/express/tree/master/examples/route-middleware) - Working with route middleware
-- [route-separation](https://github.com/expressjs/express/tree/master/examples/route-separation) - Organizing routes per each resource
-- [search](https://github.com/expressjs/express/tree/master/examples/search) - Search API
-- [session](https://github.com/expressjs/express/tree/master/examples/session) - User sessions
-- [static-files](https://github.com/expressjs/express/tree/master/examples/static-files) - Serving static files
-- [vhost](https://github.com/expressjs/express/tree/master/examples/vhost) - Working with virtual hosts
-- [view-constructor](https://github.com/expressjs/express/tree/master/examples/view-constructor) - Rendering views dynamically
-- [view-locals](https://github.com/expressjs/express/tree/master/examples/view-locals) - Saving data in request object between middleware calls
-- [web-service](https://github.com/expressjs/express/tree/master/examples/web-service) - Simple API service
-
-## Additional examples
-
-These are some additional examples with more extensive integrations.
-
-
-
-This information refers to third-party sites, products, or modules that are not maintained by the
-Expressjs team. Listing here does not constitute an endorsement or recommendation from the
-Expressjs project team.
+本页面包含一系列 Express 的使用示例。
+
+- [auth](https://github.com/expressjs/express/tree/master/examples/auth) - 基于账号密码的身份验证
+- [content-negotiation](https://github.com/expressjs/express/tree/master/examples/content-negotiation) - HTTP内容协商
+- [cookie-sessions](https://github.com/expressjs/express/tree/master/examples/cookie-sessions) - 基于Cookie的会话使用示例
+- [cookies](https://github.com/expressjs/express/tree/master/examples/cookies) - Cookie 使用示例
+- [downloads](https://github.com/expressjs/express/tree/master/examples/downloads) - 向客户端传输文件
+- [ejs](https://github.com/expressjs/express/tree/master/examples/ejs) - 使用嵌入式JavaScript模板引擎(ejs)
+- [error-pages](https://github.com/expressjs/express/tree/master/examples/error-pages) - 自定义错误页面
+- [error](https://github.com/expressjs/express/tree/master/examples/error) - 使用错误处理中间件
+- [hello-world](https://github.com/expressjs/express/tree/master/examples/hello-world) - 简易请求处理程序
+- [markdown](https://github.com/expressjs/express/tree/master/examples/markdown) - Markdown 作为模板引擎
+- [multi-router](https://github.com/expressjs/express/tree/master/examples/multi-router) - 使用多个 Express 路由
+- [mvc](https://github.com/expressjs/express/tree/master/examples/mvc) - MVC 风格控制器
+- [online](https://github.com/expressjs/express/tree/master/examples/online) - 使用 `online` 和 `redis` 包追踪在线用户活动
+- [params](https://github.com/expressjs/express/tree/master/examples/params) - 路由参数使用示例
+- [resource](https://github.com/expressjs/express/tree/master/examples/resource) - 对同一资源执行多种 HTTP 操作
+- [route-map](https://github.com/expressjs/express/tree/master/examples/route-map) - 使用映射表组织路由
+- [route-middleware](https://github.com/expressjs/express/tree/master/examples/route-middleware) - 路由中间件使用示例
+- [route-separation](https://github.com/expressjs/express/tree/master/examples/route-separation) - 按资源拆分组织路由
+- [search](https://github.com/expressjs/express/tree/master/examples/search) - 搜索 API
+- [session](https://github.com/expressjs/express/tree/master/examples/session) - 用户会话
+- [static-files](https://github.com/expressjs/express/tree/master/examples/static-files) - 静态文件服务
+- [vhost](https://github.com/expressjs/express/tree/master/examples/vhost) - 虚拟主机使用示例
+- [view-constructor](https://github.com/expressjs/express/tree/master/examples/view-constructor) - 动态渲染视图
+- [view-locals](https://github.com/expressjs/express/tree/master/examples/view-locals) - 在中间件调用之间于请求对象中存储数据
+- [web-service](https://github.com/expressjs/express/tree/master/examples/web-service) - 简易 API 服务
+
+## 更多示例
+
+以下是一些包含更复杂集成的示例。
+
+
+
+这些信息指的是第三方站点、产品或模块,它们不是由Expressjs团队维护的。 此处的罗列并不代表 Express 项目团队的认可或推荐。
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
-- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
+- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - 使用 TypeScript 的 Express REST API,并使用 [Prisma](https://www.npmjs.com/package/prisma) 作为 ORM
diff --git a/src/content/docs/zh-cn/5x/starter/faq.md b/src/content/docs/zh-cn/5x/starter/faq.md
index e487cc3501..5b9dc00149 100644
--- a/src/content/docs/zh-cn/5x/starter/faq.md
+++ b/src/content/docs/zh-cn/5x/starter/faq.md
@@ -1,58 +1,43 @@
---
-title: FAQ
-description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more.
+title: FAQ 常见问题解答
+description: 查找有关 Express.js 的常见问题解答,涵盖应用程序架构、数据模型、身份验证、模板引擎、错误处理等相关主题。
---
-## How should I structure my application?
+## 我应该如何组织我的应用程序?
-There is no definitive answer to this question. The answer depends
-on the scale of your application and the team that is involved. To be as
-flexible as possible, Express makes no assumptions in terms of structure.
+这个问题没有标准答案。 答案取决于你的应用规模以及参与开发的团队。 为实现最大限度的灵活性,Express 不会对项目结构做任何强制限定。
-Routes and other application-specific logic can live in as many files
-as you wish, in any directory structure you prefer. View the following
-examples for inspiration:
+路由和其他应用专属逻辑可拆分至任意数量文件,并采用你偏好的任意目录结构存放。 可参考下方示例获取项目结构设计思路:
- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
- [Route map](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
- [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc)
-Also, there are third-party extensions for Express, which simplify some of these patterns:
+此外,Express 拥有各类第三方扩展,能够简化部分开发架构范式:
- [Resourceful routing](https://github.com/expressjs/express-resource)
-## How do I define models?
+## 如何定义模型?
-Express has no notion of a database. This concept is
-left up to third-party Node modules, allowing you to
-interface with nearly any database.
+Express 本身不包含数据库相关概念。 这一概念交由第三方 Node 模块实现,让你能够与几乎所有数据库进行交互。
See [LoopBack](http://loopback.io) for an Express-based framework that is centered around models.
-## How can I authenticate users?
+## 如何实现用户身份验证?
-Authentication is another opinionated area that Express does not
-venture into. You may use any authentication scheme you wish.
-For a simple username / password scheme, see [this example](https://github.com/expressjs/express/tree/master/examples/auth).
+身份验证同样是一项带有主观选型倾向的功能,Express 并未涉足该领域。 你可以选用任意你想要的身份验证方案。
+如需实现简易的用户名/密码验证方案,可参考[该示例](https://github.com/expressjs/express/tree/master/examples/auth)。
-## Which template engines does Express support?
+## Express 支持哪些模板引擎?
-Express supports any template engine that conforms with the `(path, locals, callback)` signature.
-To normalize template engine interfaces and caching, see the
-[consolidate.js](https://github.com/visionmedia/consolidate.js)
-project for support. Unlisted template engines might still support the Express signature.
+Express 支持所有符合 `(path, locals, callback)` 入参规范的模板引擎。
+如需统一各类模板引擎的接口与缓存机制,可查看 [consolidate.js](https://github.com/visionmedia/consolidate.js) 项目以获取相关支持。 未列入清单的模板引擎也可能兼容 Express 的调用规范。
For more information, see [Using template engines with Express](/guide/using-template-engines).
-## How do I handle 404 responses?
+## 如何处理 404 响应?
-In Express, 404 responses are not the result of an error, so
-the error-handler middleware will not capture them. This behavior is
-because a 404 response simply indicates the absence of additional work to do;
-in other words, Express has executed all middleware functions and routes,
-and found that none of them responded. All you need to
-do is add a middleware function at the very bottom of the stack (below all other functions)
-to handle a 404 response:
+在 Express 中,404 响应并非由错误导致,因此错误处理中间件不会捕获这类响应。 出现这种行为的原因是,404 响应仅表示没有其他待执行的操作;换言之,Express 已执行完所有中间件函数和路由,但未找到任何能够响应请求的处理逻辑。 你只需在中间件栈的最底部(所有其他函数之后)添加一个中间件函数来处理 404 响应即可:
```js
app.use((req, res, next) => {
@@ -60,13 +45,11 @@ app.use((req, res, next) => {
});
```
-Add routes dynamically at runtime on an instance of `express.Router()`
-so the routes are not superseded by a middleware function.
+在运行时通过 `express.Router()` 实例动态添加路由,确保路由不会被中间件函数覆盖。
-## How do I setup an error handler?
+## 如何设置错误处理程序?
-You define error-handling middleware in the same way as other middleware,
-except with four arguments instead of three; specifically with the signature `(err, req, res, next)`:
+错误处理中间件的定义方式与其他中间件相同,区别在于它使用四个参数而非三个;具体的函数签名为 `(err, req, res, next)`:
```js
app.use((err, req, res, next) => {
@@ -77,14 +60,13 @@ app.use((err, req, res, next) => {
For more information, see [Error handling](/guide/error-handling).
-## How do I render plain HTML?
+## 如何渲染纯 HTML?
-You don't! There's no need to "render" HTML with the `res.render()` function.
-If you have a specific file, use the `res.sendFile()` function.
-If you are serving many assets from a directory, use the `express.static()`
-middleware function.
+无需额外操作! 无需使用 `res.render()` 函数来“渲染” HTML。
+如果你需要响应指定的文件,请使用 `res.sendFile()` 函数。
+如果你要从一个目录提供多个静态资源,请使用 `express.static()` 中间件函数。
-## What version of Node.js does Express require?
+## Express 需要哪个版本的 Node.js?
- [Express 4.x](/4x/api) requires Node.js 0.10 or higher.
- [Express 5.x](/api) requires Node.js 18 or higher.
diff --git a/src/content/docs/zh-cn/5x/starter/generator.mdx b/src/content/docs/zh-cn/5x/starter/generator.mdx
index 4f22665f43..1bbc4ad151 100644
--- a/src/content/docs/zh-cn/5x/starter/generator.mdx
+++ b/src/content/docs/zh-cn/5x/starter/generator.mdx
@@ -1,26 +1,26 @@
---
-title: Express application generator
-description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration.
+title: Express 应用生成器
+description: 学习如何使用 Express 应用生成器工具快速创建 Express.js 应用骨架,简化初始化与配置工作。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-Use the application generator tool, `express-generator`, to quickly create an application skeleton.
+使用应用生成器工具 `express-generator` 可以快速创建应用骨架。
-You can run the application generator with the `npx` command (available in Node.js 8.2.0).
+你可以使用 `npx` 命令(Node.js 8.2.0 及以上版本可用)运行应用生成器。
```bash
$ npx express-generator
```
-For earlier Node versions, install the application generator as a global npm package and then launch it:
+对于早期的 Node 版本,请将应用生成器作为全局 npm 包安装,然后启动它:
```bash
$ npm install -g express-generator
$ express
```
-Display the command options with the `-h` option:
+使用 `-h` 选项查看命令选项:
```bash
$ express -h
@@ -42,7 +42,7 @@ $ express -h
-f, --force force on non-empty directory
```
-For example, the following creates an Express app named _myapp_. The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug:
+例如,以下命令会创建一个名为 _myapp_ 的 Express 应用。 此应用将创建在当前工作目录下名为 _myapp_ 的文件夹中,并且视图引擎将设置为 Pug:
```bash
$ express --view=pug myapp
@@ -66,34 +66,34 @@ $ express --view=pug myapp
create : myapp/bin/www
```
-Then install dependencies:
+然后安装依赖项:
```bash
$ cd myapp
$ npm install
```
-On MacOS or Linux, run the app with this command:
+在 macOS 或 Linux 系统上,使用此命令运行应用:
```bash
$ DEBUG=myapp:* npm start
```
-On Windows Command Prompt, use this command:
+在 Windows 命令提示符中,使用此命令:
```bash
> set DEBUG=myapp:* & npm start
```
-On Windows PowerShell, use this command:
+在 Windows PowerShell 中,使用此命令:
```bash
PS> $env:DEBUG='myapp:*'; npm start
```
-Then, load `http://localhost:3000/` in your browser to access the app.
+然后在浏览器中加载 `http://localhost:3000/` 以访问该应用。
-The generated app has the following directory structure:
+生成的应用具有以下目录结构:
```bash
.
@@ -119,7 +119,7 @@ The generated app has the following directory structure:
-The app structure created by the generator is just one of many ways to structure Express apps.
-Feel free to use this structure or modify it to best suit your needs.
+生成器创建的应用结构只是 Express 应用多种结构方案中的一种。
+你可以随意使用此结构,或根据你的需求对其进行修改。
diff --git a/src/content/docs/zh-cn/5x/starter/hello-world.mdx b/src/content/docs/zh-cn/5x/starter/hello-world.mdx
index 629d697721..4ecf64e0b0 100644
--- a/src/content/docs/zh-cn/5x/starter/hello-world.mdx
+++ b/src/content/docs/zh-cn/5x/starter/hello-world.mdx
@@ -1,20 +1,17 @@
---
-title: Hello world example
-description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners.
+title: Hello world 示例
+description: 通过构建一个简单的“Hello World”应用来入门 Express.js,展示基础的配置和服务器创建过程,适合初学者学习。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-Embedded below is essentially the simplest Express app you can create. It is a single file app
-— _not_ what you'd get if you use the [Express generator](/starter/generator), which
-creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and
-sub-directories for various purposes.
+下面展示的是一个本质上最简单的 Express 应用。 这是一个单文件应用—而不是使用 [Express 生成器](/en/starter/generator) 所生成的项目结构,后者会创建一个完整应用的脚手架,包含多个 JavaScript 文件、Jade 模板,以及用于不同用途的子目录。
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,27 +25,39 @@ app.listen(port, () => {
});
```
-This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
-to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
+```mjs title="index.mjs"
+import express from 'express';
-## Running Locally
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
+该应用启动一个服务器,并在 3000 端口监听连接请求。 当请求根 URL(`/`)或“ _route_”时,该应用会返回“Hello World!”。 对于其他所有路径,它都会返回 **404 Not Found**。
+
+## 本地运行
-First create a directory named `myapp`, change to it and run `npm init`. Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
+首先创建一个名为 `myapp` 的目录,进入该目录并运行 `npm init`。 Then, install `express` as a dependency, as per the [installation guide](/starter/installing).
-In the `myapp` directory, create a file named `app.js` and copy the code from the example above.
+在 `myapp` 目录中创建一个名为 `app.js` 的文件,并复制上方示例中的代码。
-The `req` (request) and `res` (response) are the exact same objects that Node provides, so you can
-invoke `req.pipe()`, `req.on('data', callback)`, and anything else you would do without Express
-involved.
+`req`(请求)和 `res`(响应)就是 Node 本身提供的同一对象,因此你可以调用 `req.pipe()`、`req.on('data', callback)`,以及在不使用 Express 时会用到的任何其他方法。
-Run the app with the following command:
+使用以下命令运行应用:
```bash
$ node app.js
```
-Then, load `http://localhost:3000/` in a browser to see the output.
+然后,在浏览器中打开 `http://localhost:3000/` 查看输出结果。
diff --git a/src/content/docs/zh-cn/5x/starter/installing.mdx b/src/content/docs/zh-cn/5x/starter/installing.mdx
index f6dc8220d4..9831858395 100644
--- a/src/content/docs/zh-cn/5x/starter/installing.mdx
+++ b/src/content/docs/zh-cn/5x/starter/installing.mdx
@@ -1,41 +1,36 @@
---
-title: Installing
-description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm.
+title: 安装
+description: 学习如何在 Node.js 环境中安装 Express.js,包括创建项目目录以及使用 npm 管理依赖项。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Before you begin, make sure you have [Node.js](https://nodejs.org/) 18 or higher installed. Then, create a directory for your application and navigate into it.
+在开始前,请确保你有安装 [Node.js](https://nodejs.org/) 18 或更高版本。 然后,为你的应用创建一个目录并进入该目录。
```bash
mkdir myapp
cd myapp
```
-Use the `npm init` command to create a `package.json` file for your application.
-For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
+使用 `npm init` 命令为你的应用创建一个 `package.json` 文件。
+有关 `package.json` 工作机制的更多信息,请参阅 [npm 的 package.json 处理细则](https://docs.npmjs.com/files/package.json)。
-```bash
-npm init
-```
+
-This command prompts you for a number of things, such as the name and version of your application.
-For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
+该命令会提示你输入一些信息,例如应用的名称和版本号。
+目前,你可以直接按回车键接受大多数默认值,但以下情况除外:
```
entry point: (index.js)
```
-Enter `app.js`, or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name.
+输入 `app.js`,或者你希望作为主文件的其他名称。 如果希望使用 `index.js`,直接按回车键接受系统建议的默认文件名即可。
-Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
+现在,在 `myapp` 目录中安装 Express,并将其保存到依赖列表中。 举个例子:
-```bash
-npm install express
-```
+
-To install Express temporarily and not add it to the dependencies list:
+如果只是临时安装 Express,而不将其加入依赖列表:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/zh-cn/5x/starter/static-files.mdx b/src/content/docs/zh-cn/5x/starter/static-files.mdx
index dbadee731a..81262e4ac3 100644
--- a/src/content/docs/zh-cn/5x/starter/static-files.mdx
+++ b/src/content/docs/zh-cn/5x/starter/static-files.mdx
@@ -1,28 +1,28 @@
---
-title: Serving static files in Express
-description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware.
+title: 在 Express 中托管静态文件
+description: 了解如何在 Express.js 应用中使用内置的 `static` 中间件托管图片、CSS 和 JavaScript 等静态文件。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express.
+要托管图片、CSS 文件和 JavaScript 文件等静态文件,需使用 Express 内置的 `express.static` 中间件函数。
-The function signature is:
+该函数的签名为:
```js
express.static(root, [options]);
```
-The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/api#express.static).
+`root` 参数用于指定托管静态资源的根目录。
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
-For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
+例如,使用以下代码来托管 `public` 目录中的图片、CSS 文件和 JavaScript 文件:
```js
app.use(express.static('public'));
```
-Now, you can load the files that are in the `public` directory:
+现在,你就可以加载 `public` 目录中的文件了:
```text
http://localhost:3000/images/kitten.jpg
@@ -34,19 +34,18 @@ http://localhost:3000/hello.html
-Express looks up the files relative to the static directory, so the name of the static directory
-is not part of the URL.
+Express 查找文件时是相对于静态目录的,因此静态目录名称不会出现在 URL 中。
-To use multiple static assets directories, call the `express.static` middleware function multiple times:
+若要使用多个静态资源目录,需多次调用 `express.static` 中间件函数:
```js
app.use(express.static('public'));
app.use(express.static('files'));
```
-Express looks up the files in the order in which you set the static directories with the `express.static` middleware function.
+Express 会按照你使用 `express.static` 中间件设置静态目录的**顺序**来查找文件。
@@ -56,13 +55,13 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
```
-Now, you can load the files that are in the `public` directory from the `/static` path prefix.
+现在,你可以通过 `/static` 路径前缀加载存放在 `public` 目录中的文件。
```text
http://localhost:3000/static/images/kitten.jpg
@@ -72,11 +71,17 @@ http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
```
-However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
+但是,你提供给 `express.static` 函数的路径是相对于你启动 `node` 进程的目录而言的。 如果你从其他目录启动 Express 应用,使用你要托管的目录的绝对路径会更安全:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/zh-tw/4x/guide/error-handling.mdx b/src/content/docs/zh-tw/4x/guide/error-handling.mdx
index 507232b013..3d65d4d3b6 100644
--- a/src/content/docs/zh-tw/4x/guide/error-handling.mdx
+++ b/src/content/docs/zh-tw/4x/guide/error-handling.mdx
@@ -207,7 +207,7 @@ app.use((err, req, res, next) => {
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +223,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +246,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. For example, to define an error-handler
for requests made by using `XHR` and those without:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +262,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
diff --git a/src/content/docs/zh-tw/4x/guide/overriding-express-api.md b/src/content/docs/zh-tw/4x/guide/overriding-express-api.md
index ac0953c945..ef06cf056c 100644
--- a/src/content/docs/zh-tw/4x/guide/overriding-express-api.md
+++ b/src/content/docs/zh-tw/4x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Altering the global prototypes will affect all loaded Express apps in the same p
You can override the signature and behavior of existing methods with your own, by assigning a custom function.
-Following is an example of overriding the behavior of [res.sendStatus](/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/zh-tw/4x/guide/routing.mdx b/src/content/docs/zh-tw/4x/guide/routing.mdx
index b795b146ba..ae581e72dd 100644
--- a/src/content/docs/zh-tw/4x/guide/routing.mdx
+++ b/src/content/docs/zh-tw/4x/guide/routing.mdx
@@ -10,10 +10,10 @@ For an introduction to routing, see [Basic routing](/starter/basic-routing).
You define routing using methods of the Express `app` object that correspond to HTTP methods;
for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as arguments.
With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
@@ -21,7 +21,7 @@ to the next callback.
The following code is an example of a very basic route.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
@@ -212,7 +223,7 @@ characters with an additional backslash, for example `\d+`.
-The `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`.
+The [`*`](https://github.com/expressjs/express/issues/2495) character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`.
## Route handlers
@@ -312,17 +323,17 @@ app.get(
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | Description |
+| ----------------------------------------------- | ------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Prompt a file to be downloaded. |
+| [res.end()](/api/response#resend) | End the response process. |
+| [res.json()](/api/response#resjson) | Send a JSON response. |
+| [res.jsonp()](/api/response#resjsonp) | Send a JSON response with JSONP support. |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | Render a view template. |
+| [res.send()](/api/response#ressend) | Send a response of various types. |
+| [res.sendFile()](/api/response#ressendfile) | Send a file as an octet stream. |
+| [res.sendStatus()](/api/response#ressendstatus) | Set the response status code and send its string representation as the response body. |
## app.route()
@@ -353,7 +364,7 @@ The following example creates a router as a module, loads a middleware function
Create a router file named `birds.js` in the app directory, with the following content:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -376,9 +387,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -386,9 +421,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/zh-tw/4x/guide/using-middleware.mdx b/src/content/docs/zh-tw/4x/guide/using-middleware.mdx
index 1372e8ca17..9e832fe09f 100644
--- a/src/content/docs/zh-tw/4x/guide/using-middleware.mdx
+++ b/src/content/docs/zh-tw/4x/guide/using-middleware.mdx
@@ -4,10 +4,11 @@ description: Learn how to use middleware in Express.js applications, including a
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named `next`.
Middleware functions can perform the following tasks:
@@ -31,11 +32,11 @@ You can also load a series of middleware functions together, which creates a sub
## Application-level middleware
-Bind application-level middleware to an instance of the [app object](/5x/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
+Bind application-level middleware to an instance of the [app object](/api#app) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
HTTP request on the `/user/:id` path.
@@ -167,7 +179,7 @@ Load router-level middleware by using the `router.use()` and `router.METHOD()` f
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
To skip the rest of the router's middleware functions, call `next('router')`
to pass control back out of the router instance.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Error-handling middleware
@@ -271,9 +355,9 @@ functions that were previously included with Express are now in separate modules
Express has the following built-in middleware functions:
-- [express.static](/5x/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/5x/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/5x/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
## Third-party middleware
@@ -283,11 +367,9 @@ Install the Node.js module for the required functionality, then load it in your
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
diff --git a/src/content/docs/zh-tw/4x/guide/using-template-engines.mdx b/src/content/docs/zh-tw/4x/guide/using-template-engines.mdx
index 0f660ddbb2..18de44b3bf 100644
--- a/src/content/docs/zh-tw/4x/guide/using-template-engines.mdx
+++ b/src/content/docs/zh-tw/4x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate and use template engines like Pug, Handle
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ This approach makes it easier to design an HTML page.
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-To render template files, set the following [application setting properties](/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
This defaults to the `views` directory in the application root directory.
@@ -19,9 +20,7 @@ To render template files, set the following [application setting properties](/ap
Then install the corresponding template engine npm package; for example to install Pug:
-```bash
-$ npm install pug --save
-```
+
Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
diff --git a/src/content/docs/zh-tw/4x/guide/writing-middleware.mdx b/src/content/docs/zh-tw/4x/guide/writing-middleware.mdx
index ae0eeaf7f0..5d822b2883 100644
--- a/src/content/docs/zh-tw/4x/guide/writing-middleware.mdx
+++ b/src/content/docs/zh-tw/4x/guide/writing-middleware.mdx
@@ -5,7 +5,7 @@ description: Learn how to write custom middleware functions for Express.js appli
import Alert from '@components/primitives/Alert/Alert.astro';
-_Middleware_ functions are functions that have access to the [request object](/5x/api#req) (`req`), the [response object](/5x/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
+_Middleware_ functions are functions that have access to the [request object](/api#req) (`req`), the [response object](/api#res) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
@@ -40,11 +40,10 @@ The following figure shows the elements of a middleware function call:
- HTTP response argument to the middleware function, called "res" by
- convention.
+ HTTP [response](/api/response) argument to the middleware function, called "res" by convention.
-HTTP request argument to the middleware function, called "req" by convention.
+HTTP [request](/api/request) argument to the middleware function, called "req" by convention.
@@ -59,7 +58,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -70,6 +69,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Middleware function myLogger
Here is a simple example of a middleware function called "myLogger". This function just prints
@@ -95,7 +106,7 @@ but by convention it is always named "next". To avoid confusion, always use this
To load the middleware function, call `app.use()`, specifying the middleware function.
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -113,6 +124,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
@@ -135,7 +165,7 @@ const requestTime = function (req, res, next) {
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -155,6 +185,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
### Middleware function validateCookies
@@ -175,7 +226,7 @@ async function cookieValidator(cookies) {
Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -199,6 +250,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
@@ -217,9 +292,7 @@ For more information about Express middleware, see: [Using Express middleware](/
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
-File: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -228,10 +301,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
The middleware can now be used as shown below.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/zh-tw/4x/starter/examples.mdx b/src/content/docs/zh-tw/4x/starter/examples.mdx
index 6685b9cbe4..a38dd14df2 100644
--- a/src/content/docs/zh-tw/4x/starter/examples.mdx
+++ b/src/content/docs/zh-tw/4x/starter/examples.mdx
@@ -41,5 +41,4 @@ These are some additional examples with more extensive integrations.
Expressjs project team.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
diff --git a/src/content/docs/zh-tw/4x/starter/hello-world.mdx b/src/content/docs/zh-tw/4x/starter/hello-world.mdx
index 629d697721..4c26ad0813 100644
--- a/src/content/docs/zh-tw/4x/starter/hello-world.mdx
+++ b/src/content/docs/zh-tw/4x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
diff --git a/src/content/docs/zh-tw/4x/starter/installing.mdx b/src/content/docs/zh-tw/4x/starter/installing.mdx
index fc66c7f9df..d2e6ad2a1a 100644
--- a/src/content/docs/zh-tw/4x/starter/installing.mdx
+++ b/src/content/docs/zh-tw/4x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Learn how to install Express.js in your Node.js environment, includ
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Before you begin, make sure you have [Node.js](https://nodejs.org/) 0.10 or higher installed. Then, create a directory for your application and navigate into it.
@@ -15,9 +16,7 @@ cd myapp
Use the `npm init` command to create a `package.json` file for your application.
For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
This command prompts you for a number of things, such as the name and version of your application.
For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
@@ -30,15 +29,11 @@ Enter `app.js`, or whatever you want the name of the main file to be. If you wan
Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
-```bash
-npm install express
-```
+
To install Express temporarily and not add it to the dependencies list:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/zh-tw/4x/starter/static-files.mdx b/src/content/docs/zh-tw/4x/starter/static-files.mdx
index 0f2c8280b1..15a901a994 100644
--- a/src/content/docs/zh-tw/4x/starter/static-files.mdx
+++ b/src/content/docs/zh-tw/4x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/5x/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
@@ -56,7 +56,7 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/5x/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/docs/zh-tw/5x/guide/error-handling.mdx b/src/content/docs/zh-tw/5x/guide/error-handling.mdx
index 507232b013..3d65d4d3b6 100644
--- a/src/content/docs/zh-tw/5x/guide/error-handling.mdx
+++ b/src/content/docs/zh-tw/5x/guide/error-handling.mdx
@@ -207,7 +207,7 @@ app.use((err, req, res, next) => {
You define error-handling middleware last, after other `app.use()` and routes calls; for example:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -223,6 +223,22 @@ app.use((err, req, res, next) => {
});
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use((err, req, res, next) => {
+ // logic
+});
+```
+
Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.
For organizational (and higher-level framework) purposes, you can define
@@ -230,7 +246,7 @@ several error-handling middleware functions, much as you would with
regular middleware functions. For example, to define an error-handler
for requests made by using `XHR` and those without:
-```js
+```cjs title="index.cjs"
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
@@ -246,6 +262,22 @@ app.use(clientErrorHandler);
app.use(errorHandler);
```
+```mjs title="index.mjs"
+import bodyParser from 'body-parser';
+import methodOverride from 'method-override';
+
+app.use(
+ bodyParser.urlencoded({
+ extended: true,
+ })
+);
+app.use(bodyParser.json());
+app.use(methodOverride());
+app.use(logErrors);
+app.use(clientErrorHandler);
+app.use(errorHandler);
+```
+
In this example, the generic `logErrors` might write request and
error information to `stderr`, for example:
diff --git a/src/content/docs/zh-tw/5x/guide/overriding-express-api.md b/src/content/docs/zh-tw/5x/guide/overriding-express-api.md
index 6167938c4d..ef06cf056c 100644
--- a/src/content/docs/zh-tw/5x/guide/overriding-express-api.md
+++ b/src/content/docs/zh-tw/5x/guide/overriding-express-api.md
@@ -14,7 +14,7 @@ Altering the global prototypes will affect all loaded Express apps in the same p
You can override the signature and behavior of existing methods with your own, by assigning a custom function.
-Following is an example of overriding the behavior of [res.sendStatus](/4x/api#res.sendStatus).
+Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus).
```js
app.response.sendStatus = function (statusCode, type, message) {
diff --git a/src/content/docs/zh-tw/5x/guide/routing.mdx b/src/content/docs/zh-tw/5x/guide/routing.mdx
index c24b1f6395..f7a1e00a3f 100644
--- a/src/content/docs/zh-tw/5x/guide/routing.mdx
+++ b/src/content/docs/zh-tw/5x/guide/routing.mdx
@@ -10,10 +10,10 @@ For an introduction to routing, see [Basic routing](/starter/basic-routing).
You define routing using methods of the Express `app` object that correspond to HTTP methods;
for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list,
-see [app.METHOD](/api/application#appmethodpath-callback--callback-). You can also use [app.all()](/api/application#appallpath-callback--callback-) to handle all HTTP methods and [app.use()](/api/application#appusepath-callback--callback) to
+see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to
specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details).
-These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
+These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as arguments.
With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control
@@ -21,7 +21,7 @@ to the next callback.
The following code is an example of a very basic route.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -31,6 +31,17 @@ app.get('/', (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+// respond with "hello world" when a GET request is made to the homepage
+app.get('/', (req, res) => {
+ res.send('hello world');
+});
+```
+
## Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class.
@@ -50,7 +61,7 @@ app.post('/', (req, res) => {
```
Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.
-For a full list, see [app.METHOD](/api/application#appmethodpath-callback--callback-).
+For a full list, see [app.METHOD](/api/application#appmethod).
There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods).
@@ -292,17 +303,17 @@ app.get(
The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
-| Method | Description |
-| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| [res.download()](/api/response#resdownloadpath--filename--options--fn) | Prompt a file to be downloaded. |
-| [res.end()](/api/response#resenddata-encoding-callback) | End the response process. |
-| [res.json()](/api/response#resjsonbody) | Send a JSON response. |
-| [res.jsonp()](/api/response#resjsonpbody) | Send a JSON response with JSONP support. |
-| [res.redirect()](/api/response#resredirectstatus-path) | Redirect a request. |
-| [res.render()](/api/response#resrenderview--locals--callback) | Render a view template. |
-| [res.send()](/api/response#ressendbody) | Send a response of various types. |
-| [res.sendFile()](/api/response#ressendfilepath--options--fn) | Send a file as an octet stream. |
-| [res.sendStatus()](/api/response#ressendstatusstatuscode) | Set the response status code and send its string representation as the response body. |
+| Method | Description |
+| ----------------------------------------------- | ------------------------------------------------------------------------------------- |
+| [res.download()](/api/response#resdownload) | Prompt a file to be downloaded. |
+| [res.end()](/api/response#resend) | End the response process. |
+| [res.json()](/api/response#resjson) | Send a JSON response. |
+| [res.jsonp()](/api/response#resjsonp) | Send a JSON response with JSONP support. |
+| [res.redirect()](/api/response#resredirect) | Redirect a request. |
+| [res.render()](/api/response#resrender) | Render a view template. |
+| [res.send()](/api/response#ressend) | Send a response of various types. |
+| [res.sendFile()](/api/response#ressendfile) | Send a file as an octet stream. |
+| [res.sendStatus()](/api/response#ressendstatus) | Set the response status code and send its string representation as the response body. |
## app.route()
@@ -333,7 +344,7 @@ The following example creates a router as a module, loads a middleware function
Create a router file named `birds.js` in the app directory, with the following content:
-```js
+```cjs title="birds.cjs"
const express = require('express');
const router = express.Router();
@@ -356,9 +367,33 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware that is specific to this router
+const timeLog = (req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+};
+router.use(timeLog);
+
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
const birds = require('./birds');
// ...
@@ -366,9 +401,17 @@ const birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route.
-But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appusepath-callback--callback).
+But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor [reference](/api/application#appuse).
```js
const router = express.Router({ mergeParams: true });
diff --git a/src/content/docs/zh-tw/5x/guide/using-middleware.mdx b/src/content/docs/zh-tw/5x/guide/using-middleware.mdx
index e6b97dd47f..9e832fe09f 100644
--- a/src/content/docs/zh-tw/5x/guide/using-middleware.mdx
+++ b/src/content/docs/zh-tw/5x/guide/using-middleware.mdx
@@ -4,6 +4,7 @@ description: Learn how to use middleware in Express.js applications, including a
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
@@ -35,7 +36,7 @@ Bind application-level middleware to an instance of the [app object](/api#app) b
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -45,6 +46,17 @@ app.use((req, res, next) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+```
+
This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of
HTTP request on the `/user/:id` path.
@@ -167,7 +179,7 @@ Load router-level middleware by using the `router.use()` and `router.METHOD()` f
The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware:
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -216,12 +228,62 @@ router.get('/user/:id', (req, res, next) => {
app.use('/', router);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// a middleware function with no mount path. This code is executed for every request to the router
+router.use((req, res, next) => {
+ console.log('Time:', Date.now());
+ next();
+});
+
+// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
+router.use(
+ '/user/:id',
+ (req, res, next) => {
+ console.log('Request URL:', req.originalUrl);
+ next();
+ },
+ (req, res, next) => {
+ console.log('Request Type:', req.method);
+ next();
+ }
+);
+
+// a middleware sub-stack that handles GET requests to the /user/:id path
+router.get(
+ '/user/:id',
+ (req, res, next) => {
+ // if the user ID is 0, skip to the next router
+ if (req.params.id === '0') next('route');
+ // otherwise pass control to the next middleware function in this stack
+ else next();
+ },
+ (req, res, next) => {
+ // render a regular page
+ res.render('regular');
+ }
+);
+
+// handler for the /user/:id path, which renders a special page
+router.get('/user/:id', (req, res, next) => {
+ console.log(req.params.id);
+ res.render('special');
+});
+
+// mount the router on the app
+app.use('/', router);
+```
+
To skip the rest of the router's middleware functions, call `next('router')`
to pass control back out of the router instance.
This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
@@ -242,6 +304,28 @@ app.use('/admin', router, (req, res) => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const router = express.Router();
+
+// predicate the router with a check and bail out when needed
+router.use((req, res, next) => {
+ if (!req.headers['x-auth']) return next('router');
+ next();
+});
+
+router.get('/user/:id', (req, res) => {
+ res.send('hello, user!');
+});
+
+// use the router and 401 anything falling through
+app.use('/admin', router, (req, res) => {
+ res.sendStatus(401);
+});
+```
+
## Error-handling middleware
@@ -271,9 +355,9 @@ functions that were previously included with Express are now in separate modules
Express has the following built-in middleware functions:
-- [express.static](/api#express.static) serves static assets such as HTML files, images, and so on.
-- [express.json](/api#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
-- [express.urlencoded](/api#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
+- [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on.
+- [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+**
+- [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**
## Third-party middleware
@@ -283,11 +367,9 @@ Install the Node.js module for the required functionality, then load it in your
The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`.
-```bash
-$ npm install cookie-parser
-```
+
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
@@ -296,4 +378,14 @@ const cookieParser = require('cookie-parser');
app.use(cookieParser());
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+
+const app = express();
+
+// load the cookie-parsing middleware
+app.use(cookieParser());
+```
+
For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](/resources/middleware).
diff --git a/src/content/docs/zh-tw/5x/guide/using-template-engines.mdx b/src/content/docs/zh-tw/5x/guide/using-template-engines.mdx
index 6b74b66f11..18de44b3bf 100644
--- a/src/content/docs/zh-tw/5x/guide/using-template-engines.mdx
+++ b/src/content/docs/zh-tw/5x/guide/using-template-engines.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate and use template engines like Pug, Handle
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces
variables in a template file with actual values, and transforms the template into an HTML file sent to the client.
@@ -11,7 +12,7 @@ This approach makes it easier to design an HTML page.
The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it also supports [Handlebars](https://www.npmjs.com/package/handlebars), and [EJS](https://www.npmjs.com/package/ejs), among others.
-To render template files, set the following [application setting properties](/4x/api#app.set), in the default `app.js` created by the generator:
+To render template files, set the following [application setting properties](/api/application/#appset), in the default `app.js` created by the generator:
- `views`, the directory where the template files are located. Eg: `app.set('views', './views')`.
This defaults to the `views` directory in the application root directory.
@@ -19,9 +20,7 @@ To render template files, set the following [application setting properties](/4x
Then install the corresponding template engine npm package; for example to install Pug:
-```bash
-$ npm install pug --save
-```
+
Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`,
diff --git a/src/content/docs/zh-tw/5x/guide/writing-middleware.mdx b/src/content/docs/zh-tw/5x/guide/writing-middleware.mdx
index de62911dd9..4f58c9ec58 100644
--- a/src/content/docs/zh-tw/5x/guide/writing-middleware.mdx
+++ b/src/content/docs/zh-tw/5x/guide/writing-middleware.mdx
@@ -29,7 +29,7 @@ The remainder of this article will define and add three middleware functions to
one called `myLogger` that prints a simple log message, one called `requestTime` that
displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -40,6 +40,18 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
### Middleware function myLogger
Here is a simple example of a middleware function called "myLogger". This function just prints
@@ -65,7 +77,7 @@ but by convention it is always named "next". To avoid confusion, always use this
To load the middleware function, call `app.use()`, specifying the middleware function.
For example, the following code loads the `myLogger` middleware function before the route to the root path (/).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -83,6 +95,25 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const myLogger = function (req, res, next) {
+ console.log('LOGGED');
+ next();
+};
+
+app.use(myLogger);
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(3000);
+```
+
Every time the app receives a request, it prints the message "LOGGED" to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
@@ -105,7 +136,7 @@ const requestTime = function (req, res, next) {
The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object).
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
@@ -125,6 +156,27 @@ app.get('/', (req, res) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+
+const requestTime = function (req, res, next) {
+ req.requestTime = Date.now();
+ next();
+};
+
+app.use(requestTime);
+
+app.get('/', (req, res) => {
+ let responseText = 'Hello World! ';
+ responseText += `Requested at: ${req.requestTime}`;
+ res.send(responseText);
+});
+
+app.listen(3000);
+```
+
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
### Middleware function validateCookies
@@ -145,7 +197,7 @@ async function cookieValidator(cookies) {
Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler.
-```js
+```cjs title="index.cjs"
const express = require('express');
const cookieParser = require('cookie-parser');
const cookieValidator = require('./cookieValidator');
@@ -169,6 +221,30 @@ app.use((err, req, res, next) => {
app.listen(3000);
```
+```mjs title="index.mjs"
+import express from 'express';
+import cookieParser from 'cookie-parser';
+import cookieValidator from './cookieValidator';
+
+const app = express();
+
+async function validateCookies(req, res, next) {
+ await cookieValidator(req.cookies);
+ next();
+}
+
+app.use(cookieParser());
+
+app.use(validateCookies);
+
+// error handler
+app.use((err, req, res, next) => {
+ res.status(400).send(err.message);
+});
+
+app.listen(3000);
+```
+
Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if
@@ -187,9 +263,7 @@ For more information about Express middleware, see: [Using Express middleware](/
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
-File: `my-middleware.js`
-
-```js
+```cjs title="my-middleware.cjs"
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
@@ -198,10 +272,25 @@ module.exports = function (options) {
};
```
+```mjs title="my-middleware.mjs"
+export default function (options) {
+ return function (req, res, next) {
+ // Implement the middleware function based on the options object
+ next();
+ };
+}
+```
+
The middleware can now be used as shown below.
-```js
-const mw = require('./my-middleware.js');
+```cjs title="index.cjs"
+const mw = require('./my-middleware.cjs');
+
+app.use(mw({ option1: '1', option2: '2' }));
+```
+
+```mjs title="index.mjs"
+import mw from './my-middleware.mjs';
app.use(mw({ option1: '1', option2: '2' }));
```
diff --git a/src/content/docs/zh-tw/5x/starter/examples.mdx b/src/content/docs/zh-tw/5x/starter/examples.mdx
index 69f410e908..385c0ef3b9 100644
--- a/src/content/docs/zh-tw/5x/starter/examples.mdx
+++ b/src/content/docs/zh-tw/5x/starter/examples.mdx
@@ -45,5 +45,4 @@ Expressjs project team.
-- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
diff --git a/src/content/docs/zh-tw/5x/starter/hello-world.mdx b/src/content/docs/zh-tw/5x/starter/hello-world.mdx
index 629d697721..4c26ad0813 100644
--- a/src/content/docs/zh-tw/5x/starter/hello-world.mdx
+++ b/src/content/docs/zh-tw/5x/starter/hello-world.mdx
@@ -14,7 +14,7 @@ sub-directories for various purposes.
-```js
+```cjs title="index.cjs"
const express = require('express');
const app = express();
const port = 3000;
@@ -28,6 +28,21 @@ app.listen(port, () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+
+const app = express();
+const port = 3000;
+
+app.get('/', (req, res) => {
+ res.send('Hello World!');
+});
+
+app.listen(port, () => {
+ console.log(`Example app listening on port ${port}`);
+});
+```
+
This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests
to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**.
diff --git a/src/content/docs/zh-tw/5x/starter/installing.mdx b/src/content/docs/zh-tw/5x/starter/installing.mdx
index f6dc8220d4..30424bae35 100644
--- a/src/content/docs/zh-tw/5x/starter/installing.mdx
+++ b/src/content/docs/zh-tw/5x/starter/installing.mdx
@@ -4,6 +4,7 @@ description: Learn how to install Express.js in your Node.js environment, includ
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Before you begin, make sure you have [Node.js](https://nodejs.org/) 18 or higher installed. Then, create a directory for your application and navigate into it.
@@ -15,9 +16,7 @@ cd myapp
Use the `npm init` command to create a `package.json` file for your application.
For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json).
-```bash
-npm init
-```
+
This command prompts you for a number of things, such as the name and version of your application.
For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
@@ -30,12 +29,8 @@ Enter `app.js`, or whatever you want the name of the main file to be. If you wan
Now, install Express in the `myapp` directory and save it in the dependencies list. For example:
-```bash
-npm install express
-```
+
To install Express temporarily and not add it to the dependencies list:
-```bash
-npm install express --no-save
-```
+
diff --git a/src/content/docs/zh-tw/5x/starter/static-files.mdx b/src/content/docs/zh-tw/5x/starter/static-files.mdx
index dbadee731a..15a901a994 100644
--- a/src/content/docs/zh-tw/5x/starter/static-files.mdx
+++ b/src/content/docs/zh-tw/5x/starter/static-files.mdx
@@ -14,7 +14,7 @@ express.static(root, [options]);
```
The `root` argument specifies the root directory from which to serve static assets.
-For more information on the `options` argument, see [express.static](/api#express.static).
+For more information on the `options` argument, see [express.static](/api/express/#expressstatic).
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`:
@@ -56,7 +56,7 @@ serving static assets.
-To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api#app.use) for the static directory, as shown below:
+To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below:
```js
app.use('/static', express.static('public'));
@@ -74,9 +74,15 @@ http://localhost:3000/static/hello.html
However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve:
-```js
+```cjs title="index.cjs"
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
```
+```mjs title="index.mjs"
+import path from 'path';
+
+app.use('/static', express.static(path.join(__dirname, 'public')));
+```
+
For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static).
diff --git a/src/content/pages/de/advanced/best-practice-performance.md b/src/content/pages/de/advanced/best-practice-performance.md
index 8d00607284..5cd16ec224 100644
--- a/src/content/pages/de/advanced/best-practice-performance.md
+++ b/src/content/pages/de/advanced/best-practice-performance.md
@@ -33,7 +33,7 @@ Hier sind einige Dinge, die Sie in Ihrem Code tun können, um die Leistung Ihrer
Gzip-Komprimierung kann die Reaktionskörper erheblich verringern und damit die Geschwindigkeit einer Web-App erhöhen. Benutzen Sie die [compression](https://www.npmjs.com/package/compression) Middleware für gzip Komprimierung in Ihrer Express-App. Zum Beispiel:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-Für eine stark frequentierte Website in der Produktion, der beste Weg zur Komprimierung ist die Implementierung auf umgekehrter Proxyebene (siehe [Reverse Proxy](#use-a-reverse-proxy)) . In diesem Fall brauchen Sie keine Komprimierungsmittelware. Details zum Aktivieren der gzip-Komprimierung in Nginx finden Sie unter [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in der Nginx-Dokumentation.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### Keine synchronen Funktionen verwenden
+### Don't use synchronous functions
-Synchronische Funktionen und Methoden binden den Ausführungsprozess bis sie zurückkehren. Ein einzelner Aufruf einer synchronen Funktion kann in ein paar Mikrosekunden oder Millisekunden zurückgegeben werden auf Websites mit hohem Traffic jedoch tragen diese Anrufe dazu bei, die Performance der App zu reduzieren. Vermeiden Sie ihren Einsatz in der Produktion.
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Obwohl Node und viele Module synchrone und asynchrone Versionen ihrer Funktionen liefern, verwenden Sie immer die asynchrone Version in der Produktion. Die einzige Zeit, in der eine synchrone Funktion gerechtfertigt werden kann, ist beim ersten Start.
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-Du kannst das `--trace-sync-io` Kommandozeilen-Flag verwenden, um eine Warnung und einen Stack-Trace zu drucken, wann immer deine Anwendung eine synchrone API verwendet. Natürlich möchten Sie dies nicht in der Produktion verwenden, sondern vielmehr sicherstellen, dass Ihr Code produktionsbereit ist. Weitere Informationen finden Sie in der [Knoten Kommandozeilenoptionen Dokumentation](https://nodejs.org/api/cli.html#trace-sync-io) .
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Logging korrekt
+### Do logging correctly
-Im Allgemeinen gibt es zwei Gründe für die Protokollierung aus Ihrer App: Für das Debuggen und für die Protokollierung von App-Aktivitäten (im Wesentlichen alles andere). Die Verwendung von `console.log()` oder `console.error()` zum Drucken von Logmeldungen an das Terminal ist gängige Praxis in der Entwicklung. Aber [diese Funktionen sind synchronisiert](https://nodejs.org/api/console.html#console), wenn das Ziel ein Terminal oder eine Datei ist so dass sie nicht für die Produktion geeignet sind, es sei denn, Sie rollen die Ausgabe zu einem anderen Programm.
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### Zum Debuggen
+#### For debugging
-Wenn du zum Debuggen loggst, benutze anstelle von `console.log()` ein spezielles Debugging-Modul wie [debug](https://www.npmjs.com/package/debug). Dieses Modul ermöglicht es Ihnen, die DEBUG Umgebungsvariable zu verwenden, um zu kontrollieren, welche Debug-Meldungen an `console.error()` gesendet werden, falls vorhanden. Um deine App rein asynchron zu halten, solltest du trotzdem `console.error()` zu einem anderen Programm weiterleiten. Aber dann bist du nicht wirklich in der Produktion zu debuggen, oder?
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### Für App-Aktivitäten
+#### For app activity
-Wenn Sie App-Aktivitäten protokollieren (zum Beispiel Traffic oder API-Aufrufe), anstatt „Konsole“. og()\`, verwende eine Logging-Bibliothek wie [Pino](https://www.npmjs.com/package/pino), die schnellste und effizienteste verfügbare Option.
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### Ausnahmen richtig handhaben
+### Handle exceptions properly
-Knoten-Apps stürzen ab, wenn sie auf eine nicht gefangene Ausnahme stoßen. Wenn Sie Ausnahmen nicht bearbeiten und entsprechende Maßnahmen ergreifen, wird Ihre Express-App zum Absturz bringen und offline gehen. Wenn du dem Rat folgst [Stelle sicher, dass deine App automatisch neu startet](#ensure-your-app-automatically-restarts) unten, dann wird deine App von einem Absturz erholt. Glücklicherweise haben Express-Apps in der Regel eine kurze Startzeit. Nichtsdestotrotz wollen Sie einen Absturz vermeiden, und dazu müssen Sie die Ausnahmen ordentlich behandeln.
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-Um sicherzustellen, dass Sie mit allen Ausnahmen umgehen, verwenden Sie folgende Techniken:
+To ensure you handle all exceptions, use the following techniques:
-- [Versuchscatch](#use-try-catch)
-- [Versprechungen verwenden](#use-promises)
+- [Use try-catch](#use-try-catch)
+- [Use promises](#use-promises)
-Bevor Sie in diese Themen eintauchen, sollten Sie ein grundlegendes Verständnis von Node/Express-Fehlerbehandlung haben: Verwendung von Fehler-First Callbacks und Verbreitung von Fehlern in Middleware. Knoten verwendet eine "error-first callback"-Konvention um Fehler aus asynchronen Funktionen zurückzugeben, wobei der erste Parameter der Callback-Funktion das Fehlerobjekt ist, gefolgt von Ergebnisdaten in folgenden Parametern. Um keinen Fehler anzugeben, übergeben Sie Null als ersten Parameter. Die Callback-Funktion muss entsprechend der ersten Callback-Konvention folgen, um den Fehler sinnvoll zu bearbeiten. Und in Express ist es am besten, die next() Funktion zu nutzen, um Fehler über die Middleware-Kette zu verbreiten.
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-Für mehr über die Grundlagen der Fehlerbehandlung, siehe:
+For more on the fundamentals of error handling, see:
-- [Fehler beim Umgang mit Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Versuchsfang verwenden
+#### Use try-catch
-Try-catch ist eine JavaScript-Sprachkonstruktion, die Sie verwenden können, um Ausnahmen im synchronen Code zu fangen. Verwenden Sie zum Beispiel den versuchen Catch, um JSON-Parsing-Fehler wie unten gezeigt zu behandeln.
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-Hier ist ein Beispiel für die Verwendung von "try-catch", um eine mögliche Prozessabsturzausnahme zu bewältigen.
-Diese Middleware-Funktion akzeptiert einen Abfragefeldparameter namens "params", das ein JSON-Objekt ist.
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-Der Versuch funktioniert jedoch nur für synchrone Code. Da die Knotenplattform primär asynchron ist (insbesondere in einer Produktionsumgebung), wird der Versuch nicht viele Ausnahmen fangen.
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Versprechen verwenden
+#### Use promises
-Wenn ein Fehler in einer `async` Funktion ausgelöst wird oder ein abgelehntes Versprechen in einer `async` Funktion erwartet wird, diese Fehler werden an den Fehlerhandler übergeben, als ob `next(err)` aufgerufen würde
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-Außerdem können Sie asynchrone Funktionen für Ihre Middleware verwenden und der Router verarbeitet Fehler, wenn das Versprechen fehlschlägt, zum Beispiel:
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-Best Practices ist es, Fehler so nah wie möglich an der Website zu behandeln. So während dies jetzt im Router behandelt wird, ist es am besten, den Fehler in der Middleware zu fangen und ihn zu bearbeiten, ohne sich auf eine separate Middleware zu verlassen.
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### Was nicht zu tun
+#### What not to do
-Eine Sache, die du _nicht_ tun solltest ist, auf das `uncaptException` Event zu hören emittiert, wenn eine Ausnahme den ganzen Weg zurück zur Ereignis-Schleife weht. Das Hinzufügen eines Ereignis-Listeners für `uncaughtException` ändert das Standardverhalten des Prozesses, der auf eine Ausnahme stößt; wird der Prozess trotz der Ausnahme weiterhin laufen. Dies könnte nach einer guten Möglichkeit klingen, um zu verhindern, dass Ihre App abstürzt, aber die Anwendung nach einer nicht gefangenen Ausnahme weiterhin zu laufen ist eine gefährliche Praxis und wird nicht empfohlen, weil der Zustand des Prozesses unzuverlässig und unberechenbar wird.
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-Zusätzlich wird die Verwendung von `uncaughtException` offiziell als [crude]anerkannt (https://nodejs.org/api/process.html#event-uncaughtexception). Also ist das Hören auf `uncaughtException` eine schlechte Idee. Aus diesem Grund empfehlen wir Dinge wie mehrere Prozesse und Supervisoren: Absturz und Neustart sind oft der zuverlässigste Weg, um einen Fehler zu beheben.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-Wir empfehlen auch nicht [domains]zu verwenden (https://nodejs.org/api/domain.html). Es löst das Problem im Allgemeinen nicht und ist ein veraltetes Modul.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## Dinge zu tun in Ihrer Umgebung / Einrichtung
+## Things to do in your environment / setup
-Hier sind einige Dinge, die Sie in Ihrer Systemumgebung tun können, um die Leistung Ihrer App zu verbessern:
+Here are some things you can do in your system environment to improve your app's performance:
- [Setze NODE_ENV auf "Produktion"](#set-node_env-to-production)
- [Stelle sicher, dass deine App automatisch neu startet](#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Hier sind einige Dinge, die Sie in Ihrer Systemumgebung tun können, um die Leis
- [Lastausgleich verwenden](#use-a-load-balancer)
- [Reverse Proxy](#use-a-reverse-proxy) verwenden
-### Knoten_ENV auf "Produktion" setzen
+### Set NODE_ENV to "production"
-Die NODE_ENV Umgebungsvariable spezifiziert die Umgebung, in der eine Anwendung ausgeführt wird (normalerweise Entwicklung oder Produktion). Eines der einfachsten Dinge, die Sie tun können, um die Leistung zu verbessern, ist, NODE_ENV auf `production` zu setzen.
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-Setze NODE_ENV auf "production" makes Express:
+Setting NODE_ENV to "production" makes Express:
-- Cache-Ansichtsvorlagen.
-- Cache-CSS-Dateien, die aus CSS-Erweiterungen generiert wurden.
-- Weniger ausführliche Fehlermeldungen generieren.
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-[Tests deuten an](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/), dass dies die Leistung der App um einen Faktor von drei verbessern kann!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-Wenn Sie umweltspezifischen Code schreiben müssen, können Sie den Wert von NODE_ENV mit `process.env.NODE_ENV` überprüfen. Beachten Sie, dass die Überprüfung des Wertes einer Umgebungsvariable eine Leistungsstrafe verursacht und daher sparsam durchgeführt werden sollte.
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-In der Entwicklung setzst du in der Regel Umgebungsvariablen in deiner interaktiven Shell ein, indem du `export` oder deine `.bash_profile` Datei verwendest. Aber im Allgemeinen sollten Sie das nicht auf einem Produktionsserver tun; stattdessen sollten Sie das Init-System Ihres Betriebssystems (System) verwenden. Der nächste Abschnitt enthält weitere Details zur Verwendung Ihres Init-Systems im Allgemeinen aber das Setzen von `NODE_ENV` ist so wichtig für die Leistung (und einfach zu tun), dass es hier hervorgehoben wird.
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-Mit dem System verwenden Sie die `Environment` Direktive in Ihrer Einheitendatei. Zum Beispiel:
+With systemd, use the `Environment` directive in your unit file. Zum Beispiel:
```sh
Environment=NODE_ENV=production
```
-Weitere Informationen finden Sie unter [Umgebungsvariablen in systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### Stellen Sie sicher, dass Ihre App automatisch neu gestartet wird
+### Ensure your app automatically restarts
-In der Produktion wollen Sie nicht, dass Ihre Bewerbung offline ist. Dies bedeutet, dass Sie sicherstellen müssen, dass es sowohl neu gestartet wird, wenn die App abstürzt als auch wenn der Server selbst abstürzt. Obwohl Sie hoffen, dass keines dieser Ereignisse eintritt, müssen Sie realistischerweise beide Eventualitäten berücksichtigen von:
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- Verwendung eines Prozess-Managers, um die App (und den Knoten) neu zu starten, wenn sie abstürzt.
-- Verwendung des von Ihrem Betriebssystem zur Verfügung gestellten Init-Systems, um den Prozessmanager beim Absturz des Betriebssystems neu zu starten. Es ist auch möglich, das Init-System ohne Prozessmanager zu verwenden.
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-Knotenapplikationen stürzen ab, wenn sie eine nicht gefangene Ausnahme erleben. Das Wichtigste, was Sie tun müssen, ist, sicherzustellen, dass Ihre App gut getestet ist und alle Ausnahmen handhabt (siehe [Ausnahmen ordnungsgemäß behandeln](#handle-exceptions-properly) für Details). Aber als Fail-Safe setzen Sie einen Mechanismus, um sicherzustellen, dass wenn und wenn Ihre App abstürzt, automatisch neu gestartet wird.
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### Prozessmanager verwenden
+#### Use a process manager
-In der Entwicklung hast du deine App einfach von der Kommandozeile aus mit `node server.js` oder etwas Ähnlichem gestartet. Aber dies in der Produktion zu tun, ist ein Rezept für eine Katastrophe. Wenn die App abstürzt, wird sie offline sein, bis Sie sie neu starten. Um sicherzustellen, dass Ihre App neu gestartet wird, wenn sie abstürzt, verwenden Sie einen Prozessmanager. Ein Prozessmanager ist ein "Container" für Anwendungen, die den Einsatz erleichtern, eine hohe Verfügbarkeit bieten und Ihnen die Verwaltung der Anwendung zur Laufzeit ermöglichen.
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-Zusätzlich zum Neustart Ihrer App bei einem Absturz kann ein Prozessmanager Sie aktivieren:
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- Gewinnen Sie Einblicke in Laufzeitleistung und Ressourcenverbrauch.
-- Ändern Sie die Einstellungen dynamisch, um die Leistung zu verbessern.
-- Steuerung Clustering (pm2).
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-Historisch war es beliebt, einen Node.js Prozessmanager wie [PM2](https://github.com/Unitech/pm2) zu verwenden. Lesen Sie deren Dokumentation, wenn Sie dies tun möchten. Wir empfehlen jedoch, Ihr Init-System für das Prozessmanagement zu verwenden.
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### Init-System verwenden
+#### Use an init system
-Die nächste Ebene der Zuverlässigkeit besteht darin, sicherzustellen, dass Ihre App beim Neustart des Servers neu gestartet wird. Systeme können aus verschiedenen Gründen immer noch heruntergehen. Um sicherzustellen, dass Ihre App neu gestartet wird, wenn der Server abstürzt, verwenden Sie das Init-System, das in Ihr Betriebssystem integriert wurde. Das heute verwendete Hauptinitsystem ist [systemd](https://wiki.debian.org/systemd).
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Es gibt zwei Möglichkeiten, Init-Systeme mit Ihrer Express-App zu verwenden:
+There are two ways to use init systems with your Express app:
-- Führen Sie Ihre App in einem Prozessmanager aus und installieren Sie den Prozessmanager als Service mit dem Init-System. Der Prozessmanager startet Ihre App neu, wenn die App abstürzt, und das Init-System startet den Prozessmanager beim Neustart des Betriebssystems neu. Dies ist der empfohlene Ansatz.
-- Führen Sie Ihre App (und Ihren Knoten) direkt mit dem Init-System aus. Das ist etwas einfacher, aber Sie haben nicht die zusätzlichen Vorteile eines Prozessmanagers.
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-Systemd ist ein Linux System und Service Manager. Die meisten großen Linux-Distributionen haben System als Standard-Init-System übernommen.
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-Eine Systemd-Service-Konfigurationsdatei heißt _unit file_, mit einem Dateinamen endet in `.service`. Hier ist eine Beispiel-Einheitsdatei, um eine Knoten-App direkt zu verwalten. Ersetzen Sie die Werte in `` für Ihr System und App:
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-Weitere Informationen zum System finden Sie unter [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Starte deine App in einem Cluster
+### Run your app in a cluster
-In einem Multi-Core-System können Sie die Leistung einer Knoten-App um ein Vielfaches erhöhen, indem Sie einen Cluster von Prozessen starten. Ein Cluster führt mehrere Instanzen der App aus, idealerweise eine Instanz auf jedem CPU-Core, wodurch die Last und Aufgaben auf die Instanzen verteilt werden.
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
-
+
-WICHTIG: Da die App-Instanzen als separate Prozesse laufen, teilen sie nicht den gleichen Speicherplatz. Das heißt, Objekte sind lokal für jede Instanz der App. Daher können Sie den Status im Anwendungscode nicht beibehalten. Du kannst jedoch einen Speicherdatenspeicher wie [Redis](http://redis.io/) verwenden, um Sitzungsdaten und -status zu speichern. Dieser Vorbehalt bezieht sich im Wesentlichen auf alle Formen der horizontalen Skalierung, sei es beim Clustering mit mehreren Prozessen oder mehreren physischen Servern.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-In geclusterten Apps können Worker-Prozesse individuell abstürzen, ohne den Rest der Prozesse zu beeinträchtigen. Abgesehen von den Leistungsvorteilen ist die Fehlerisolierung ein weiterer Grund, einen Cluster von App-Prozessen auszuführen. Immer wenn ein Worker-Prozess abstürzt, vergewissern Sie sich, das Ereignis zu protokollieren und einen neuen Prozess mit cluster.fork() zu erzeugen.
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### Cluster-Modul des Knotens
+#### Using Node's cluster module
-Clustering wird mit Knotens [Cluster-Modul](https://nodejs.org/api/cluster.html) ermöglicht. Dies ermöglicht es einem Master-Prozess, Worker-Prozesse zu generieren und eingehende Verbindungen unter den Arbeitern zu verteilen.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### PM2 verwenden
+#### Using PM2
-Wenn Sie Ihre Anwendung mit PM2 bereitstellen, können Sie die Vorteile des Clustering _without out_ Ändern Ihres Anwendungscodes nutzen. Du solltest sicherstellen, dass deine [Anwendung zustandslos ist](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) zuerst , was bedeutet, dass keine lokalen Daten im Prozess gespeichert werden (wie Sessions, Websocket-Verbindungen und dergleichen).
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-Wenn du eine Anwendung mit PM2 ausführst, kannst du den **Cluster-Modus** aktivieren, um ihn in einem Cluster mit einer Anzahl von Instanzen deiner Wahl auszuführen zum Beispiel die übereinstimmende Anzahl der verfügbaren CPUs. Du kannst die Anzahl der Prozesse im Cluster manuell mit dem Kommandozeilenwerkzeug `pm2` ändern, ohne die App zu stoppen.
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-Um den Cluster-Modus zu aktivieren, starten Sie Ihre Anwendung so:
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-Dies kann auch innerhalb einer PM2-Prozessdatei konfiguriert werden (`ecosystem.config. s` oder ähnlich) indem `exec_mode` auf `cluster` und `instances` auf die Anzahl der zu startenden Arbeiter gesetzt wird.
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-Nach dem Ausführen kann die Anwendung so skaliert werden:
+Once running, the application can be scaled like so:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-Weitere Informationen zum Clustering mit PM2 finden Sie unter [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in der PM2-Dokumentation.
+For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### Cache-Abfrageergebnisse
+### Cache request results
-Eine weitere Strategie zur Verbesserung der Leistung in der Produktion ist das Cache-Ergebnis von Anfragen so dass Ihre App die Operation nicht wiederholt, um dieselbe Anfrage wiederholt zu bedienen.
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Benutze einen Caching-Server wie [Varnish](https://www.varnish-cache.org/) oder [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (siehe auch [Nginx Caching](https://serversforhackers.com/nginx-caching/)) um die Geschwindigkeit und Leistung deiner App deutlich zu verbessern.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Lastausgleich verwenden
+### Use a load balancer
-Egal wie optimiert eine App ist, eine einzelne Instanz kann nur eine begrenzte Menge an Last und Traffic verwalten. Eine Möglichkeit, eine App zu skalieren, besteht darin, mehrere Instanzen davon auszuführen und den Traffic über einen Lastausgleicher zu verteilen. Das Einrichten eines Lastausgleichs kann die Leistung und Geschwindigkeit Ihrer App verbessern und es ermöglichen, mehr zu skalieren, als mit einer einzigen Instanz möglich ist.
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-Ein Loadbalancer ist in der Regel ein Reverse-Proxy, der den Datenverkehr zu und von mehreren Anwendungsinstanzen und Servern regelt. Mit [Nginx](https://nginx.org/en/docs/http/load_balancing.html) oder [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) können Sie ganz einfach einen Lastausgleich für Ihre App einrichten.
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-Bei Loadbalancing müssen Sie eventuell sicherstellen, dass Anforderungen, die mit einer bestimmten Session-ID in Verbindung stehen, mit dem Prozess verbunden sind, der sie verursacht hat. Dies ist _session_, oder _sticky sessions_, bekannt und kann durch den oben genannten Vorschlag angesprochen werden, um einen Datenspeicher wie Redis für Sitzungsdaten (je nach Anwendung) zu verwenden. Für eine Diskussion siehe [Mehrere Knoten verwenden](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### Reverse-Proxy verwenden
+### Use a reverse proxy
-Ein Reverse Proxy sitzt vor einer Web-App und führt unterstützende Operationen auf den Anfragen aus, abgesehen von der Weiterleitung von Anfragen an die App. Es kann Fehlerseiten, Komprimierung, Caching, Servieren von Dateien und laden Balancing unter anderem.
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Die Übergabe von Aufgaben, die keine Kenntnisse des Anwendungszustands an einen Reverse Proxy erfordern, gibt Express frei, spezielle Anwendungsaufgaben durchzuführen. Aus diesem Grund wird empfohlen, Express in der Produktion hinter einem umgekehrten Proxy wie [Nginx](https://www.nginx.org/) oder [HAProxy](https://www.haproxy.org/) auszuführen.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/de/advanced/best-practice-security.mdx b/src/content/pages/de/advanced/best-practice-security.mdx
index 7979ce1d32..52d205e86a 100644
--- a/src/content/pages/de/advanced/best-practice-security.mdx
+++ b/src/content/pages/de/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Entdecken Sie wichtige Sicherheits-Best Practices für Express-Apps
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Der Begriff _"production"_ bezieht sich auf die Stufe im Software-Lebenszyklus, wenn eine Anwendung oder API allgemein für Endbenutzer oder Verbraucher verfügbar ist. Im Gegensatz dazu, in der _"development"_ Bühne, Sie immer noch aktiv schreiben und Test-Code, und die Anwendung ist nicht offen für externen Zugriff. Die entsprechenden Systemumgebungen werden als _production_ bzw. _development_ Umgebungen bezeichnet.
@@ -18,21 +19,19 @@ Richtlinien und Prozeduren.
Best Practices für Express-Anwendungen in der Produktion beinhalten:
-- [Beste Produktionspraktiken: Sicherheit](#production-best-practices-security)
- - [Overview](#overview)
- - [Veraltete oder verwundbare Versionen von Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Benutze TLS](#use-tls)
- - [Nicht auf Benutzereingabe vertrauen](#do-not-trust-user-input)
- - [Verhindere offene Weiterleitungen](#prevent-open-redirects)
- - [Helm verwenden](#use-helmet)
- - [Fingerabdruck reduzieren](#reduce-fingerprinting)
- - [Cookies sicher verwenden](#use-cookies-securely)
- - [Benutze nicht den Standard-Sitzungs-Cookie Name](#dont-use-the-default-session-cookie-name)
- - [Cookie Sicherheitseinstellungen setzen](#set-cookie-security-options)
- - [Verhindere Brute-Force-Angriffe gegen Autorisierung](#prevent-brute-force-attacks-against-authorization)
- - [Vergewissern Sie sich, dass Ihre Abhängigkeiten sicher sind](#ensure-your-dependencies-are-secure)
- - [Vermeide andere bekannte Schwachstellen aus](#avoid-other-known-vulnerabilities)
- - [Zusätzliche Überlegungen](#additional-considerations)
+- [Veraltete oder verwundbare Versionen von Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Benutze TLS](#use-tls)
+- [Nicht auf Benutzereingabe vertrauen](#do-not-trust-user-input)
+ - [Verhindere offene Weiterleitungen](#prevent-open-redirects)
+- [Helm verwenden](#use-helmet)
+- [Fingerabdruck reduzieren](#reduce-fingerprinting)
+- [Cookies sicher verwenden](#use-cookies-securely)
+ - [Benutze nicht den Standard-Sitzungs-Cookie Name](#dont-use-the-default-session-cookie-name)
+ - [Cookie Sicherheitseinstellungen setzen](#set-cookie-security-options)
+- [Verhindere Brute-Force-Angriffe gegen Autorisierung](#prevent-brute-force-attacks-against-authorization)
+- [Vergewissern Sie sich, dass Ihre Abhängigkeiten sicher sind](#ensure-your-dependencies-are-secure)
+ - [Vermeide andere bekannte Schwachstellen aus](#avoid-other-known-vulnerabilities)
+- [Zusätzliche Überlegungen](#additional-considerations)
## Veraltete oder verwundbare Versionen von Express nicht verwenden
@@ -44,7 +43,7 @@ Vergewissern Sie sich auch, dass Sie keine der verwundbaren Express-Versionen au
Wenn Ihre App sensible Daten behandelt oder übermittelt, verwenden Sie [Transport-Layer-Sicherheit](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) um die Verbindung und die Daten zu sichern. Diese Technologie verschlüsselt Daten, bevor sie vom Client an den Server gesendet werden, und verhindert so einige häufige (und einfache) Hacks. Obwohl Ajax und POST Anfragen möglicherweise nicht sichtbar sind und im Browser "versteckt" zu sein scheinen, ihr Netzwerkverkehr ist anfällig für [Paket-Sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) und [Man-in-the-middle-Angriffe](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-Sie können mit der Verschlüsselung Secure Socket Layer (SSL) vertraut sein. [TLS ist einfach die nächste Weiterentwicklung von SSL](). Mit anderen Worten: Wenn Sie SSL zuvor verwendet haben, sollten Sie ein Upgrade auf TLS in Betracht ziehen. Im Allgemeinen empfehlen wir Nginx mit TLS umzugehen. Für eine gute Referenz zum Konfigurieren von TLS auf Nginx (und anderen Servern) siehe [Empfohlene Server-Konfigurationen (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+Sie können mit der Verschlüsselung Secure Socket Layer (SSL) vertraut sein. Im Allgemeinen empfehlen wir Nginx mit TLS umzugehen. Mit anderen Worten: Wenn Sie SSL zuvor verwendet haben, sollten Sie ein Upgrade auf TLS in Betracht ziehen. Mit anderen Worten: Wenn Sie SSL zuvor verwendet haben, sollten Sie ein Upgrade auf TLS in Betracht ziehen. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Ein praktisches Werkzeug, um ein kostenloses TLS-Zertifikat zu erhalten, ist [Let's Encrypt](https://letsencrypt.org/about/), ein kostenloses und automatisiertes TLS-Zertifikat und offene Zertifizierungsstelle (CA) zur Verfügung gestellt von der [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Jeder Header kann konfiguriert oder deaktiviert werden. Um mehr darüber zu erfa
Helm wie jedes andere Modul installieren:
-```bash
-$ npm install helmet
-```
+
Dann verwenden Sie es in Ihrem Code:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Fingerabdruck verringern
Es kann helfen, eine zusätzliche Sicherheitsschicht zu bieten, um die Fähigkeit von Angreifern zu verringern,
@@ -177,7 +184,7 @@ Die Verwendung des Standard-Sitzungs-Cookie-Namens kann Ihre App für Angriffe
Um dieses Problem zu vermeiden, verwenden Sie generische Cookie-Namen; zum Beispiel [express-session](https://www.npmjs.com/package/express-session) Middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Cookie-Sicherheitsoptionen festlegen
Legen Sie die folgenden Cookie-Optionen fest, um die Sicherheit zu verbessern:
@@ -200,7 +219,7 @@ Legen Sie die folgenden Cookie-Optionen fest, um die Sicherheit zu verbessern:
Hier ist ein Beispiel mit [cookie-session](https://www.npmjs.com/package/cookie-session) Middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Brute-Force-Angriffe gegen Autorisierung verhindern
Stellen Sie sicher, dass Login-Endpunkte geschützt sind, um private Daten sicherer zu machen.
@@ -244,7 +285,7 @@ $ npm audit
Wenn du sicherer bleiben möchtest, bedenke [Snyk](https://snyk.io/).
-Snyk bietet sowohl ein [Kommandozeilenwerkzeug](https://www.npmjs.com/package/snyk) als auch eine [Github-Integration](https://snyk.io/docs/github), die Ihre Anwendung auf [Snyk's Open-Source-Verwundbarkeitsdatenbank](https://snyk.io/vuln/) auf bekannte Verwundbarkeiten in Ihren Abhängigkeiten überprüft. Installieren Sie das CLI wie folgt:
+Snyk bietet sowohl ein [Kommandozeilenwerkzeug](https://www.npmjs.com/package/snyk) als auch eine [Github-Integration](https://snyk.io/docs/github), die Ihre Anwendung auf [Snyk's Open-Source-Verwundbarkeitsdatenbank](https://snyk.io/vuln/) auf bekannte Verwundbarkeiten in Ihren Abhängigkeiten überprüft. Installieren Sie das CLI wie folgt: Install the CLI as follows:
```bash
$ npm install -g snyk
@@ -259,7 +300,7 @@ $ snyk test
### Vermeiden Sie andere bekannte Schwachstellen
-Halten Sie Ausschau nach [Node Security Project](https://npmjs.com/advisories) oder [Snyk](https://snyk.io/vuln/) Ankündigungen, die Express oder andere Module, die Ihre App verwendet, beeinflussen können. Im Allgemeinen sind diese Datenbanken ausgezeichnete Ressourcen für Wissen und Werkzeuge rund um die Knotensicherheit.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. Im Allgemeinen sind diese Datenbanken ausgezeichnete Ressourcen für Wissen und Werkzeuge rund um die Knotensicherheit.
Schließlich können Express-Apps—wie alle anderen Web-Apps—anfällig für eine Vielzahl webbasierter Angriffe sein. Vertrauen Sie sich mit bekannten [Web-Verwundbarkeiten](https://www.owasp.org/www-project-top-ten/) und ergreifen Sie Vorsichtsmaßnahmen, um sie zu vermeiden.
diff --git a/src/content/pages/de/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/de/advanced/healthcheck-graceful-shutdown.md
index df8006c126..be14170367 100644
--- a/src/content/pages/de/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/de/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Gesundheitschecks
-Ein Lastausgleicher verwendet Gesundheitsprüfungen, um festzustellen, ob eine Anwendungsinstanz gesund ist und Anfragen annehmen kann. Zum Beispiel [Kubernetes hat zwei Gesundheitschecke](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+Ein Lastausgleicher verwendet Gesundheitsprüfungen, um festzustellen, ob eine Anwendungsinstanz gesund ist und Anfragen annehmen kann. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- 'liveness', das bestimmt, wann ein Container neu gestartet werden soll.
- `readiness`, das bestimmt, wann ein Container bereit ist, den Verkehr zu akzeptieren. Wenn ein Pod nicht bereit ist, wird er aus den Lastausgleichern entfernt.
diff --git a/src/content/pages/de/guide/database-integration.mdx b/src/content/pages/de/guide/database-integration.mdx
index 3a360e6af2..fa2406e688 100644
--- a/src/content/pages/de/guide/database-integration.mdx
+++ b/src/content/pages/de/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Erfahren Sie, wie Sie verschiedene Datenbanken mit Express.js Anwen
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Hinzufügen der Möglichkeit, Datenbanken mit Express-Apps zu verbinden, ist nur eine Frage des Laden eines geeigneten Node.js Treibers für die Datenbank in Ihrer App. Dieses Dokument erklärt kurz wie Sie einige der beliebtesten Node.js-Module für Datenbanksysteme in Ihrer Express-App hinzufügen und nutzen:
@@ -34,13 +35,11 @@ Diese Datenbanktreiber sind unter vielen verfügbar. Für andere Optionen suchen
### Installation
-```bash
-$ npm install cassandra-driver
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**Modul**: [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installation
-```bash
-$ npm install couchbase
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**Modul**: [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### Installation
-```bash
-$ npm install nano
-```
+
### Beispiel
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**Modul**: [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Installation
-```bash
-$ npm install level levelup leveldown
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**Modul**: [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installation
-```bash
-$ npm install mysql
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**Modul**: [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installation
-```bash
-$ npm install mongodb
-```
+
-### Beispiel (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### Beispiel (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-Wenn du einen Objektmodelltreiber für MongoDB möchtest, schau dir [Mongoose]an (https://github.com/LearnBoost/mongoose).
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**Modul**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Installation
-```bash
-$ npm install neo4j-driver
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
-## Jürgen
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
-**Modul**: [oracledb](https://github.com/oracle/node-oracledb)
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
+## Oracle
+
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Installation
-HINWEIS: [Siehe die Installationsvoraussetzungen](https://github.com/oracle/node-oracledb#-installation).
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**Modul**: [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installation
-```bash
-$ npm install pg-promise
-```
+
### Beispiel
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**Modul**: [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### Installation
-```bash
-$ npm install redis
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
-## SQL-Server
+```mjs title="index.mjs"
+import redis from 'redis';
-**Modul**: [tedious](https://github.com/tediousjs/tedious)
+const client = redis.createClient();
-### Installation
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
-```bash
-$ npm install tedious
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
```
+## SQL Server
+
+**Module**: [tedious](https://github.com/tediousjs/tedious)
+
+### Installation
+
+
+
### Beispiel
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**Modul**: [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Installation
-```bash
-$ npm install sqlite3
-```
+
### Beispiel
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -463,17 +588,15 @@ db.close();
## Elasticsearch
-**Modul**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Installation
-```bash
-$ npm install elasticsearch
-```
+
### Beispiel
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/de/guide/migrating-4.mdx b/src/content/pages/de/guide/migrating-4.mdx
index 0d9a92fe58..d3fe3b87ca 100644
--- a/src/content/pages/de/guide/migrating-4.mdx
+++ b/src/content/pages/de/guide/migrating-4.mdx
@@ -4,41 +4,23 @@ description: Eine Anleitung zur Migration Ihrer Express.js Anwendungen von Versi
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 ist ein brillanter Wechsel von Express 3. Das bedeutet, dass eine bestehende Express 3-App _nicht_ funktioniert, wenn Sie die Express-Version in ihren Abhängigkeiten aktualisieren.
Dieser Artikel Covers:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Änderungen in Express 4
Es gibt mehrere bedeutende Änderungen in Express 4:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
Siehe auch:
@@ -254,7 +236,7 @@ Das folgende Beispiel erzeugt einen Router als Modul, lädt Middleware in
Erstelle zum Beispiel eine Router-Datei namens `birds.js` im App-Verzeichnis,
mit folgendem Inhalt:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -275,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Laden Sie dann das Router-Modul in der App:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -285,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
Die App wird nun in der Lage sein, Anfragen an die `/birds` und
`/birds/about` Pfade zu bearbeiten, und ruft die "timeLog"
Middleware auf, die spezifisch für die Route ist.
@@ -300,29 +312,27 @@ Die folgende Tabelle listet weitere kleine, aber wichtige Änderungen in Express
| Node.js |
-
- Express 4 benötigt Node.js 0.10.x oder höher und hat die Unterstützung für Node.js 0.8.x
- fallen gelassen.
- |
+ Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` |
Das `http` Modul wird nicht mehr benötigt, außer du musst direkt mit ihm
- (socket.io/SPDY/HTTPS) arbeiten. Die App kann über die Funktion `app.listen()` gestartet
- werden.
+ (socket.io/SPDY/HTTPS) arbeiten. The app can be started by using the `app.listen()` function.
|
| `app.configure()` |
- Die Funktion `app.configure()` wurde entfernt. Benutze die Funktion `process.env.NODE_ENV`
- oder `app.get('env')` um die Umgebung zu erkennen und die App entsprechend zu konfigurieren.
+ Die Funktion `app.configure()` wurde entfernt. Use the `process.env.NODE_ENV` or
+ `app.get('env')` function to detect the environment and configure the app accordingly.
|
| `json spaces` |
- Die Eigenschaft `json spaces` ist standardmäßig in Express 4 deaktiviert. |
+
+ The `json spaces` application property is disabled by default in Express 4.
+ |
| `req.accepted()` |
@@ -379,7 +389,7 @@ Die Dateien von Interesse sind `app.js` und `package.json`.
Betrachten Sie eine Express v.3 Anwendung mit der folgenden `app.js` Datei:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -413,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### "package.json"
The accompanying version 3 `package.json` file might look
@@ -433,15 +477,13 @@ something like this:
}
```
-### Verarbeiten
+### Process
Beginnen Sie den Migrationsprozess, indem Sie die benötigte Middleware für die
Express 4 App installieren und Express und Pug mit folgendem Befehl auf ihre jeweils neueste
Version aktualisieren:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Folgende Änderungen an `app.js` vornehmen:
@@ -491,7 +533,7 @@ Das Ausführen des obigen `npm` Befehls wird `package.json` wie folgt aktualisie
Entferne dann ungültigen Code, lade die benötigte Middleware und führe bei Bedarf andere
Änderungen durch. Die `app.js` Datei wird folgendermaßen aussehen:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -541,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
Wenn du nicht direkt mit dem `http` Modul (socket.io/SPDY/HTTPS) arbeiten musst, ist das Laden nicht erforderlich, und die App kann einfach auf diese Weise gestartet werden:
@@ -576,18 +667,14 @@ den Express 3 App-Generator deinstallieren und dann den neuen
Wenn Sie bereits den Express 3 App-Generator auf Ihrem System installiert haben,
müssen Sie ihn deinstallieren:
-```bash
-$ npm uninstall -g express
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
Jetzt den neuen Generator installieren:
-```bash
-$ npm install -g express-generator
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
diff --git a/src/content/pages/de/guide/migrating-5.mdx b/src/content/pages/de/guide/migrating-5.mdx
index d0847c02b5..f461d96a1d 100644
--- a/src/content/pages/de/guide/migrating-5.mdx
+++ b/src/content/pages/de/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: Eine umfassende Anleitung zur Migration Ihrer Express.js-Anwendunge
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 5 unterscheidet sich nicht sehr von Express 4; obwohl es die gleiche grundlegende API hat, gibt es immer noch Änderungen, die die Kompatibilität mit der vorherigen Version stören. Daher könnte eine Anwendung mit Express 4 nicht funktionieren, wenn Sie sie auf Express 5 aktualisieren.
@@ -11,9 +12,7 @@ Express 5 unterscheidet sich nicht sehr von Express 4; obwohl es die gleiche gru
Um diese Version zu installieren, benötigst du eine **Node.js Version 18 oder höher**. Führen Sie dann den folgenden Befehl in Ihrem Anwendungsverzeichnis aus:
-```sh
-npm install "express@5"
-```
+
Sie können dann Ihre automatisierten Tests durchführen, um zu sehen, was fehlschlägt, und Probleme gemäß den unten aufgeführten Updates beheben. Nach dem Beheben von Testfehlern führen Sie Ihre App aus, um zu sehen, welche Fehler auftreten. Sie werden sofort erfahren, ob die App Methoden oder Eigenschaften verwendet, die nicht unterstützt werden.
@@ -23,15 +22,11 @@ Um Ihnen zu helfen, Ihren Expressserver zu migrieren Wir haben eine Reihe von Co
Führen Sie den folgenden Befehl aus, um alle verfügbaren Codemods auszuführen:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
Wenn du eine bestimmte Codemod ausführen möchtest, kannst du folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
Du findest die Liste der verfügbaren Codemoden [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Anfangs wurde `del` anstelle von `delete` verwendet, da `delete` ein reservierte
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -80,9 +73,7 @@ Die folgenden Methodennamen wurden pluralisiert. In Express 4 führte die Verwen
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -101,9 +92,9 @@ Oder Sie können Ihren Code manuell aktualisieren:
### Führender Doppelpunkt (:) im Namen von app.param(name, fn)
-Ein führendes Doppelzeichen (:) im Namen der `app. aram(name, fn)` Funktion ist ein Überbleibsel von Express 3, und um der Abwärtskompatibilität willen hat Express 4 sie mit einer Veraltungsmeldung unterstützt. Express 5 ignoriert es stillschweigend und verwendet den Namensparameter, ohne ihn mit einem Doppelpunkt zu präfixieren.
+In Express 4 waren unpassende Platzhalter leere Zeichenketten (`''`) und optionale `:` Parameter (mit `?`) hatten einen Schlüssel mit dem Wert `undefiniert`. In Express 5 werden unübertroffene Parameter vollständig aus `req.params` entfernt.
-Dies sollte deinen Code nicht beeinflussen, wenn du der Express-4-Dokumentation von [app.param]folgst (/en/4x/api#app.param), da es keine Erwähnung des führenden Doppelpunkts.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(Name)
@@ -113,9 +104,7 @@ Diese potenziell verwirrende und gefährliche Methode zum Abrufen von Formularda
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -134,15 +123,13 @@ Oder Sie können Ihren Code manuell aktualisieren:
### res.json(obj, Status)
-Express 5 unterstützt nicht mehr die Signatur `res.json(obj, status)`. Setze stattdessen den Status und verkette ihn auf die Methode `res.json()` wie folgt: `res.status(status).json(obj)`.
+Express 5 unterstützt nicht mehr die Signatur `res.jsonp(obj, status)`. Setze stattdessen den Status und verkette ihn auf die `res.jsonp()` Methode wie folgt: `res.status(status).jsonp(obj)`.
#### Wie aktualisiere ich
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -155,15 +142,13 @@ Oder Sie können Ihren Code manuell aktualisieren:
### res.jsonp(obj, status)
-Express 5 unterstützt nicht mehr die Signatur `res.jsonp(obj, status)`. Setze stattdessen den Status und verkette ihn auf die `res.jsonp()` Methode wie folgt: `res.status(status).jsonp(obj)`.
+Express 5 unterstützt nicht mehr die Signatur `res.json(obj, status)`. Setze stattdessen den Status und verkette ihn auf die Methode `res.json()` wie folgt: `res.status(status).json(obj)`.
#### Wie aktualisiere ich
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -182,16 +167,19 @@ Express 5 unterstützt nicht mehr die Signatur `res.redirect(url, status)`. Verw
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 unterstützt nicht mehr den magischen String `back` in den Methoden `r
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -224,9 +210,7 @@ Express 5 unterstützt nicht mehr die Signatur `res.send(obj, status)`. Setze st
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -246,9 +230,7 @@ Wenn Sie eine Nummer mit Hilfe der `res senden müssen. end()` Funktion, zitiert
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -267,9 +249,7 @@ Die `res.sendfile()` Funktion wurde durch eine camel-cased Version `res.sendFile
Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Oder Sie können Ihren Code manuell aktualisieren:
@@ -284,6 +264,10 @@ Oder Sie können Ihren Code manuell aktualisieren:
Die `hidden` und `from` Optionen für `res.sendFile()` werden nicht mehr unterstützt. Benutze stattdessen `dotfiles` und `root`.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### Wie aktualisiere ich
```diff
@@ -293,12 +277,30 @@ Die `hidden` und `from` Optionen für `res.sendFile()` werden nicht mehr unterst
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### express.static() Optionen
Die `hidden` und `from` Optionen für `express.static()` werden nicht mehr unterstützt. Benutze stattdessen `dotfiles` und `root`. Beachte, dass `from` nie in der API dokumentiert wurde, aber als Alias für `root` akzeptiert wurde. Der Standardwert von `dotfiles` ist jetzt `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### Wie aktualisiere ich
+Sie können Ihren Code automatisch aktualisieren, indem Sie den folgenden Befehl ausführen:
+
+
+
+Oder Sie können Ihren Code manuell aktualisieren:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ Die `hidden` und `from` Optionen für `express.static()` werden nicht mehr unter
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
Die Signatur `router.param(fn)` wurde verwendet, um das Verhalten der `router.param(name, fn)` Funktion zu ändern. Es ist seit v4.11.0 veraltet und Express 5 unterstützt es überhaupt nicht mehr.
@@ -449,6 +458,25 @@ Servieren Sie spezifische dot-Verzeichnisse explizit mit der Option `dotfiles: "
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### Wie aktualisiere ich
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### app.hören
In Express 5 ruft die `app.listen` Methode die vom Benutzer zur Verfügung gestellte Callback-Funktion auf, wenn der Server ein Fehlerereignis erhält. In Express 4 würden solche Fehler aufgeworfen. Diese Änderung verlagert die Verantwortung für die Fehlerbehandlung auf die Callback-Funktion in Express 5. Wenn ein Fehler auftritt, wird er als Argument an den Callback übergeben.
@@ -491,7 +519,7 @@ Das `req.params` Objekt hat nun einen **null Prototyp** wenn man String Pfade be
**Wildcard-Parameter sind jetzt Arrays:**
-Platzhalter (z.B. `/*splat`) erfassen Pfadsegmente als Array anstelle eines einzelnen Strings.
+`/*splat`) erfassen Pfadsegmente als Array anstelle eines einzelnen Strings.
```js
app.get('/*splat', (req, res) => {
diff --git a/src/content/pages/de/resources/contributing.mdx b/src/content/pages/de/resources/contributing.mdx
index 2c6d3ec0e0..29dabf0b58 100644
--- a/src/content/pages/de/resources/contributing.mdx
+++ b/src/content/pages/de/resources/contributing.mdx
@@ -150,13 +150,11 @@ Projekt teilnimmt. Sie sollten
mit Code-Beiträgen und trillierenden Problemen unterstützen. Sie müssen
auch 2FA auf ihren GitHub und npm Konten aktiviert haben.
-Jedes TC-Mitglied oder ein existierender Kapitän im **gleichen** Repository kann einen anderen Committer
-für die Hauptleiterrolle nominieren. Um dies zu tun, sollten sie diesem Dokument eine PR-Mitteilung vorlegen. aktualisiere den Abschnitt
-**Active Project Captains** (während die Sortierreihenfolge beibehalten wird) mit dem Namen des Projekts
-der GitHub Handle des Kandidaten und ihr npm Benutzername (falls unterschiedlich).
+Ein TC-Mitglied oder ein existierender Repo-Kapitän **im selben Projekt** kann einen neuen Kapitän nominieren. Repo-Kapitän aus anderen Projekten sollten keine Kapitän für ein anderes Projekt nominieren.
- Repos können so viele Kapitän haben, wie sinnvoll für den Umfang der Arbeit.
-- Ein TC-Mitglied oder ein existierender Repo-Kapitän **im selben Projekt** kann einen neuen Kapitän nominieren.
+- Jedes TC-Mitglied oder ein existierender Kapitän im **gleichen** Repository kann einen anderen Committer
+ für die Hauptleiterrolle nominieren.
Repo-Kapitän aus anderen Projekten sollten keine Kapitän für ein anderes Projekt nominieren.
Die PR benötigt mindestens 2 Genehmigungen von TC-Mitgliedern und 2 Wochen Wartezeit, um
@@ -188,7 +186,7 @@ Jeder kann aus persönlichen oder beruflichen Gründen einen vorübergehenden Au
#### Verantwortlichkeit
-- Der Technische Ausschuss (TC) und die jeweiligen Kapitän jedes Pakets/Teams sind dafür verantwortlich, die Aktivitätsniveaus zu bewerten und diese Richtlinie fair und transparent umzusetzen. in Abstimmung mit anderen relevanten Teams.
+- Der Technische Ausschuss (TC) und die jeweiligen Kapitän jedes Pakets/Teams sind dafür verantwortlich, die Aktivitätsniveaus zu bewerten und diese Richtlinie fair und transparent umzusetzen.
- Im Falle von Meinungsverschiedenheiten kann die Situation durch Konsens innerhalb des TC oder eines entsprechenden Teams diskutiert und gelöst werden.
### Entwickler-Ursprungszertifikat 1.1
diff --git a/src/content/pages/de/resources/glossary.mdx b/src/content/pages/de/resources/glossary.mdx
index f476e41aa9..b5ae63f3fa 100644
--- a/src/content/pages/de/resources/glossary.mdx
+++ b/src/content/pages/de/resources/glossary.mdx
@@ -27,7 +27,7 @@ Eine Funktion, die von der Express-Routing Layer vor dem letzten Request-Handler
- `var foo = require('middleware')` heißt _requiring_ oder _using_ ein Node.js Modul. Dann gibt die Anweisung `var mw = foo()` typischerweise die Middleware zurück.
- `app.use(mw)` heißt _adding the middleware to the global processing stack_.
-- `app.get('/foo', mw, function (req, res) { ... })` heißt _adding the middleware to the "GET /foo" processing stack_.
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
@@ -46,11 +46,11 @@ und hyphenieren ein Compound Adjektiv.
## anfragen
-Eine HTTP-Anfrage. Ein Client sendet eine HTTP-Anfrage an einen Server, der eine Antwort zurückgibt. Die Anfrage muss eine von mehreren [Anfragemethoden](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) wie GET, POST usw. verwenden.
+Eine HTTP-Antwort. Ein Server gibt dem Client eine HTTP-Antwortmeldung zurück. Die Antwort enthält Vollständigkeitsinformationen über die Anfrage und kann auch angeforderte Inhalte in ihrem Nachrichtentext enthalten.
## antwort
-Eine HTTP-Antwort. Ein Server gibt dem Client eine HTTP-Antwortmeldung zurück. Die Antwort enthält Vollständigkeitsinformationen über die Anfrage und kann auch angeforderte Inhalte in ihrem Nachrichtentext enthalten.
+Eine HTTP-Anfrage. Ein Client sendet eine HTTP-Anfrage an einen Server, der eine Antwort zurückgibt. Die Antwort enthält Vollständigkeitsinformationen über die Anfrage und kann auch angeforderte Inhalte in ihrem Nachrichtentext enthalten.
## routen
diff --git a/src/content/pages/de/resources/index.mdx b/src/content/pages/de/resources/index.mdx
index aa2b38cf01..9fa8164788 100644
--- a/src/content/pages/de/resources/index.mdx
+++ b/src/content/pages/de/resources/index.mdx
@@ -23,7 +23,7 @@ Finden Sie Ressourcen, um das Express.js Ökosystem zu lernen, beizutragen und z
diff --git a/src/content/pages/de/resources/middleware/body-parser.mdx b/src/content/pages/de/resources/middleware/body-parser.mdx
index 4a61e2ce46..06b1f969af 100644
--- a/src/content/pages/de/resources/middleware/body-parser.mdx
+++ b/src/content/pages/de/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Node.js Körper parsen Middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Andere Körper-Parser, die Sie interessieren können:
## Installation
-```sh
-$ npm install body-parser
-```
+
## API
@@ -111,8 +110,8 @@ auf `'100kb`.
##### reviver
Die Option `reviver` wird als zweites
-Argument direkt an `JSON.parse` übergeben. Weitere Informationen zu diesem Argument
-[in der MDN-Dokumentation über JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+Argument direkt an `JSON.parse` übergeben. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strikt
diff --git a/src/content/pages/de/resources/middleware/compression.mdx b/src/content/pages/de/resources/middleware/compression.mdx
index 4666486664..d09b9b39f4 100644
--- a/src/content/pages/de/resources/middleware/compression.mdx
+++ b/src/content/pages/de/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js Komprimierungs-Middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/cookie-parser.mdx b/src/content/pages/de/resources/middleware/cookie-parser.mdx
index 15582d57c9..8a9870a745 100644
--- a/src/content/pages/de/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/de/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: HTTP-Anfrage-Cookies analysieren
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/cookie-session.mdx b/src/content/pages/de/resources/middleware/cookie-session.mdx
index 23b81dd354..4ff29b8ceb 100644
--- a/src/content/pages/de/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/de/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie Session Middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/cors.mdx b/src/content/pages/de/resources/middleware/cors.mdx
index d380892147..aebc423933 100644
--- a/src/content/pages/de/resources/middleware/cors.mdx
+++ b/src/content/pages/de/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS ist eine [Node.js](https://nodejs.org/en/) Middleware für [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect), die [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) Antwort-Kopfzeilen setzt. Diese Header geben Browsern an, welche Herkunft Antworten von Ihrem Server lesen kann.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. Diese Header geben Browsern an, welche Herkunft Antworten von Ihrem Server lesen kann.
@@ -39,9 +40,7 @@ Dies ist ein [Node.js](https://nodejs.org/en/) Modul über die
[npm Registry](https://www.npmjs.com/). Installation erfolgt mit dem
[`npm install` Befehl](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Auslastung
diff --git a/src/content/pages/de/resources/middleware/errorhandler.mdx b/src/content/pages/de/resources/middleware/errorhandler.mdx
index 1ee4fc2844..5acb62cd8a 100644
--- a/src/content/pages/de/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/de/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Middleware für Entwicklungsfehler
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/index.mdx b/src/content/pages/de/resources/middleware/index.mdx
new file mode 100644
index 0000000000..76fc2879dc
--- /dev/null
+++ b/src/content/pages/de/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Beschreibung |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ Diese Informationen beziehen sich auf Sites, Produkte oder Module, die nicht vom Expressjs Team
+ betreut werden. Die Auflistung hier stellt keine Billigung oder Empfehlung des Projektteams von
+ Expressjs dar.
+
+
+| Middleware module | Beschreibung |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/de/resources/middleware/method-override.mdx b/src/content/pages/de/resources/middleware/method-override.mdx
index 63e5e9c1ec..6ef2673549 100644
--- a/src/content/pages/de/resources/middleware/method-override.mdx
+++ b/src/content/pages/de/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: HTTP-Verben überschreiben
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/morgan.mdx b/src/content/pages/de/resources/middleware/morgan.mdx
index 0e7fb1bf14..3d9e9328d3 100644
--- a/src/content/pages/de/resources/middleware/morgan.mdx
+++ b/src/content/pages/de/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: HTTP Request Logger Middleware für Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ Dies ist ein [Node.js](https://nodejs.org/en/) Modul über die
[npm Registry](https://www.npmjs.com/). Installation erfolgt mit dem
[`npm install` Befehl](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ Wenn kein Format angegeben ist, dann ist der Standard `web`.
Die HTTP-Version der Anfrage.
-##### :method
+#####
Die HTTP-Methode der Anfrage.
-##### :pid
+#####
Die Prozess-ID des Node.js Prozesses zur Bearbeitung der Anfrage.
-##### :referrer
+#####
Der Referrer-Header der Anfrage. Dies wird den Standard-falsch geschriebenen Referer-Header verwenden, falls vorhanden, andernfalls Referrer.
@@ -239,7 +238,7 @@ Die Zeit zwischen der Anfrage, die in `morgan` eintrifft, und der Antwort-
Das `digits`-Argument ist eine Zahl, die die Anzahl der Ziffern angibt, die
enthalten ist für die Zahl, Standardwert ist `3`, was die Genauigkeit der Mikrosekunden angibt.
-##### :status
+#####
Der Statuscode der Antwort.
@@ -255,7 +254,7 @@ beendet ist, wird in Millisekunden auf die Verbindung geschrieben.
Das `digits`-Argument ist eine Zahl, die die Anzahl der Ziffern angibt, die
enthalten ist für die Zahl, Standardwert ist `3`, was die Genauigkeit der Mikrosekunden angibt.
-##### :url
+#####
Die URL der Anfrage. Dies wird `req.originalUrl` verwenden, wenn vorhanden, andernfalls `req.url`.
diff --git a/src/content/pages/de/resources/middleware/multer.mdx b/src/content/pages/de/resources/middleware/multer.mdx
index 4eb44e7889..60b6d4b985 100644
--- a/src/content/pages/de/resources/middleware/multer.mdx
+++ b/src/content/pages/de/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware für den Umgang mit Multipart/Formulardaten
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ Diese README ist auch in anderen Sprachen verfügbar:
## Installation
-```sh
-$ npm install multer
-```
+
## Auslastung
@@ -284,15 +283,16 @@ Ein Objekt, das die Größengrenzen der folgenden optionalen Eigenschaften angib
Die folgenden Ganzzahlwerte sind verfügbar:
-| Schlüssel | Beschreibung | Standard |
-| --------------- | ---------------------------------------------------------------------------------------------------- | ------------- |
-| "fieldNameSize" | Max. Feldnamensgröße | 100 Bytes |
-| "fieldGröße" | Maximale Feldwertgröße (in Bytes) | 1MB |
-| `Felder` | Maximale Anzahl von Nicht-Dateifeldern | Unendlichkeit |
-| Dateigröße | Für mehrteilige Formulare ist die maximale Dateigröße (in Bytes) | Unendlichkeit |
-| `Dateien` | Für mehrteilige Formulare ist die maximale Anzahl von Dateifeldern | Unendlichkeit |
-| "Teile" | Für mehrteilige Formulare ist die maximale Anzahl von Teilen (Felder + Dateien) | Unendlichkeit |
-| "headerPairs" | Bei mehrteiligen Formularen ist die maximale Anzahl der Kopfzeilen-Schlüssel=>Werte-Paare zum Parsen | 2000 |
+| Schlüssel | Beschreibung | Standard |
+| ------------------- | ---------------------------------------------------------------------------------------------------- | ------------- |
+| "fieldNameSize" | Max. Feldnamensgröße | 100 Bytes |
+| "fieldGröße" | Maximale Feldwertgröße (in Bytes) | 1MB |
+| `Felder` | Maximale Anzahl von Nicht-Dateifeldern | Unendlichkeit |
+| Dateigröße | Für mehrteilige Formulare ist die maximale Dateigröße (in Bytes) | Unendlichkeit |
+| `Dateien` | Für mehrteilige Formulare ist die maximale Anzahl von Dateifeldern | Unendlichkeit |
+| "Teile" | Für mehrteilige Formulare ist die maximale Anzahl von Teilen (Felder + Dateien) | Unendlichkeit |
+| "headerPairs" | Bei mehrteiligen Formularen ist die maximale Anzahl der Kopfzeilen-Schlüssel=>Werte-Paare zum Parsen | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Unendlichkeit |
Die Angabe der Grenzwerte kann dazu beitragen, Ihre Website vor Denial of Service (DoS) Attacken zu schützen.
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Fehlerbehandlung
Wenn ein Fehler auftritt, wird Multer den Fehler an Express übertragen. Du kannst
diff --git a/src/content/pages/de/resources/middleware/response-time.mdx b/src/content/pages/de/resources/middleware/response-time.mdx
index b77eb25eb4..5e2bc101cf 100644
--- a/src/content/pages/de/resources/middleware/response-time.mdx
+++ b/src/content/pages/de/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Antwortzeit für Node.js Server
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/serve-favicon.mdx b/src/content/pages/de/resources/middleware/serve-favicon.mdx
index 7d863af6bf..0de7298d28 100644
--- a/src/content/pages/de/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/de/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon, der Middleware mit Caching bedient
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/serve-index.mdx b/src/content/pages/de/resources/middleware/serve-index.mdx
index 5aee87b062..f8c2decaa7 100644
--- a/src/content/pages/de/resources/middleware/serve-index.mdx
+++ b/src/content/pages/de/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Serve-Verzeichnislisten
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/serve-static.mdx b/src/content/pages/de/resources/middleware/serve-static.mdx
index 13b493966e..deca19dffa 100644
--- a/src/content/pages/de/resources/middleware/serve-static.mdx
+++ b/src/content/pages/de/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Statische Dateien Servieren
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/resources/middleware/session.mdx b/src/content/pages/de/resources/middleware/session.mdx
index 0b609cc959..dda757b5b7 100644
--- a/src/content/pages/de/resources/middleware/session.mdx
+++ b/src/content/pages/de/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Einfache Sitzungs-Middleware für Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Installation
@@ -18,9 +19,7 @@ Dies ist ein [Node.js](https://nodejs.org/en/) Modul über die
[npm Registry](https://www.npmjs.com/). Installation erfolgt mit dem
[`npm install` Befehl](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -124,9 +123,8 @@ Gibt den `boolean` Wert für das [`Partitioned` `Set-Cookie`](https://github.com
Attribut an. Wenn Wahrheit, ist das `Partitioned` Attribut gesetzt, andernfalls nicht.
Standardmäßig ist das Attribut `Partitioned` nicht gesetzt.
-**Notiz** Dies ist ein Attribut, das noch nicht vollständig standardisiert wurde und in Zukunft
-ändern kann. Dies bedeutet auch, dass viele Kunden dieses Attribut ignorieren können, bis sie es
-verstehen.
+**Notiz** Dies ist ein Attribut, das noch nicht vollständig standardisiert wurde und in Zukunft in
+ändern kann. Dies bedeutet auch, dass viele Clients dieses Attribut ignorieren können, bis sie es verstehen.
Weitere Informationen finden Sie in [dem Vorschlag](https://github.com/privacycg/CHIPS).
@@ -164,7 +162,7 @@ Standardmäßig ist dies `false`.
Weitere Informationen über die verschiedenen Durchsetzungsstufen finden Sie unter
[die Spezifikation][rfc-6265bis-03-4.1.2.7].
-**Notiz** Dies ist ein Attribut, das noch nicht vollständig standardisiert wurde und in Zukunft in
+**Notiz** Dies ist ein Attribut, das noch nicht vollständig standardisiert wurde und in Zukunft
ändern kann. Dies bedeutet auch, dass viele Clients dieses Attribut ignorieren können, bis sie es verstehen.
**Hinweis** Es gibt ein [Entwurfsspekta](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
@@ -285,8 +283,7 @@ Erzwingt die Sitzung, wieder im Session-Store zu speichern, selbst wenn die Sitz
während der Anfrage nie geändert wurde. Abhängig von Ihrem Shop könnte dies
notwendig sein aber es kann auch Rennbedingungen schaffen, bei denen ein Client zwei
parallele Anfragen an Ihren Server stellt und Änderungen an der Sitzung in einer
-Anfrage können überschrieben werden, wenn die andere Anfrage beendet ist. auch wenn es keine
-Änderungen vorgenommen hat (dieses Verhalten hängt auch davon ab, welcher Shop Sie verwenden).
+Anfrage können überschrieben werden, wenn die andere Anfrage beendet ist.
Der Standardwert ist `true`, aber die Verwendung des Standardwertes wurde veraltet,
als Standardwert wird sich in Zukunft ändern. Bitte prüfen Sie diese Einstellung
diff --git a/src/content/pages/de/resources/middleware/timeout.mdx b/src/content/pages/de/resources/middleware/timeout.mdx
index 62d5715920..4ba719a07b 100644
--- a/src/content/pages/de/resources/middleware/timeout.mdx
+++ b/src/content/pages/de/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Timeout Middleware für Connect/Express anfordern
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Timeout einer Anfrage im Connect/Express Anwendungs-Framework.
@@ -20,9 +21,7 @@ Dies ist ein [Node.js](https://nodejs.org/en/) Modul über die
[npm Registry](https://www.npmjs.com/). Installation erfolgt mit dem
[`npm install` Befehl](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/de/resources/middleware/vhost.mdx b/src/content/pages/de/resources/middleware/vhost.mdx
index 99c2d46310..8c4e4e2c51 100644
--- a/src/content/pages/de/resources/middleware/vhost.mdx
+++ b/src/content/pages/de/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Virtuelles Domänen-Hosting
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/de/support.md b/src/content/pages/de/support.md
index 84fb775a98..64248f4034 100644
--- a/src/content/pages/de/support.md
+++ b/src/content/pages/de/support.md
@@ -7,14 +7,14 @@ Nur die neueste Version einer der wichtigsten Release-Zeilen wird unterstützt.
Versionen, die EOL (Ende des Lebens) _may_ sind, erhalten Updates für kritische Sicherheitslücken, aber das Express-Team bietet keine Garantie und plant keine Korrekturen für festgestellte Probleme zu beheben oder zu veröffentlichen.
-| Hauptversion | Minimale Node.js Version | Support-Startdatum | Support-Enddatum |
-| ------------------- | ------------------------ | ------------------ | ---------------- |
-| [**v5.x**](/5x/api) | 18 | September 2024 | **Laufend** |
-| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **Laufend** |
-| [**v3.x**](/3x/api) | 0.8.0 | Oktober 2012 | Juli 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | März 2011 | Juli 2012 |
-| **v1.x** | 0.2.0 | Dezember 2010 | März 2011 |
-| **v0.14.x** | 0.1.98 | Dezember 2010 | Dezember 2010 |
+| Hauptversion | Minimale Node.js Version | Support-Startdatum | Support-Enddatum |
+| -------------------------------------------------------------- | ------------------------ | ------------------ | ---------------- |
+| [**v5.x**](/5x/api) | 18 | September 2024 | **Laufend** |
+| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **Laufend** |
+| [**v3.x**](/3x/api) | 0.8.0 | Oktober 2012 | Juli 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | März 2011 | Juli 2012 |
+| **v1.x** | 0.2.0 | Dezember 2010 | März 2011 |
+| **v0.14.x** | 0.1.98 | Dezember 2010 | Dezember 2010 |
## Kommerzielle Support-Optionen
diff --git a/src/content/pages/es/advanced/best-practice-performance.md b/src/content/pages/es/advanced/best-practice-performance.md
index 9307f646ce..9483849121 100644
--- a/src/content/pages/es/advanced/best-practice-performance.md
+++ b/src/content/pages/es/advanced/best-practice-performance.md
@@ -10,7 +10,7 @@ Este tema entra claramente en el mundo de los "devops", que abarca tanto el desa
- Cosas que hacer en tu código (la parte del desarrollador):
- [Usar compresión gzip](#use-gzip-compression)
- [No usar funciones sincrónicas](#dont-use-synchronous-functions)
- - [Registrar correctamente](#do-logging-correctly)
+ - [Registrar correctamente] (#do-logging-correctly)
- [Manejar excepciones correctamente](#handle-exceptions-properly)
- Cosas que hacer en tu entorno / configuración (parte de la opción):
- [Establecer NODE_ENV a "producción"](#set-node_env-to-production)
@@ -26,14 +26,14 @@ Aquí hay algunas cosas que puedes hacer en tu código para mejorar el rendimien
- [Usar compresión gzip](#use-gzip-compression)
- [No usar funciones sincrónicas](#dont-use-synchronous-functions)
-- [Registrar correctamente](#do-logging-correctly)
+- [Registrar correctamente] (#do-logging-correctly)
- [Manejar excepciones correctamente](#handle-exceptions-properly)
### Usar compresión gzip
La compresión Gzip puede disminuir en gran medida el tamaño del cuerpo de respuesta y por lo tanto aumentar la velocidad de una aplicación web. Utilice el Middleware [compression](https://www.npmjs.com/package/compression) para compresión gzip en su aplicación Express. Por ejemplo:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-Para un sitio web de alto tráfico en producción, la mejor manera de poner compresión en su lugar es implementarla en un nivel proxy inverso (ver [Usar un proxy inverso](#use-a-reverse-proxy)). En ese caso, no necesita usar middleware de compresión. Para más detalles sobre habilitar compresión gzip en Nginx, vea [Módulo ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) en la documentación de Nginx.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### No utilizar funciones sincrónicas
+### Don't use synchronous functions
-Las funciones y métodos sincrónicos emiten el proceso de ejecución hasta que regresen. Una sola llamada a una función sincrónica puede regresar en unos pocos microsegundos o milisegundos, Sin embargo, en sitios web de alto tráfico, estas llamadas añaden y reducen el rendimiento de la aplicación. Evite su uso en la producción.
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Aunque Node y muchos módulos proporcionan versiones sincrónicas y asíncronas de sus funciones, siempre utiliza la versión asíncrona en producción. La única vez que una función sincrónica puede ser justificada es al inicio inicial.
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-Puedes usar la bandera de línea de comandos `--trace-sync-io` para imprimir una advertencia y un stack trace cada vez que tu aplicación usa una API sincrónica. Por supuesto, no querrías usar esto en la producción, sino más bien asegurar que tu código esté listo para la producción. Vea la [documentación de opciones de línea de comandos de nodo](https://nodejs.org/api/cli.html#trace-sync-io) para más información.
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Hacer el registro correctamente
+### Do logging correctly
-En general, hay dos razones para registrarse desde tu aplicación: para depurar y para registrar la actividad de la aplicación (esencialmente, todo lo demás). Usar `console.log()` o `console.error()` para imprimir mensajes de registro en la terminal es práctica común en desarrollo. Pero [estas funciones son sincrónicas](https://nodejs.org/api/console.html#console) cuando el destino es un terminal o un archivo, por lo que no son aptos para la producción, a menos que usted pipe la salida a otro programa.
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### Para depuración
+#### For debugging
-Si está registrando para fines de depuración, entonces en lugar de usar `console.log()`, utilice un módulo especial de depuración como [debug](https://www.npmjs.com/package/debug). Este módulo le permite usar la variable de entorno DEBUG para controlar qué mensajes de depuración se envían a `console.error()`, si los hay. Para mantener tu aplicación puramente asincrónica, todavía quieres pipe `console.error()` a otro programa. Pero entonces, no vas a depurar en la producción, ¿verdad?
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### Para actividad de la aplicación
+#### For app activity
-Si estás registrando actividad de la aplicación (por ejemplo, rastreando tráfico o llamadas de API), en lugar de usar `console. og()`, utiliza una biblioteca de registro como [Pino](https://www.npmjs.com/package/pino), que es la opción más rápida y eficiente disponible.
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### Manejar excepciones correctamente
+### Handle exceptions properly
-Las aplicaciones del nodo fallan cuando se encuentran con una excepción no capturada. No manejar excepciones y tomar las acciones apropiadas hará que su aplicación Express se bloquee y se desconecte. Si sigues los consejos de [Asegúrate de que tu aplicación se reinicie automáticamente](#ensure-your-app-automatically-restarts) a continuación, tu aplicación se recuperará de un cuelgue. Afortunadamente, las aplicaciones Express típicamente tienen un corto tiempo de inicio. Sin embargo, usted quiere evitar el bloqueo en primer lugar, y para hacerlo, necesita manejar las excepciones adecuadamente.
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-Para asegurar que maneja todas las excepciones, utilice las siguientes técnicas:
+To ensure you handle all exceptions, use the following techniques:
-- [Usar try-catch](#use-try-catch)
-- [Usar promesas](#use-promises)
+- [Use try-catch](#use-try-catch)
+- [Use promises](#use-promises)
-Antes de sumergirte en estos temas, deberías tener una comprensión básica del manejo de errores de Node/Express: usando callbacks de primer error, y propagando errores en middleware. Node utiliza una convención de "error de primer callback" para devolver errores de funciones asíncronas, donde el primer parámetro de la función callback es el objeto de error, seguido de los datos de resultado en los parámetros posteriores. Para indicar ningún error, pase nulo como el primer parámetro. La función callback debe seguir la convención de devolución de llamada de primer error para manejar el error de forma significativa. Y en Express, la mejor práctica es usar la función next() para propagar errores a través de la cadena middleware.
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-Para más información sobre los fundamentos del manejo de errores, vea:
+For more on the fundamentals of error handling, see:
-- [Manejo de Error en Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Usar try-catch
+#### Use try-catch
-Try-catch es una construcción de lenguaje JavaScript que se puede utilizar para capturar excepciones en código sincrónico. Use try-catch, por ejemplo, para manejar errores de análisis JSON como se muestra a continuación.
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-He aquí un ejemplo del uso de try-catch para manejar una posible excepción de bloqueo de procesos.
-Esta función middleware acepta un parámetro de campo de consulta llamado "params" que es un objeto JSON.
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-Sin embargo, try-catch funciona sólo para código sincrónico. Debido a que la plataforma de Node es principalmente asíncrona (especialmente en un entorno de producción), la captura de pruebas no capturará muchas excepciones.
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Utilizar promesas
+#### Use promises
-Cuando se arroja un error en una función `async` o se espera una promesa rechazada dentro de una función `async`, esos errores se pasarán al gestor de errores como si llamara a `next(err)`
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-También, puede utilizar funciones asíncronas para su middleware, y el router manejará errores si la promesa falla, por ejemplo:
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-La mejor práctica es manejar los errores lo más cerca posible del sitio. Así que mientras esto se maneja ahora en el router, es mejor capturar el error en el middleware y manejarlo sin depender de middleware separado para manejar errores.
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### Qué no hacer
+#### What not to do
-Una cosa que debes _no_ hacer es escuchar el evento `uncaughtException`, emitido cuando una excepción emite todo el camino de regreso al bucle del evento. Añadir un detector de eventos para `uncaughtException` cambiará el comportamiento predeterminado del proceso que se encuentra con una excepción; el proceso continuará funcionando a pesar de la excepción. Esto puede sonar como una buena manera de evitar que tu aplicación falle, pero seguir ejecutando la aplicación después de una excepción no capturada es una práctica peligrosa y no se recomienda, porque el estado del proceso se vuelve poco fiable e impredecible.
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-Además, usar `uncaughtException` es oficialmente reconocido como [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Así que escuchar `uncaughtException` es sólo una mala idea. Por eso recomendamos cosas como múltiples procesos y supervisores: fallar y reiniciar es a menudo la manera más confiable de recuperarse de un error.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-Tampoco recomendamos usar [domains](https://nodejs.org/api/domain.html). Generalmente no resuelve el problema y es un módulo obsoleto.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## Cosas que hacer en tu entorno / configuración
+## Things to do in your environment / setup
-Aquí hay algunas cosas que puedes hacer en el entorno de tu sistema para mejorar el rendimiento de tu aplicación:
+Here are some things you can do in your system environment to improve your app's performance:
- [Establecer NODE_ENV a "producción"](#set-node_env-to-production)
- [Asegúrate de que tu aplicación se reinicie automáticamente](#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Aquí hay algunas cosas que puedes hacer en el entorno de tu sistema para mejora
- [Usa un balanceador de carga](#use-a-load-balancer)
- [Usa un proxy inverso](#use-a-reverse-proxy)
-### Establecer NODE_ENV a "producción"
+### Set NODE_ENV to "production"
-La variable de entorno NODE_ENV especifica el entorno en el que se está ejecutando una aplicación (normalmente, desarrollo o producción). Una de las cosas más sencillas que puedes hacer para mejorar el rendimiento es establecer NODE_ENV en `production`.
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-Establecer NODE_ENV a "producción" hace Expresión:
+Setting NODE_ENV to "production" makes Express:
-- Plantillas de vista de caché.
-- Caché de archivos CSS generados a partir de extensiones CSS.
-- Generar mensajes de error menos detallados.
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-¡[Las pruebas indican](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) que hacer esto puede mejorar el rendimiento de la aplicación en un factor de tres!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-Si necesita escribir código específico del entorno, puede comprobar el valor de NODE_ENV con `process.env.NODE_ENV`. Tenga en cuenta que comprobar el valor de cualquier variable de entorno incurre en una penalidad de rendimiento, y por lo tanto debe hacerse de forma esparcida.
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-En desarrollo, normalmente estableces variables de entorno en tu shell interactivo, por ejemplo usando `export` o tu archivo `.bash_profile`. Pero en general, no debería hacer esto en un servidor de producción; en cambio, utilice el sistema de inicio de su sistema operativo (systemd). La siguiente sección proporciona más detalles sobre el uso de tu sistema de inicio en general pero configurar `NODE_ENV` es tan importante para el rendimiento (y fácil de hacer), que está resaltado aquí.
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-Con el sistema, utilice la directiva 'Entorno de Entorno' en su archivo de unidad. Por ejemplo:
+With systemd, use the `Environment` directive in your unit file. Por ejemplo:
```sh
Environment=NODE_ENV=production
```
-Para obtener más información, consulte [Usar variables de entorno en unidades del sistema](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### Asegúrate de que tu aplicación se reinicie automáticamente
+### Ensure your app automatically restarts
-En la producción, usted no quiere que su aplicación esté fuera de línea, nunca. Esto significa que necesita asegurarse de que se reinicie si la aplicación se bloquea y si el servidor mismo falla. Aunque usted espera que ninguno de estos eventos ocurra, realísticamente usted debe dar cuenta de ambos eventos por:
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- Usar un gestor de procesos para reiniciar la aplicación (y Node) cuando se bloquea.
-- Usando el sistema de inicio proporcionado por su sistema operativo para reiniciar el gestor de procesos cuando el sistema operativo se bloquea. También es posible usar el sistema init sin un gestor de procesos.
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-Las aplicaciones de nodos se estrellan si se encuentran con una excepción no capturada. Lo más importante que tienes que hacer es asegurar que tu aplicación está bien probada y gestiona todas las excepciones (ver [excepciones de manejo correctamente](#handle-exceptions-properly) para más detalles). Pero como seguro de fallos, ponga en marcha un mecanismo para asegurar que si tu aplicación se bloquea y cuando se bloquee, se reiniciará automáticamente.
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### Usar un gestor de procesos
+#### Use a process manager
-En desarrollo, ha iniciado su aplicación simplemente desde la línea de comandos con `node server.js` o algo similar. Pero hacer esto en la producción es una receta para el desastre. Si la aplicación falla, estará desconectada hasta que la reinicie. Para asegurar que su aplicación se reinicie si se bloquea, utilice un gestor de procesos. Un gestor de procesos es un "contenedor" para aplicaciones que facilita el despliegue, proporciona alta disponibilidad y le permite gestionar la aplicación en tiempo de ejecución.
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-Además de reiniciar su aplicación cuando falla, un gestor de procesos puede habilitarlo:
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- Obtener información sobre el rendimiento y el consumo de recursos en tiempo de ejecución.
-- Modificar ajustes dinámicamente para mejorar el rendimiento.
-- Clasificación de controles (pm2).
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-Históricamente, era popular usar un gestor de procesos Node.js como [PM2](https://github.com/Unitech/pm2). Vea su documentación si desea hacer esto. Sin embargo, recomendamos usar su sistema de inicio para la gestión de procesos.
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### Usar un sistema de inicio
+#### Use an init system
-La siguiente capa de fiabilidad es asegurar que la aplicación se reinicie cuando el servidor se reinicie. Los sistemas pueden seguir bajando por diversas razones. Para asegurarse de que su aplicación se reinicie si el servidor se bloquea, utilice el sistema init incorporado en su sistema operativo. El sistema principal de inicio en uso hoy es [systemd](https://wiki.debian.org/systemd).
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Hay dos formas de usar sistemas de inicio con su aplicación Express:
+There are two ways to use init systems with your Express app:
-- Ejecute su aplicación en un gestor de procesos, e instale el gestor de procesos como un servicio con el sistema init. El gestor de procesos reiniciará la aplicación cuando la aplicación se bloquee, y el sistema de inicio reiniciará el gestor de procesos cuando el sistema operativo se reinicie. Este es el enfoque recomendado.
-- Ejecute su aplicación (y Node) directamente con el sistema init. Esto es algo más simple, pero no obtiene las ventajas adicionales de usar un gestor de procesos.
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-Systemd es un gestor de servicios y sistemas Linux. La mayoría de las distribuciones de Linux más importantes han adoptado el sistema de inicio como su sistema predeterminado.
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-Un archivo de configuración de servicio systemd se llama _unit file_, con un nombre de archivo que termina en `.service`. Aquí hay un archivo de unidad de ejemplo para administrar directamente una aplicación de Node. Reemplaza los valores encerrados en `` para tu sistema y aplicación:
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-Para más información sobre el sistema, vea la [referencia del sistema (página de manu)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Ejecutar tu aplicación en un clúster
+### Run your app in a cluster
-En un sistema multinúcleo, puede aumentar el rendimiento de una aplicación Node muchas veces lanzando un clúster de procesos. Un clúster ejecuta múltiples instancias de la aplicación, idealmente una instancia en cada núcleo de CPU, distribuyendo así la carga y las tareas entre las instancias.
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
-
+
-IMPORTANTE: Dado que las instancias de la aplicación se ejecutan como procesos separados, no comparten el mismo espacio de memoria. Es decir, los objetos son locales a cada instancia de la aplicación. Por lo tanto, no puede mantener el estado en el código de la aplicación. Sin embargo, puede utilizar un datastore en memoria como [Redis](http://redis.io/) para almacenar datos y estado relacionados con la sesión. Esta advertencia se aplica esencialmente a todas las formas de escalado horizontal, ya sea en racimo con múltiples procesos o múltiples servidores físicos.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-En las aplicaciones agrupadas, los procesos del worker pueden fallar individualmente sin afectar al resto de los procesos. Aparte de las ventajas de rendimiento, el aislamiento de fallos es otra razón para ejecutar un cluster de procesos de aplicaciones. Cada vez que un proceso worker se bloquea, siempre asegúrese de registrar el evento y generar un nuevo proceso usando cluster.fork().
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### Usando el módulo de cluster del nodo
+#### Using Node's cluster module
-Clustering es posible con el [módulo de cluster]de Node (https://nodejs.org/api/cluster.html). Esto permite que un proceso maestro genere procesos de trabajador y distribuya conexiones entrantes entre los trabajadores.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### Usando PM2
+#### Using PM2
-Si implementa su aplicación con PM2, puede aprovechar el clustering _without_ modificando su código de aplicación. Deberías asegurarte de que tu [aplicación está sin estado](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) primero, lo que significa que no hay datos locales almacenados en el proceso (como sesiones, conexiones websocket y similares).
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-Cuando ejecutas una aplicación con PM2, puedes habilitar el **modo clúster** para ejecutarla en un clúster con varias instancias de tu elección, como el número de CPUs disponibles en la máquina. Puede cambiar manualmente el número de procesos en el clúster usando la herramienta de línea de comandos `pm2` sin detener la aplicación.
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-Para activar el modo cluster, inicia tu aplicación así:
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-Esto también se puede configurar dentro de un archivo de proceso PM2 (`ecosystem.config. s` o similar) estableciendo `exec_mode` a `cluster` y `instancias` al número de workers a comenzar.
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-Una vez ejecutada, la aplicación puede escalarse así:
+Once running, the application can be scaled like so:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-Para más información sobre el clustering con PM2, vea [Modo Cluster](https://pm2.keymetrics.io/docs/usage/cluster-mode/) en la documentación de PM2.
+For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### Resultados de la solicitud de caché
+### Cache request results
-Otra estrategia para mejorar el rendimiento en la producción es almacenar en caché el resultado de las solicitudes, para que tu aplicación no repita la operación para servir la misma petición repetidamente.
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Usa un servidor de caché como [Varnish](https://www.varnish-cache.org/) o [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (ver también [Caching Nginx](https://serversforhackers.com/nginx-caching/)) para mejorar enormemente la velocidad y el rendimiento de tu aplicación.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Usar un balanceador de carga
+### Use a load balancer
-No importa cuán optimizada sea una aplicación, una sola instancia puede manejar sólo una cantidad limitada de carga y tráfico. Una forma de escalar una aplicación es ejecutar múltiples instancias de ella y distribuir el tráfico a través de un equilibrador de carga. Configurar un balanceador de carga puede mejorar el rendimiento y la velocidad de tu aplicación, y permitirla escalar más de lo posible con una sola instancia.
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-Un balanceador de carga es generalmente un proxy inverso que orchestriza tráfico hacia y desde múltiples instancias y servidores de la aplicación. Puedes configurar fácilmente un equilibrador de carga para tu aplicación usando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-Con el saldo de carga, puede que tenga que asegurarse de que las peticiones que están asociadas con un ID de sesión particular se conectan al proceso que las originó. Esto se conoce como _session affinity_, o _sticky sessions_, y puede ser abordado por la sugerencia anterior de utilizar un almacén de datos como Redis para datos de sesión (dependiendo de su aplicación). Para una discusión, vea [Usando múltiples nodos](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### Usar un proxy inverso
+### Use a reverse proxy
-Un proxy inverso se sienta frente a una aplicación web y realiza operaciones de soporte en las peticiones, además de dirigir peticiones a la aplicación. Puede manejar páginas de errores, compresión, caché, servir archivos y equilibrar la carga entre otras cosas.
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-La entrega de tareas que no requieren conocimiento del estado de la aplicación a un proxy inverso libera Express para realizar tareas especializadas de la aplicación. Por esta razón, se recomienda ejecutar Express detrás de un proxy inverso como [Nginx](https://www.nginx.org/) o [HAProxy](https://www.haproxy.org/) en producción.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/es/advanced/best-practice-security.mdx b/src/content/pages/es/advanced/best-practice-security.mdx
index 9549b7e477..1859d97445 100644
--- a/src/content/pages/es/advanced/best-practice-security.mdx
+++ b/src/content/pages/es/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Descubra las mejores prácticas de seguridad cruciales para aplicac
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
El término _"producción"_ se refiere a la etapa del ciclo de vida del software cuando una aplicación o API está generalmente disponible para sus usuarios finales o consumidores. En contraste, en la etapa _"desarrollo"_ todavía estás escribiendo activamente y probando código, y la aplicación no está abierta al acceso externo. Los entornos del sistema correspondientes se conocen como entornos _production_ y _development_, respectivamente.
@@ -18,21 +19,19 @@ Políticas y procedimientos.
Las mejores prácticas de seguridad para aplicaciones Express en producción incluyen:
-- [Prácticas Mejores de Producción: Seguridad](#production-best-practices-security)
- - [Overview](#overview)
- - [No usar versiones obsoletas o vulnerables de Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Usar TLS](#use-tls)
- - [No confiar en la entrada del usuario](#do-not-trust-user-input)
- - [Prevenir redirecciones abiertas](#prevent-open-redirects)
- - [Casco de Uso](#use-helmet)
- - [Reducir la huella dactilar](#reduce-fingerprinting)
- - [Usar cookies de forma segura](#use-cookies-securely)
- - [No usar el nombre de cookie de sesión predeterminado](#dont-use-the-default-session-cookie-name)
- - [Establecer opciones de seguridad de cookies](#set-cookie-security-options)
- - [Prevenir ataques de fuerza bruta contra autorización](#prevent-brute-force-attacks-against-authorization)
- - [Asegúrate de que tus dependencias son seguras](#ensure-your-dependencies-are-secure)
- - [Evitar otras vulnerabilidades conocidas](#avoid-other-known-vulnerabilities)
- - [Examen adicional](#additional-considerations)
+- [No usar versiones obsoletas o vulnerables de Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Usar TLS](#use-tls)
+- [No confiar en la entrada del usuario](#do-not-trust-user-input)
+ - [Prevenir redirecciones abiertas](#prevent-open-redirects)
+- [Casco de Uso](#use-helmet)
+- [Reducir la huella dactilar](#reduce-fingerprinting)
+- [Usar cookies de forma segura](#use-cookies-securely)
+ - [No usar el nombre de cookie de sesión predeterminado](#dont-use-the-default-session-cookie-name)
+ - [Establecer opciones de seguridad de cookies](#set-cookie-security-options)
+- [Prevenir ataques de fuerza bruta contra autorización](#prevent-brute-force-attacks-against-authorization)
+- [Asegúrate de que tus dependencias son seguras](#ensure-your-dependencies-are-secure)
+ - [Evitar otras vulnerabilidades conocidas](#avoid-other-known-vulnerabilities)
+- [Examen adicional](#additional-considerations)
## No utilizar versiones obsoletas o vulnerables de Express
@@ -44,7 +43,7 @@ También asegúrese de que no está usando ninguna de las versiones Express vuln
Si tu aplicación trata o transmite datos confidenciales, usa [Seguridad de la capa de transporte](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) para asegurar la conexión y los datos. Esta tecnología encripta los datos antes de que sean enviados desde el cliente al servidor, evitando así algunos hacks comunes (y fáciles). Aunque las solicitudes Ajax y POST pueden no ser visiblemente obvias y parecen "ocultas" en los navegadores, su tráfico de red es vulnerable a [sniffing de paquetes](https://en.wikipedia.org/wiki/Packet_analyzer) y [ataques man-in-the-midds](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-Puede estar familiarizado con el cifrado de la capa de conector seguro (SSL). [TLS es simplemente la siguiente progresión de SSL](). En otras palabras, si estaba usando SSL antes, considere actualizar a TLS. En general, recomendamos Nginx para manejar TLS. Para una buena referencia para configurar TLS en Nginx (y otros servidores), vea [Configuraciones Recomendadas del servidor (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+Puede estar familiarizado con el cifrado de la capa de conector seguro (SSL). En general, recomendamos Nginx para manejar TLS. En otras palabras, si estaba usando SSL antes, considere actualizar a TLS. En otras palabras, si estaba usando SSL antes, considere actualizar a TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Además, una útil herramienta para obtener un certificado TLS gratis es [Vamos a cifrar](https://letsencrypt.org/about/), un gratuito, automatizado, y autoridad certificadora abierta (CA) proporcionada por el [Grupo de Investigación sobre Seguridad de Internet (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Cada cabecera puede ser configurada o deshabilitada. Para leer más al respecto,
Instalar casco como cualquier otro módulo:
-```bash
-$ npm install helmet
-```
+
Luego para usarlo en tu código:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,10 +111,20 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Reduce la toma de huellas digitales
Puede ayudar a proporcionar una capa extra de seguridad para reducir la capacidad de los atacantes para determinar
-el software que utiliza un servidor. conocido como "huella dactilar". Aunque no es un problema de seguridad en sí mismo,
+el software que utiliza un servidor. Aunque no es un problema de seguridad en sí mismo,
reducir la capacidad de huellas dactilares de una aplicación mejora su posición general de seguridad.
El software del servidor puede ser tomado con huellas dactilares en cómo responde a peticiones específicas, por ejemplo en
las cabeceras de respuesta HTTP.
@@ -177,7 +184,7 @@ Usar el nombre de la cookie de sesión por defecto puede abrir su aplicación pa
To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Configurar opciones de seguridad de cookies
Establecer las siguientes opciones de cookie para mejorar la seguridad:
@@ -200,7 +219,7 @@ Establecer las siguientes opciones de cookie para mejorar la seguridad:
Aquí hay un ejemplo usando un middleware [cookie-session](https://www.npmjs.com/package/cookie-session):
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Evitar ataques de fuerza bruta contra autorización
Asegúrese de que los puntos finales de inicio de sesión están protegidos para hacer que los datos privados sean más seguros.
@@ -259,7 +300,7 @@ $ snyk test
### Evitar otras vulnerabilidades conocidas
-Esté atento a los avisos de [Node Security Project](https://npmjs.com/advisories) o [Snyk](https://snyk.io/vuln/) que pueden afectar a Express u otros módulos que tu aplicación utiliza. En general, estas bases de datos son excelentes recursos para conocimientos y herramientas sobre la seguridad de Node.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. En general, estas bases de datos son excelentes recursos para conocimientos y herramientas sobre la seguridad de Node.
Finalmente, las aplicaciones Express—como cualquier otra aplicación web—pueden ser vulnerables a una variedad de ataques basados en la web. Familiarizarse con [vulnerabilidades web](https://www.owasp.org/www-project-top-ten/) y tomar precauciones para evitarlas.
diff --git a/src/content/pages/es/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/es/advanced/healthcheck-graceful-shutdown.md
index bb0926aaa2..5324873999 100644
--- a/src/content/pages/es/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/es/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Revisiones de salud
-Un balanceador de carga utiliza cheques de salud para determinar si una instancia de aplicación es saludable y puede aceptar solicitudes. Por ejemplo, [Kubernetes tiene dos cheques de salud](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+Un balanceador de carga utiliza cheques de salud para determinar si una instancia de aplicación es saludable y puede aceptar solicitudes. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, que determina cuándo reiniciar un contenedor.
- `readiness`, que determina cuando un contenedor está listo para empezar a aceptar tráfico. Cuando un pod no está listo, se elimina de los balanceadores de carga de servicio.
diff --git a/src/content/pages/es/guide/database-integration.mdx b/src/content/pages/es/guide/database-integration.mdx
index 1b05d684b9..5e1650d190 100644
--- a/src/content/pages/es/guide/database-integration.mdx
+++ b/src/content/pages/es/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Descubra cómo integrar varias bases de datos con aplicaciones Expr
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Añadir la capacidad para conectar bases de datos a aplicaciones Express es sólo una cuestión de cargar un controlador Node.js apropiado para la base de datos en su aplicación. Este documento explica brevemente cómo agregar y utilizar algunos de los módulos Node.js más populares para sistemas de base de datos en su aplicación Express:
@@ -34,13 +35,11 @@ Estos controladores de base de datos están entre muchos que están disponibles.
### Instalación
-```bash
-$ npm install cassandra-driver
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**Módulo**: [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Instalación
-```bash
-$ npm install couchbase
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**Módulo**: [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### Instalación
-```bash
-$ npm install nano
-```
+
### Ejemplo
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**Módulo**: [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Instalación
-```bash
-$ npm install level levelup leveldown
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**Módulo**: [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Instalación
-```bash
-$ npm install mysql
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**Módulo**: [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Instalación
-```bash
-$ npm install mongodb
-```
+
-### Ejemplo (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### Ejemplo (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-Si quieres un controlador de modelo de objeto para MongoDB, mira [Mongoose](https://github.com/LearnBoost/mongoose).
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**Módulo**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Instalación
-```bash
-$ npm install neo4j-driver
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
-## Oráculo
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
-**Módulo**: [oracledb](https://github.com/oracle/node-oracledb)
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
+## Oracle
+
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Instalación
-NOTA: [Ver los prerrequisitos de instalación](https://github.com/oracle/node-oracledb#-installation).
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**Módulo**: [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Instalación
-```bash
-$ npm install pg-promise
-```
+
### Ejemplo
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**Módulo**: [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### Instalación
-```bash
-$ npm install redis
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
+```mjs title="index.mjs"
+import redis from 'redis';
+
+const client = redis.createClient();
+
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
+
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
+```
+
## SQL Server
-**Módulo**: [tedious](https://github.com/tediousjs/tedious)
+**Module**: [tedious](https://github.com/tediousjs/tedious)
### Instalación
-```bash
-$ npm install tedious
-```
+
### Ejemplo
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**Módulo**: [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Instalación
-```bash
-$ npm install sqlite3
-```
+
### Ejemplo
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -461,19 +586,17 @@ db.serialize(() => {
db.close();
```
-## Búsqueda elástica
+## Elasticsearch
-**Módulo**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Instalación
-```bash
-$ npm install elasticsearch
-```
+
### Ejemplo
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/es/guide/migrating-4.mdx b/src/content/pages/es/guide/migrating-4.mdx
index f41d2fb7e8..204b7fe6bb 100644
--- a/src/content/pages/es/guide/migrating-4.mdx
+++ b/src/content/pages/es/guide/migrating-4.mdx
@@ -4,39 +4,23 @@ description: Una guía para migrar sus aplicaciones Express.js de la versión 3
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 es un cambio de ruptura de Express 3. Esto significa que una aplicación Express 3 funcionará _no_ si actualiza la versión Express en sus dependencias.
Este artículo cubre:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Cambios en Express 4
Hay varios cambios significativos en Express 4:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
Ver también:
@@ -252,7 +236,7 @@ El siguiente ejemplo crea un enrutador como módulo, carga middleware en
Por ejemplo, crea un archivo de enrutador llamado `birds.js` en el directorio de la aplicación,
con el siguiente contenido:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Luego, cargue el módulo de enrutador en la aplicación:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
La aplicación ahora podrá manejar las solicitudes a las rutas `/birds` y
`/birds/about`, y llamará al middleware `timeLog`
que es específico de la ruta.
@@ -298,9 +312,7 @@ La siguiente tabla muestra otros cambios pequeños pero importantes en Express 4
| Node.js |
-
- Express 4 requiere Node.js 0.10.x o posterior y ha eliminado el soporte para Node.js 0.8.x.
- |
+ Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` |
@@ -377,7 +389,7 @@ Los archivos de interés son `app.js` y `package.json`.
Considere una aplicación Express v.3 con el siguiente archivo `app.js`:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -411,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
El archivo `package.json` de la versión 3 que acompaña podría verse
@@ -437,9 +483,7 @@ Comience el proceso de migración instalando el middleware necesario para la apl
Express 4 y actualizando Express y Pug a su respectiva versión
con el siguiente comando:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Hacer los siguientes cambios a `app.js`:
@@ -489,7 +533,7 @@ Ejecutar el comando anterior `npm` actualizará `package.json` de la siguiente m
Luego, elimina el código inválido, carga el middleware necesario y haz otros cambiosformat@@0
según sea necesario. El archivo `app.js` se verá así:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -539,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
A menos que necesite trabajar directamente con el módulo `http` (socket.io/SPDY/HTTPS), cargarlo no es necesario, y la aplicación puede iniciarse simplemente de esta manera:
@@ -574,18 +667,14 @@ el generador de aplicaciones Express 3 y luego instalar el nuevo generador
Si ya tiene instalado el generador de aplicaciones Express 3 en su sistema,
debe desinstalarlo:
-```bash
-$ npm uninstall -g express
-```
+
Dependiendo de cómo estén configurados tus privilegios de archivo y directorio,
puede que necesites ejecutar este comando con `sudo`.
Ahora instale el nuevo generador:
-```bash
-$ npm install -g express-generator
-```
+
Dependiendo de cómo estén configurados tus privilegios de archivo y directorio,
puede que necesites ejecutar este comando con `sudo`.
diff --git a/src/content/pages/es/guide/migrating-5.mdx b/src/content/pages/es/guide/migrating-5.mdx
index e50f5cbee3..edc2c71270 100644
--- a/src/content/pages/es/guide/migrating-5.mdx
+++ b/src/content/pages/es/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: Una guía completa para migrar sus aplicaciones Express.js de la ve
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 5 no es muy diferente de Express 4; aunque mantiene la misma API básica, todavía hay cambios que rompen la compatibilidad con la versión anterior. Por lo tanto, una aplicación construida con Express 4 podría no funcionar si la actualiza para usar Express 5.
@@ -11,9 +12,7 @@ Express 5 no es muy diferente de Express 4; aunque mantiene la misma API básica
Para instalar esta versión, necesitas tener una **versión 18 o superior de Node.js**. Luego, ejecuta el siguiente comando en el directorio de tu aplicación:
-```sh
-npm install "express@5"
-```
+
Luego puede ejecutar sus pruebas automatizadas para ver qué falla, y arreglar problemas de acuerdo a las actualizaciones que se listan a continuación. Después de gestionar los fallos de prueba, ejecuta tu aplicación para ver qué errores ocurren. Descubrirá de inmediato si la aplicación utiliza cualquier método o propiedades que no sean compatibles.
@@ -23,15 +22,11 @@ Para ayudarle a migrar su servidor exprés, hemos creado un conjunto de códigos
Ejecutar el siguiente comando para ejecutar todos los codemods disponibles:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
Si quieres ejecutar un código específico, puedes ejecutar el siguiente comando:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
Puedes encontrar la lista de códigos disponibles [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Inicialmente, `del` fue usado en lugar de `delete`, porque `delete` es una palab
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
O puedes actualizar tu código manualmente:
@@ -80,9 +73,7 @@ Los siguientes nombres de métodos han sido pluralizados. En Express 4, el uso d
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
O puedes actualizar tu código manualmente:
@@ -103,7 +94,7 @@ O puedes actualizar tu código manualmente:
Un personaje con dos puntos (:) en el nombre de la aplicación `. aram(name, fn)` función es un remanente de Express 3, y por el bien de la compatibilidad hacia atrás, Express 4 lo soportó con un aviso de desaprobación. Express 5 lo ignorará silenciosamente y usará el parámetro de nombre sin prefijarlo con dos puntos.
-Esto no debería afectar tu código si sigues la documentación Express 4 de [app.param](/4x/api#app.param), ya que no hace mención alguna de los dos puntos principales.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(nombre)
@@ -113,9 +104,7 @@ Se ha eliminado este método potencialmente confuso y peligroso de recuperar dat
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
O puedes actualizar tu código manualmente:
@@ -140,9 +129,7 @@ Express 5 ya no soporta la firma `res.json(obj, status)`. En su lugar, establece
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
O puedes actualizar tu código manualmente:
@@ -161,9 +148,7 @@ Express 5 ya no soporta la firma `res.jsonp(obj, status)`. En su lugar, establec
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
O puedes actualizar tu código manualmente:
@@ -182,16 +167,19 @@ Express 5 ya no soporta la firma `res.redirect(url, status)`. En su lugar, utili
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
O puedes actualizar tu código manualmente:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 ya no soporta la cadena mágica `back` en los métodos `res.redirect()
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
O puedes actualizar tu código manualmente:
@@ -224,9 +210,7 @@ Express 5 ya no soporta la firma `res.send(obj, status)`. En su lugar, establece
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
O puedes actualizar tu código manualmente:
@@ -246,9 +230,7 @@ Si necesita enviar un número usando el `res. función end()`, cita el número p
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
O puedes actualizar tu código manualmente:
@@ -267,9 +249,7 @@ La función `res.sendfile()` ha sido reemplazada por una versión `res.sendFile(
Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
O puedes actualizar tu código manualmente:
@@ -284,6 +264,10 @@ O puedes actualizar tu código manualmente:
Las opciones `hidden` y `from` para `res.sendFile()` ya no son compatibles. En su lugar, usa `dotfiles` y `root`.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### Cómo actualizar
```diff
@@ -293,12 +277,30 @@ Las opciones `hidden` y `from` para `res.sendFile()` ya no son compatibles. En s
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### opciones express.static()
Las opciones `hidden` y `from` para `express.static()` ya no están soportadas. En su lugar, usa `dotfiles` y `root`. Ten en cuenta que `from` nunca fue documentado en la API pero fue aceptado como un alias para `root`. El valor por defecto de `dotfiles` ahora es `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### Cómo actualizar
+Puedes actualizar automáticamente tu código ejecutando el siguiente comando:
+
+
+
+O puedes actualizar tu código manualmente:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ Las opciones `hidden` y `from` para `express.static()` ya no están soportadas.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
La firma `router.param(fn)` fue usada para modificar el comportamiento de la función `router.param(name, fn)`. Ha sido obsoleto desde v4.11.0, y Express 5 ya no lo soporta en absoluto.
@@ -449,6 +458,25 @@ Serve directorios de puntos específicos usando explícitamente `dotfiles: opci
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### Cómo actualizar
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### app.listen
En Express 5, el método `app.listen` invocará la función callback proporcionada por el usuario (si se proporciona) cuando el servidor reciba un evento de error. En Express 4, esos errores se lanzarían. This change shifts error handling responsibility to the callback function in Express 5. Si hay un error, se pasará al callback como argumento.
diff --git a/src/content/pages/es/resources/contributing.mdx b/src/content/pages/es/resources/contributing.mdx
index e8157b1613..c871592330 100644
--- a/src/content/pages/es/resources/contributing.mdx
+++ b/src/content/pages/es/resources/contributing.mdx
@@ -149,13 +149,11 @@ project for at least 6 months as a committer prior to the request. Deben haber a
con contribuciones de código, así como con problemas de prueba. También es necesario que
tenga habilitada la 2FA en sus cuentas de GitHub y npm.
-Cualquier miembro del TC o un capitán existente en el repositorio **igual** puede nominar otro committer
-al rol del capitán. Para ello, deben presentar un PR a este documento. actualizar la sección
-**Capturas de proyecto activas** (manteniendo la ordenación) con el nombre
-del proyecto el manejador de GitHub del nominado, y su nombre de usuario npm (si es diferente).
+Un miembro de TC o un capitán de repo existente **en el mismo proyecto** puede nominar a un nuevo capitán. Los capitanes de Repo de otros proyectos no deben nombrar capitanes para un proyecto diferente.
- Repos puede tener tantos capitanes como tengan sentido para el alcance del trabajo.
-- Un miembro de TC o un capitán de repo existente **en el mismo proyecto** puede nominar a un nuevo capitán.
+- Cualquier miembro del TC o un capitán existente en el repositorio **igual** puede nominar otro committer
+ al rol del capitán.
Los capitanes de Repo de otros proyectos no deben nombrar capitanes para un proyecto diferente.
Las relaciones públicas requerirán al menos 2 aprobaciones de los miembros del TC y 2 semanas de tiempo de espera para permitir
diff --git a/src/content/pages/es/resources/glossary.mdx b/src/content/pages/es/resources/glossary.mdx
index 4ad54a18e2..6a2d68ef3c 100644
--- a/src/content/pages/es/resources/glossary.mdx
+++ b/src/content/pages/es/resources/glossary.mdx
@@ -27,7 +27,7 @@ Una función que es invocada por la capa de enrutamiento Express antes del gesto
- `var foo = require('middleware')` es llamado _requiring_ o _using_ un módulo Node.js. Luego la instrucción `var mw = foo()` típicamente devuelve el middleware.
- `app.use(mw)` se llama _agregando el middleware a la pila global de procesamiento de datos_.
-- `app.get('/foo', mw, function (req, res) { ... })` se llama _adding the middleware to the "GET /foo" processing stack_.
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/es/resources/index.mdx b/src/content/pages/es/resources/index.mdx
index 16d96e292d..692b158295 100644
--- a/src/content/pages/es/resources/index.mdx
+++ b/src/content/pages/es/resources/index.mdx
@@ -23,7 +23,7 @@ Encuentre recursos para ayudarlo a aprender, contribuir y conectarse con el ecos
@@ -35,7 +35,7 @@ Encuentre recursos para ayudarlo a aprender, contribuir y conectarse con el ecos
diff --git a/src/content/pages/es/resources/middleware/body-parser.mdx b/src/content/pages/es/resources/middleware/body-parser.mdx
index 519cc29400..d25df837d6 100644
--- a/src/content/pages/es/resources/middleware/body-parser.mdx
+++ b/src/content/pages/es/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Cuerpo Node.js analizando middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Otros analizadores de cuerpo en los que podría estar interesado:
## Instalación
-```sh
-$ npm install body-parser
-```
+
## API
@@ -111,8 +110,8 @@ a `'100kb'`.
##### reviver
La opción `reviver` se pasa directamente a `JSON.parse` como segundo argumento
-. Puede encontrar más información sobre este argumento
-[en la documentación MDN sobre JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### estricto
diff --git a/src/content/pages/es/resources/middleware/compression.mdx b/src/content/pages/es/resources/middleware/compression.mdx
index 8e62e2028e..39f966d01c 100644
--- a/src/content/pages/es/resources/middleware/compression.mdx
+++ b/src/content/pages/es/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Middleware de compresión Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
@@ -119,7 +118,7 @@ con respecto al uso.
Tipo: `Objeto`
-Esto especifica las opciones para configurar Brotli. Vea [documentación de Node.js](https://nodejs.org/api/zlib.html#class-brotlioptions) para una lista completa de opciones disponibles.
+Esto especifica las opciones para configurar Brotli. Vea [documentación de Node.js] (https://nodejs.org/api/zlib.html#class-brotlioptions) para una lista completa de opciones disponibles.
##### estrategia
@@ -297,7 +296,7 @@ El proyecto Express.js acoge con satisfacción todas las contribuciones construc
desde código para correcciones de errores y mejoras, hasta adiciones y correcciones a la documentación, ¡pruebas
adicionales, probando solicitudes y problemas entrantes, y más!
-Vea la [Guía de contribución](https://github.com/expressjs/express/blob/master/Contributing.md) para más detalles técnicos sobre contribuir.
+Vea la [Guía de contribución] (https://github.com/expressjs/express/blob/master/Contributing.md) para más detalles técnicos sobre contribuir.
## Licencia
diff --git a/src/content/pages/es/resources/middleware/cookie-parser.mdx b/src/content/pages/es/resources/middleware/cookie-parser.mdx
index 5ed36171e4..3300eaa023 100644
--- a/src/content/pages/es/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/es/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Analizar cookies de petición HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/cookie-session.mdx b/src/content/pages/es/resources/middleware/cookie-session.mdx
index abe792115e..9a1fadb1b2 100644
--- a/src/content/pages/es/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/es/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Middleware de sesión de cookies
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/cors.mdx b/src/content/pages/es/resources/middleware/cors.mdx
index 7952788f20..d3e4fc1cd5 100644
--- a/src/content/pages/es/resources/middleware/cors.mdx
+++ b/src/content/pages/es/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS es un middleware [Node.js](https://nodejs.org/en/) para [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) que establece cabeceras de respuesta [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS). Estas cabeceras le dicen a los navegadores qué orígenes pueden leer las respuestas de su servidor.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. Estas cabeceras le dicen a los navegadores qué orígenes pueden leer las respuestas de su servidor.
@@ -28,7 +29,7 @@ CORS es un middleware [Node.js](https://nodejs.org/en/) para [Express](https://e
- [Configurando CORS con origen dinámico](#configuring-cors-w-dynamic-origin)
- [Habilitando CORS Pre-vuelo](#enabling-cors-pre-flight)
- [Personalizar ajustes CORS dinámicamente por solicitud](#customizing-cors-settings-dynamically-per-request)
-- [Opciones de configuración](#configuration-options)
+- [Opciones de configuración] (#configuration-options)
- [Misconcepciones comunes](#common-misconceptions)
- [License](#license)
- [Autor Original](#original-author)
@@ -39,9 +40,7 @@ Este es un módulo [Node.js](https://nodejs.org/en/) disponible a través del
[npm registry](https://www.npmjs.com/). La instalación se realiza usando el comando
[`npm install`](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Uso
@@ -83,7 +82,7 @@ app.listen(80, function () {
### Configuring CORS
-Vea las [opciones de configuración](#configuration-options) para más detalles.
+Vea las [opciones de configuración] (#configuration-options) para más detalles.
```javascript
var express = require('express');
@@ -114,7 +113,7 @@ a la opción `origin`. Esta función será pasada una cadena que sea el origen
El argumento `origin` al callback puede ser cualquier valor permitido para la opción `origin`
del middleware, excepto una función. Vea la sección
-[opciones de configuración](#configuration-options) para más información sobre todos los tipos de valor
+[opciones de configuración] (#configuration-options) para más información sobre todos los tipos de valor
posibles.
Esta función está diseñada para permitir la carga dinámica de origen(s) permitidos de
diff --git a/src/content/pages/es/resources/middleware/errorhandler.mdx b/src/content/pages/es/resources/middleware/errorhandler.mdx
index bee81232fa..7551fa9384 100644
--- a/src/content/pages/es/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/es/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Manejador de errores de sólo desarrollo middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/index.mdx b/src/content/pages/es/resources/middleware/index.mdx
new file mode 100644
index 0000000000..69bcf45ad9
--- /dev/null
+++ b/src/content/pages/es/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Descripción |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ Esta información se refiere a sitios de terceros, productos o módulos que no son mantenidos por el
+ equipo de Expressjs. La lista aquí no constituye un aviso o recomendación del equipo de proyecto
+ Expressjs.
+
+
+| Middleware module | Descripción |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/es/resources/middleware/method-override.mdx b/src/content/pages/es/resources/middleware/method-override.mdx
index 1dae104a16..28fbb2317d 100644
--- a/src/content/pages/es/resources/middleware/method-override.mdx
+++ b/src/content/pages/es/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Anular verbos HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/morgan.mdx b/src/content/pages/es/resources/middleware/morgan.mdx
index 45cdba99e8..5b097156ad 100644
--- a/src/content/pages/es/resources/middleware/morgan.mdx
+++ b/src/content/pages/es/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: Middleware del registrador de peticiones HTTP para Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ Este es un módulo [Node.js](https://nodejs.org/en/) disponible a través del
[npm registry](https://www.npmjs.com/). La instalación se realiza usando el comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ Si no se da ningún formato, entonces el predeterminado es `web`.
La versión HTTP de la solicitud.
-##### :method
+#####
El método HTTP de la solicitud.
-##### :pid
+#####
El ID de proceso del proceso Node.js que maneja la solicitud.
-##### :referrer
+#####
La cabecera del Referrer de la solicitud. Esto usará la cabecera de referencia mal escrita estándar si existe, de lo contrario Referrer.
@@ -239,7 +238,7 @@ están escritas, en milisegundos.
El argumento `digits` es un número que especifica el número de dígitos a
incluir en el número, por defecto a `3`, que proporciona precisión microsegundo.
-##### :status
+#####
El código de estado de la respuesta.
@@ -255,7 +254,7 @@ ha terminado de escribirse en la conexión, en milisegundos.
El argumento `digits` es un número que especifica el número de dígitos a
incluir en el número, por defecto a `3`, que proporciona precisión microsegundo.
-##### :url
+#####
La URL de la solicitud. Esto usará `req.originalUrl` si existe, de lo contrario `req.url`.
diff --git a/src/content/pages/es/resources/middleware/multer.mdx b/src/content/pages/es/resources/middleware/multer.mdx
index 622a867a1c..67099697ba 100644
--- a/src/content/pages/es/resources/middleware/multer.mdx
+++ b/src/content/pages/es/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware para manejar multiparte/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ Este README también está disponible en otros idiomas:
## Instalación
-```sh
-$ npm install multer
-```
+
## Uso
@@ -263,8 +262,7 @@ null como primer parámetro), consulte
#### `MemoriaStorage`
-El motor de almacenamiento de memoria almacena los archivos en memoria como objetos `Buffer`.
-no tiene ninguna opción.
+El motor de almacenamiento de memoria almacena los archivos en memoria como objetos `Buffer`. no tiene ninguna opción.
```javascript
const storage = multer.memoryStorage();
@@ -293,6 +291,7 @@ Los siguientes valores enteros están disponibles:
| `archivos` | Para formularios de varias partes, el número máximo de campos de archivo | Infinidad |
| `partes` | Para formularios de varias partes, el número máximo de partes (campos + archivos) | Infinidad |
| `pares de cabecera` | Para formularios de varias partes, el número máximo de pares de cabecera=>valor para analizar | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinidad |
Especificar los límites puede ayudar a proteger su sitio contra ataques de denegación de servicio (DoS).
@@ -317,6 +316,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Manejo de errores
Cuando se encuentra un error, Multer delegará el error a Express. You can
diff --git a/src/content/pages/es/resources/middleware/response-time.mdx b/src/content/pages/es/resources/middleware/response-time.mdx
index 3cd35702e5..c3f5d6c85c 100644
--- a/src/content/pages/es/resources/middleware/response-time.mdx
+++ b/src/content/pages/es/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Tiempo de respuesta para servidores Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/serve-favicon.mdx b/src/content/pages/es/resources/middleware/serve-favicon.mdx
index 3a5f588f7b..cb5e32f70e 100644
--- a/src/content/pages/es/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/es/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon sirviendo middleware con caché
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/serve-index.mdx b/src/content/pages/es/resources/middleware/serve-index.mdx
index eb2f79256e..74d858e378 100644
--- a/src/content/pages/es/resources/middleware/serve-index.mdx
+++ b/src/content/pages/es/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Servir listados de directorios
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/serve-static.mdx b/src/content/pages/es/resources/middleware/serve-static.mdx
index 48f9f6f027..1901953e15 100644
--- a/src/content/pages/es/resources/middleware/serve-static.mdx
+++ b/src/content/pages/es/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Servir archivos estáticos
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/resources/middleware/session.mdx b/src/content/pages/es/resources/middleware/session.mdx
index e61811602e..89b00edc3d 100644
--- a/src/content/pages/es/resources/middleware/session.mdx
+++ b/src/content/pages/es/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Middleware de sesión simple para Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Instalación
@@ -18,9 +19,7 @@ Este es un módulo [Node.js](https://nodejs.org/en/) disponible a través del
[npm registry](https://www.npmjs.com/). La instalación se realiza usando el comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -146,7 +145,8 @@ Especifica que la `cadena` sea el valor para el [`Priority` atributo `Set-Cookie
Puede encontrar más información sobre los diferentes niveles de prioridad en
[la especificación][rfc-west-cookie-priority-00-4.1].
-**Nota** Este es un atributo que aún no ha sido completamente estandarizado y puede cambiar en el futuro.
+**Nota** Este es un atributo que aún no ha sido completamente estandarizado y puede cambiar en
+el futuro.
Esto también significa que muchos clientes pueden ignorar este atributo hasta que lo entiendan.
##### cookie.sameSite
@@ -164,8 +164,7 @@ Por defecto, esto es `false`.
Puede encontrar más información sobre los diferentes niveles de cumplimiento en
[la especificación][rfc-6265bis-03-4.1.2.7].
-**Nota** Este es un atributo que aún no ha sido completamente estandarizado y puede cambiar en
-el futuro. Esto también significa que muchos clientes pueden ignorar este atributo hasta que lo entiendan.
+**Nota** Este es un atributo que aún no ha sido completamente estandarizado y puede cambiar en el futuro. Esto también significa que muchos clientes pueden ignorar este atributo hasta que lo entiendan.
**Nota** Hay un [borrador de especificación](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
que requiere que el atributo `Secure` se establezca a `true` cuando el atributo `SameSite` ha sido
diff --git a/src/content/pages/es/resources/middleware/timeout.mdx b/src/content/pages/es/resources/middleware/timeout.mdx
index 8c10da9888..9ad5493b5b 100644
--- a/src/content/pages/es/resources/middleware/timeout.mdx
+++ b/src/content/pages/es/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Solicitar middleware de tiempo de espera para Conectar/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Realiza una solicitud en el marco de la aplicación Connect/Express.
@@ -20,9 +21,7 @@ Este es un módulo [Node.js](https://nodejs.org/en/) disponible a través del
[npm registry](https://www.npmjs.com/). La instalación se realiza usando el comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/es/resources/middleware/vhost.mdx b/src/content/pages/es/resources/middleware/vhost.mdx
index 13be72f9ea..e5a8af1657 100644
--- a/src/content/pages/es/resources/middleware/vhost.mdx
+++ b/src/content/pages/es/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Alojamiento de dominio virtual
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/es/support.md b/src/content/pages/es/support.md
index 0e8357c0df..95210551a8 100644
--- a/src/content/pages/es/support.md
+++ b/src/content/pages/es/support.md
@@ -7,14 +7,14 @@ Sólo se admite la última versión de cualquier línea de lanzamiento mayor.
Las versiones que son EOL (end-of-life) _pueden_ recibir actualizaciones para vulnerabilidades de seguridad críticas, pero el equipo de Express no ofrece ninguna garantía y no planea abordar o corregir versiones para ningún problema encontrado.
-| Versión principal | Versión mínima de Node.js | Inicio de Soporte | Fecha de fin de soporte |
-| ------------------- | ------------------------- | ------------------ | ----------------------- |
-| [**v5.x**](/5x/api) | 18 | Septiembre de 2024 | **en curso** |
-| [**v4.x**](/4x/api) | 0.10.0 | Abril de 2014 | **en curso** |
-| [**v3.x**](/3x/api) | 0.8.0 | Octubre de 2012 | Julio de 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | Marzo de 2011 | Julio de 2012 |
-| **v1.x** | 0.2.0 | Diciembre 2010 | Marzo de 2011 |
-| **v0.14.x** | 0.1.98 | Diciembre 2010 | Diciembre 2010 |
+| Versión principal | Versión mínima de Node.js | Inicio de Soporte | Fecha de fin de soporte |
+| -------------------------------------------------------------- | ------------------------- | ------------------ | ----------------------- |
+| [**v5.x**](/5x/api) | 18 | Septiembre de 2024 | **en curso** |
+| [**v4.x**](/4x/api) | 0.10.0 | Abril de 2014 | **en curso** |
+| [**v3.x**](/3x/api) | 0.8.0 | Octubre de 2012 | Julio de 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | Marzo de 2011 | Julio de 2012 |
+| **v1.x** | 0.2.0 | Diciembre 2010 | Marzo de 2011 |
+| **v0.14.x** | 0.1.98 | Diciembre 2010 | Diciembre 2010 |
## Opciones de soporte comercial
diff --git a/src/content/pages/fr/advanced/best-practice-performance.md b/src/content/pages/fr/advanced/best-practice-performance.md
index 1de59e1d0d..1c325d0e30 100644
--- a/src/content/pages/fr/advanced/best-practice-performance.md
+++ b/src/content/pages/fr/advanced/best-practice-performance.md
@@ -11,7 +11,7 @@ Ce sujet tombe clairement dans le monde des « dévalises », englobant tant le
- [Utiliser la compression gzip](#use-gzip-compression)
- [Ne pas utiliser de fonctions synchrones](#dont-use-synchronous-functions)
- [Faire la journalisation correctement](#do-logging-correctly)
- - [Gérer les exceptions correctement](#handle-exceptions-properly)
+ - [Gérer les exceptions correctement] (#handle-exceptions-properly)
- Choses à faire dans votre environnement / configuration (partie Ops) :
- [Définir NODE_ENV comme "production"](#set-node_env-to-production)
- (#ensure-your-app-automatically-restarts)
@@ -27,13 +27,13 @@ Voici quelques choses que vous pouvez faire dans votre code pour améliorer les
- [Utiliser la compression gzip](#use-gzip-compression)
- [Ne pas utiliser de fonctions synchrones](#dont-use-synchronous-functions)
- [Faire la journalisation correctement](#do-logging-correctly)
-- [Gérer les exceptions correctement](#handle-exceptions-properly)
+- [Gérer les exceptions correctement] (#handle-exceptions-properly)
### Utiliser la compression gzip
La compression Gzip peut réduire considérablement la taille du corps de réponse et ainsi augmenter la vitesse d'une application web. Utilisez le middleware [compression](https://www.npmjs.com/package/compression) pour la compression gzip dans votre application Express. Par exemple :
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-Pour un site internet à fort trafic en production, la meilleure façon de mettre en place une compression est de l'implémenter à un niveau de proxy inverse (voir [Utiliser un proxy inverse](#use-a-reverse-proxy)). Dans ce cas, vous n'avez pas besoin d'utiliser le middleware de compression. Pour plus de détails sur l'activation de la compression gzip dans Nginx, voir [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) dans la documentation Nginx.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### Ne pas utiliser les fonctions synchrones
+### Don't use synchronous functions
-Les fonctions et méthodes synchrones lient le processus d'exécution jusqu'à ce qu'elles soient retournées. Un seul appel à une fonction synchrone peut retourner en quelques microsecondes ou millisecondes, Cependant, dans les sites Web à fort trafic, ces appels s'ajoutent et réduisent les performances de l'application. Évitez leur utilisation en production.
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Bien que Node et de nombreux modules fournissent des versions synchrones et asynchrones de leurs fonctions, utilisez toujours la version asynchrone en production. Le seul moment où une fonction synchrone peut être justifiée est au démarrage initial.
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-Vous pouvez utiliser le flag en ligne de commande `--trace-sync-io` pour afficher une alerte et une trace de pile chaque fois que votre application utilise une API synchrone. Bien sûr, vous ne voudriez pas utiliser cela en production, mais plutôt vous assurer que votre code est prêt pour la production. Voir la [documentation des options de la ligne de commande node](https://nodejs.org/api/cli.html#trace-sync-io) pour plus d'informations.
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Faire la journalisation correctement
+### Do logging correctly
-En général, il y a deux raisons de se connecter depuis votre application : pour le débogage et pour l'activité des applications de journalisation (essentiellement tout le reste). Utiliser `console.log()` ou `console.error()` pour imprimer les messages de log vers le terminal est pratique courante dans le développement. Mais [ces fonctions sont synchronisées](https://nodejs.org/api/console.html#console) lorsque la destination est un terminal ou un fichier, elles ne sont donc pas adaptées à la production, à moins que vous ne conduisiez la sortie vers un autre programme.
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### Pour le débogage
+#### For debugging
-Si vous êtes connecté à des fins de débogage, alors au lieu d'utiliser `console.log()`, utilisez un module de débogage spécial comme [debug](https://www.npmjs.com/package/debug). Ce module vous permet d'utiliser la variable d'environnement DEBUG pour contrôler quels messages de débogage sont envoyés à `console.error()`, le cas échéant. Pour garder votre application purement asynchrone, vous vouliez toujours canaliser `console.error()` vers un autre programme. Mais alors, vous n'allez pas vraiment déboguer en production, n'est-ce pas?
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### Pour l'activité de l'application
+#### For app activity
-Si vous connectez l'activité de l'application (par exemple, suivre le trafic ou les appels API), au lieu d'utiliser la « console ». og()\`, utilise une bibliothèque de log comme [Pino](https://www.npmjs.com/package/pino), qui est l'option la plus rapide et la plus efficace disponible.
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### Gérer correctement les exceptions
+### Handle exceptions properly
-Les applications de nœud plantent lorsqu'elles rencontrent une exception non prise. Ne pas gérer les exceptions et prendre les actions appropriées fera planter votre application Express et se déconnectera. Si vous suivez les conseils de [Assurez-vous que votre application redémarre automatiquement](#ensure-your-app-automatically-restarts) ci-dessous, votre application se remettra d'un crash. Heureusement, les applications Express ont généralement un temps de démarrage court. Néanmoins, vous voulez éviter de planter en premier lieu, et pour ce faire, vous devez gérer les exceptions correctement.
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-Pour vous assurer de gérer toutes les exceptions, utilisez les techniques suivantes :
+To ensure you handle all exceptions, use the following techniques:
-- [Utiliser try-catch](#use-try-catch)
-- [Utiliser des promesses](#use-promises)
+- [Use try-catch](#use-try-catch)
+- [Use promises](#use-promises)
-Avant de plonger dans ces sujets, vous devriez avoir une compréhension de base de la gestion des erreurs Node/Express : utiliser les premiers callbacks d'erreurs et propager les erreurs dans les middleware. Le noeud utilise une convention "error-first callback" pour retourner des erreurs à partir de fonctions asynchrones, où le premier paramètre de la fonction callback est l'objet erreur, suivi par les données de résultat dans les paramètres successifs. Pour indiquer aucune erreur, passez null comme premier paramètre. La fonction callback doit suivre la première convention de callback pour gérer l'erreur de manière significative. Et dans Express, la meilleure pratique est d'utiliser la fonction next() pour propager les erreurs à travers la chaîne du middleware.
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-Pour en savoir plus sur les fondamentaux de la gestion des erreurs, voir :
+For more on the fundamentals of error handling, see:
-- [Gestion des erreurs dans Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Utiliser try-catch
+#### Use try-catch
-Try-catch est un langage JavaScript que vous pouvez utiliser pour attraper des exceptions dans le code synchrone. Utilisez try-catch, par exemple, pour gérer les erreurs d'analyse JSON comme indiqué ci-dessous.
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-Voici un exemple d'utilisation de try-catch pour gérer une éventuelle exception plantant le processus.
-Cette fonction du middleware accepte un paramètre de champ de requête nommé "params" qui est un objet JSON.
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-Cependant, essayer-catch ne fonctionne que pour du code synchrone. Parce que la plate-forme Node est principalement asynchrone (particulièrement dans un environnement de production), les captures d'essai ne prendront pas beaucoup d'exceptions.
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Utiliser les promesses
+#### Use promises
-Lorsqu'une erreur est levée dans une fonction `async` ou qu'une promesse rejetée est attendue à l'intérieur d'une fonction `async`, ces erreurs seront passées au gestionnaire d'erreurs comme si elle appelait `next(err)`
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-De plus, vous pouvez utiliser des fonctions asynchrones pour votre middleware, et le routeur gérera des erreurs si la promesse échoue, par exemple :
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-La meilleure pratique est de gérer les erreurs le plus près possible du site. Donc, tant que ceci est maintenant géré dans le routeur, Il est préférable d’attraper l’erreur dans le middleware et de la manipuler sans s’appuyer sur un middleware séparé.
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### Ce qu'il ne faut pas faire
+#### What not to do
-Une chose que vous ne devriez pas _faire_ est d'écouter l'évènement `uncatghtException` émise lorsqu'une exception bulle tout le retour à la boucle d'événement. Ajouter un event listener pour `uncatghtException` changera le comportement par défaut du processus qui rencontre une exception ; le processus continuera à fonctionner malgré l'exception. Cela peut sembler un bon moyen d'empêcher votre application de planter, mais continuer à exécuter l'application après une exception non capturée est une pratique dangereuse et n'est pas recommandé, parce que l'état du processus devient peu fiable et imprévisible.
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-De plus, l'utilisation de `uncaughtException` est officiellement reconnue comme [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Donc l'écoute de `uncatghtException` est juste une mauvaise idée. C'est pourquoi nous recommandons des choses comme des processus multiples et des superviseurs : plantage et redémarrage est souvent le moyen le plus fiable de se remettre d'une erreur.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-Nous ne recommandons pas non plus d'utiliser [domains](https://nodejs.org/api/domain.html). Il ne résout généralement pas le problème et est un module obsolète.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## Choses à faire dans votre environnement / configuration
+## Things to do in your environment / setup
-Voici quelques choses que vous pouvez faire dans votre environnement système pour améliorer les performances de votre application :
+Here are some things you can do in your system environment to improve your app's performance:
- [Définir NODE_ENV comme "production"](#set-node_env-to-production)
- (#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Voici quelques choses que vous pouvez faire dans votre environnement système po
- [Utiliser un répartiteur de charge](#use-a-load-balancer)
- [Utiliser un proxy inverse](#use-a-reverse-proxy)
-### Définir NODE_ENV à "production"
+### Set NODE_ENV to "production"
-La variable d'environnement NODE_ENV spécifie l'environnement dans lequel une application est en cours d'exécution (généralement, développement ou production). L'une des choses les plus simples que vous pouvez faire pour améliorer les performances est de définir NODE_ENV à `production`.
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-Définir NODE_ENV sur "production" rend Express:
+Setting NODE_ENV to "production" makes Express:
-- Modèles d'affichage du cache.
-- Cache les fichiers CSS générés à partir des extensions CSS.
-- Générer des messages d'erreur moins verbeux.
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-[Les tests indiquent](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) que cela peut améliorer les performances de l'application par un facteur de trois !
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-Si vous avez besoin d'écrire du code spécifique à l'environnement, vous pouvez vérifier la valeur de NODE_ENV avec `process.env.NODE_ENV`. Sachez que la vérification de la valeur d'une variable d'environnement entraîne une pénalité de performance, et qu'elle devrait donc être faite avec modération.
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-En développement, vous définissez généralement des variables d'environnement dans votre shell interactif, par exemple en utilisant `export` ou votre fichier `.bash_profile`. Mais en général, vous ne devriez pas le faire sur un serveur de production ; au lieu de cela, utilisez le système d'initialisation de votre système d'exploitation (système). La section suivante fournit plus de détails sur l'utilisation de votre système d'initialisation en général, mais le paramètre `NODE_ENV` est si important pour les performances (et facile à faire), qu'il est mis en évidence ici.
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-Avec le système, utilisez la directive `Environnement` dans votre fichier unitaire. Par exemple :
+With systemd, use the `Environment` directive in your unit file. Par exemple :
```sh
Environment=NODE_ENV=production
```
-Pour plus d'informations, voir [Utilisation des variables d'environnement dans les unités systémiques](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### Assurez-vous que votre application redémarre automatiquement
+### Ensure your app automatically restarts
-En production, vous ne voulez pas que votre application soit déconnectée, jamais. Cela signifie que vous devez vous assurer qu'il redémarre à la fois si l'application plante et si le serveur lui-même plante. Bien que vous espériez qu'aucun de ces événements ne se produise, réalistement, vous devez rendre compte des deux éventualités par:
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- Utiliser un gestionnaire de processus pour redémarrer l'application (et Node) quand il plante.
-- Utiliser le système d'initialisation fourni par votre système d'exploitation pour redémarrer le gestionnaire de processus lorsque le système d'exploitation plante. Il est également possible d'utiliser le système d'initialisation sans gestionnaire de processus.
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-Les applications de nœud plantent si elles rencontrent une exception non prise. La première chose à faire est de s'assurer que votre application est bien testée et gère toutes les exceptions (voir [gérer les exceptions correctement](#handle-exceptions-properly) pour plus de détails). Mais en tant que sécurité pour les échecs, mettez en place un mécanisme pour vous assurer que si et quand votre application se bloque, elle redémarrera automatiquement.
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### Utiliser un gestionnaire de processus
+#### Use a process manager
-En cours de développement, vous avez démarré votre application simplement à partir de la ligne de commande avec `node server.js` ou quelque chose de similaire. Mais faire cela dans la production est une recette de désastre. Si l'application plante, elle sera hors ligne jusqu'à ce que vous la redémarrez. Pour s'assurer que votre application redémarre si elle plante, utilisez un gestionnaire de processus. Un gestionnaire de processus est un "conteneur" pour les applications qui facilitent le déploiement, fournissent une disponibilité élevée et vous permettent de gérer l'application à l'exécution.
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-En plus de redémarrer votre application en cas de plantage, un gestionnaire de processus peut vous permettre de :
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- Obtenez un aperçu de la performance de l’exécution et de la consommation des ressources.
-- Modifiez les paramètres de façon dynamique pour améliorer les performances.
-- Contrôle de la grappe (pm2).
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-Historiquement, il était populaire d'utiliser un gestionnaire de processus Node.js comme [PM2](https://github.com/Unitech/pm2). Consultez leur documentation si vous le souhaitez. Cependant, nous vous recommandons d'utiliser votre système d'initialisation pour la gestion des processus.
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### Utiliser un système d'initialisation
+#### Use an init system
-La prochaine étape de la fiabilité est de s'assurer que votre application redémarre lorsque le serveur redémarre. Les systèmes peuvent encore diminuer pour diverses raisons. Pour vous assurer que votre application redémarre si le serveur plante, utilisez le système d'initialisation intégré à votre système d'exploitation. Le système d'initialisation principal utilisé aujourd'hui est [systemd](https://wiki.debian.org/systemd).
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Il y a deux façons d'utiliser les systèmes d'initialisation avec votre application Express :
+There are two ways to use init systems with your Express app:
-- Exécutez votre application dans un gestionnaire de processus et installez le gestionnaire de processus en tant que service avec le système d'initialisation. Le gestionnaire de processus redémarrera votre application lorsque l'application se bloque, et le système d'initialisation redémarrera le gestionnaire de processus lorsque le système d'exploitation redémarrera. C'est l'approche recommandée.
-- Exécutez votre application (et Node) directement avec le système d'initialisation. C'est un peu plus simple, mais vous n'aurez pas les avantages supplémentaires d'utiliser un gestionnaire de processus.
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-Systemd est un gestionnaire de systèmes et de services Linux. La plupart des grandes distributions Linux ont adopté le système comme système d'initialisation par défaut.
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-Un fichier de configuration du service système est appelé un fichier \_unit avec un nom de fichier se terminant par `.service`. Voici un exemple de fichier d'unité pour gérer une application Node directement. Remplacez les valeurs placées en `` pour votre système et votre application:
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-Pour plus d'informations sur le système, voir [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Exécutez votre application dans un cluster
+### Run your app in a cluster
-Dans un système multi-cœurs, vous pouvez augmenter les performances d'une application Node de plusieurs fois en lançant un cluster de processus. Un cluster exécute plusieurs instances de l'application, idéalement une instance sur chaque noyau de processeur, distribuant ainsi la charge et les tâches entre les instances.
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.

-IMPORTANT: Puisque les instances de l'application s'exécutent sous forme de processus séparés, elles ne partagent pas le même espace mémoire. C'est-à-dire que les objets sont locaux à chaque instance de l'application. Par conséquent, vous ne pouvez pas maintenir l'état dans le code de l'application. Cependant, vous pouvez utiliser un datastore en mémoire comme [Redis](http://redis.io/) pour stocker des données et des états liés à la session. Cette mise en garde s'applique essentiellement à toutes les formes de mise à l'échelle horizontale, qu'il s'agisse de regroupement avec de multiples processus ou de multiples serveurs physiques.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-Dans les applications groupées, les processus de travail peuvent planter individuellement sans affecter le reste des processus. Mis à part les avantages des performances, l'isolement des défaillances est une autre raison de lancer un cluster de processus applicatifs. À chaque fois qu'un processus worker plante, assurez-vous toujours de consigner l'événement et de faire apparaître un nouveau processus en utilisant la fonction cluster.fork().
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### Utilisation du module de cluster de Node
+#### Using Node's cluster module
-Le groupement est rendu possible avec le [module de clustage](https://nodejs.org/api/cluster.html). Cela permet à un processus maître de faire apparaître des processus de travail et de distribuer des connexions entrantes entre les travailleurs.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### Utilisation du PM2
+#### Using PM2
-Si vous déployez votre application avec PM2, alors vous pouvez profiter de la grappe de serveurs _sans_ pour modifier le code de votre application. Vous devez d'abord vous assurer que votre [application est sans états](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) signifiant qu'aucune donnée locale n'est stockée dans le processus (comme les sessions, les connexions websocket et les autres).
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-Lorsque vous exécutez une application avec PM2, vous pouvez activer le **mode de cluster** pour l'exécuter dans une grappe avec un certain nombre d'instances de votre choix, comme le nombre de processeurs disponibles sur la machine. Vous pouvez modifier manuellement le nombre de processus dans le cluster en utilisant l'outil en ligne de commande `pm2` sans arrêter l'application.
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-Pour activer le mode cluster, lancez votre application comme suit:
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-Ceci peut également être configuré dans un fichier de processus PM2 (`ecosystem.config. s` ou similaire) en définissant `exec_mode` à `cluster` et `instances` au nombre de travaux à commencer.
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-Une fois exécutée, l'application peut être mise à l'échelle comme ceci:
+Once running, the application can be scaled like so:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-Pour plus d'informations sur la grappe de serveurs avec PM2, voir [Mode clusters](https://pm2.keymetrics.io/docs/usage/cluster-mode/) dans la documentation PM2.
+For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### Résultats de la requête de cache
+### Cache request results
-Une autre stratégie pour améliorer les performances en production est de mettre en cache le résultat des requêtes, afin que votre application ne répète pas l'opération pour répondre à la même requête de manière répétée.
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Utilisez un serveur de cache comme [Varnish](https://www.varnish-cache.org/) ou [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (voir aussi [Nginx Caching](https://serversforhackers.com/nginx-caching/)) pour améliorer considérablement la vitesse et les performances de votre application.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Utiliser un répartiteur de charge
+### Use a load balancer
-Quelle que soit l'optimisation d'une application, une seule instance ne peut gérer qu'une quantité limitée de charge et de trafic. Une façon de mettre à l'échelle une application est d'exécuter plusieurs instances et de distribuer le trafic via un répartiteur de charge. La mise en place d'un répartiteur de charge peut améliorer les performances et la vitesse de votre application et l'activer pour augmenter la taille de votre système par une seule instance.
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-Un répartiteur de charge est généralement un mandataire inversé qui orchestre le trafic entre et à partir de plusieurs instances et serveurs d'applications. Vous pouvez facilement configurer un répartiteur de charge pour votre application en utilisant [Nginx](https://nginx.org/en/docs/http/load_balancing.html) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-Avec l'équilibrage de charge, vous devrez peut-être vous assurer que les requêtes qui sont associées à un ID de session particulier se connectent au processus qui les a originés. C'est connu sous le nom _affinity_, ou _sticky sessions_, et peut être adressé par la suggestion ci-dessus d'utiliser un stockage de données tel que Redis pour les données de session (selon votre application). Pour une discussion, voir [Utilisation de plusieurs nœuds](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### Utiliser un proxy inversé
+### Use a reverse proxy
-Un mandataire inversé se trouve devant une application Web et effectue des opérations de support sur les requêtes, en plus de diriger les requêtes vers l'application. Il peut gérer les pages d'erreurs, la compression, la mise en cache, le service de fichiers et l'équilibrage de charge, entre autres.
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Le transfert de tâches qui ne nécessitent pas de connaissance de l'état de l'application à un mandataire inversé libère Express pour effectuer des tâches d'application spécialisées. Pour cette raison, il est recommandé d'exécuter Express derrière un proxy inverse comme [Nginx](https://www.nginx.org/) ou [HAProxy](https://www.haproxy.org/) en production.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/fr/advanced/best-practice-security.mdx b/src/content/pages/fr/advanced/best-practice-security.mdx
index 6000528976..cc3c58052e 100644
--- a/src/content/pages/fr/advanced/best-practice-security.mdx
+++ b/src/content/pages/fr/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Découvrez les meilleures pratiques de sécurité cruciales pour le
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Le terme _"production"_ désigne l'étape du cycle de vie du logiciel quand une application ou une API est généralement disponible pour ses utilisateurs finaux ou ses consommateurs. Par contre, dans l'étape _"développement"_, vous êtes toujours en train d'écrire et de tester du code, et l'application n'est pas ouverte à un accès externe. Les environnements système correspondants sont respectivement les environnements _production_ et _development_.
@@ -18,21 +19,19 @@ de sécurité [/en/resources/contributing#security-policies-and-procedures).
Les meilleures pratiques de sécurité pour les applications Express en production comprennent:
-- [Meilleures pratiques de production : Sécurité](#production-best-practices-security)
- - [Overview](#overview)
- - [Ne pas utiliser de versions obsolètes ou vulnérables d'Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Utiliser TLS](#use-tls)
- - [Ne pas faire confiance à la saisie de l'utilisateur](#do-not-trust-user-input)
- - [Empêcher les redirections ouvertes](#prevent-open-redirects)
- - [Utiliser le casque](#use-helmet)
- - [Réduire l'empreinte digitale](#reduce-fingerprinting)
- - (#use-cookies-securely)
- - [Ne pas utiliser le nom du cookie de session par défaut](#dont-use-the-default-session-cookie-name)
- - (#set-cookie-security-options)
- - [Empêcher les attaques par force brute contre l'autorisation](#prevent-brute-force-attacks-against-authorization)
- - [Assurez-vous que vos dépendances sont sécurisées](#ensure-your-dependencies-are-secure)
- - [Éviter les autres vulnérabilités connues](#avoid-other-known-vulnerabilities)
- - [Considérations supplémentaires](#additional-considerations)
+- [Ne pas utiliser de versions obsolètes ou vulnérables d'Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Utiliser TLS](#use-tls)
+- [Ne pas faire confiance à la saisie de l'utilisateur](#do-not-trust-user-input)
+ - [Empêcher les redirections ouvertes](#prevent-open-redirects)
+- [Utiliser le casque](#use-helmet)
+- [Réduire l'empreinte digitale](#reduce-fingerprinting)
+- (#use-cookies-securely)
+ - [Ne pas utiliser le nom du cookie de session par défaut](#dont-use-the-default-session-cookie-name)
+ - (#set-cookie-security-options)
+- [Empêcher les attaques par force brute contre l'autorisation](#prevent-brute-force-attacks-against-authorization)
+- [Assurez-vous que vos dépendances sont sécurisées](#ensure-your-dependencies-are-secure)
+ - [Éviter les autres vulnérabilités connues](#avoid-other-known-vulnerabilities)
+- [Considérations supplémentaires](#additional-considerations)
## Ne pas utiliser les versions obsolètes ou vulnérables de Express
@@ -44,7 +43,7 @@ Assurez-vous également que vous n'utilisez aucune des versions vulnérables Exp
Si votre application traite ou transmet des données sensibles, utilisez [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) pour sécuriser la connexion et les données. Cette technologie crypte les données avant qu'elles ne soient envoyées du client au serveur, empêchant ainsi certains hacks courants (et faciles). Bien que les requêtes Ajax et POST puissent ne pas être visiblement évidentes et semblent "cachées" dans les navigateurs, leur trafic réseau est vulnérable à [sniffing de paquets](https://en.wikipedia.org/wiki/Packet_analyzer) et aux [attaques de l'homme au milieu](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-Il se peut que vous soyez familier avec le cryptage Secure Socket Layer (SSL) . [TLS est simplement la prochaine progression de SSL](). En d'autres termes, si vous utilisiez SSL auparavant, envisagez la mise à niveau vers TLS. En général, nous recommandons à Nginx de gérer les TLS. Pour une bonne référence pour configurer TLS sur Nginx (et d'autres serveurs), voir [Configurations de serveur recommandées (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+Il se peut que vous soyez familier avec le cryptage Secure Socket Layer (SSL) . En général, nous recommandons à Nginx de gérer les TLS. En d'autres termes, si vous utilisiez SSL auparavant, envisagez la mise à niveau vers TLS. En d'autres termes, si vous utilisiez SSL auparavant, envisagez la mise à niveau vers TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
De plus, un outil pratique pour obtenir un certificat TLS gratuit est [Let's Encrypt](https://letsencrypt.org/about/), un outil gratuit, automatisé, et l'autorité de certification ouverte (CA) fournie par le [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Chaque en-tête peut être configuré ou désactivé. Pour en savoir plus à ce
Installer le casque comme n'importe quel autre module :
-```bash
-$ npm install helmet
-```
+
Ensuite, pour l'utiliser dans votre code:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Réduire la prise d'empreintes digitales
It can help to provide an extra layer of security to reduce the ability of attackers to determine
@@ -177,7 +184,7 @@ Utiliser le nom par défaut des cookies de session peut ouvrir votre application
Pour éviter ce problème, utilisez des noms génériques de cookies; par exemple en utilisant [express-session](https://www.npmjs.com/package/express-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Définir les options de sécurité des cookies
Définissez les options suivantes des cookies pour améliorer la sécurité :
@@ -200,7 +219,7 @@ Définissez les options suivantes des cookies pour améliorer la sécurité :
Voici un exemple utilisant [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Empêcher les attaques par force brute contre l'autorisation
Assurez-vous que les terminaux de connexion sont protégés pour rendre les données privées plus sécurisées.
@@ -259,7 +300,7 @@ $ snyk test
### Éviter les autres vulnérabilités connues
-Gardez un œil sur [Node Security Project](https://npmjs.com/advisories) ou [Snyk](https://snyk.io/vuln/) qui peuvent affecter Express ou d'autres modules que votre application utilise. En général, ces bases de données sont d'excellentes ressources pour la connaissance et les outils sur la sécurité des nœuds.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. En général, ces bases de données sont d'excellentes ressources pour la connaissance et les outils sur la sécurité des nœuds.
Enfin, les applications Express—comme toutes les autres applications web—peuvent être vulnérables à diverses attaques sur le Web. Familiarisez-vous avec les [vulnérabilités web connues](https://www.owasp.org/www-project-top-ten/) et prenez des précautions pour les éviter.
diff --git a/src/content/pages/fr/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/fr/advanced/healthcheck-graceful-shutdown.md
index 25736a4538..1953144c3c 100644
--- a/src/content/pages/fr/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/fr/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Examens de santé
-Un répartiteur de charge utilise des contrôles de santé pour déterminer si une instance de l'application est saine et peut accepter les demandes. Par exemple, [Kubernetes a deux examens de santé](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+Un répartiteur de charge utilise des contrôles de santé pour déterminer si une instance de l'application est saine et peut accepter les demandes. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, qui détermine quand redémarrer un conteneur.
- `readiness`, qui détermine quand un conteneur est prêt à accepter le trafic. Lorsqu'un pod n'est pas prêt, il est retiré des répartiteurs de charge du service.
diff --git a/src/content/pages/fr/advanced/security-updates.mdx b/src/content/pages/fr/advanced/security-updates.mdx
index 0fda23fcd9..64ed9b5f53 100644
--- a/src/content/pages/fr/advanced/security-updates.mdx
+++ b/src/content/pages/fr/advanced/security-updates.mdx
@@ -39,7 +39,7 @@ de sécurité [/en/resources/contributing#security-policies-and-procedures).
- 4.17.3
- La dépendance `qs` a été mise à jour pour répondre à un [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp). Cela peut affecter votre application si les API suivantes sont utilisées: `req.query`, `req.body`, `req.param`.
- 4.16.0
- - La dépendance `transférée` a été mise à jour pour répondre à un [vulnerability](https://npmjs.com/advisories/527). Cela peut affecter votre application si les API suivantes sont utilisées: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
+ - The dependency `forwarded` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-mpcf-4gmh-23w8). Cela peut affecter votre application si les API suivantes sont utilisées: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
- La dépendance `mime` a été mise à jour pour répondre à un [vulnerability](https://npmjs.com/advisories/535), mais ce problème n'a pas d'impact sur Express.
- La dépendance `send` a été mise à jour pour fournir une protection contre une vulnérabilité [Node.js 8.5.0](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Ceci n'affecte que l'exécution Express sur la version spécifique de Node.js 8.5.0.
- 4.15.5
diff --git a/src/content/pages/fr/guide/database-integration.mdx b/src/content/pages/fr/guide/database-integration.mdx
index d155581323..80cd815556 100644
--- a/src/content/pages/fr/guide/database-integration.mdx
+++ b/src/content/pages/fr/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Découvrez comment intégrer différentes bases de données avec le
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Ajouter la possibilité de connecter des bases de données à des applications Express est juste une question de charger un pilote Node.js approprié pour la base de données dans votre application. Ce document explique brièvement comment ajouter et utiliser certains des modules Node.js les plus populaires pour les systèmes de base de données dans votre application Express :
@@ -34,13 +35,11 @@ Ces pilotes de bases de données sont parmi les nombreux qui sont disponibles. P
### Installation
-```bash
-$ npm install cassandra-driver
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**Module** : [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installation
-```bash
-$ npm install couchbase
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**Module** : [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### Installation
-```bash
-$ npm install nano
-```
+
### Exemple
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**Module** : [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Installation
-```bash
-$ npm install level levelup leveldown
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**Module** : [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installation
-```bash
-$ npm install mysql
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**Module** : [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installation
-```bash
-$ npm install mongodb
-```
+
-### Exemple (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### Exemple (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-Si vous voulez un pilote de modèle objet pour MongoDB, regardez [Mongoose](https://github.com/LearnBoost/mongoose).
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**Module** : [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Installation
-```bash
-$ npm install neo4j-driver
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
-**Module** : [oracledb](https://github.com/oracle/node-oracledb)
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Installation
-REMARQUE : [Voir les conditions préalables à l'installation](https://github.com/oracle/node-oracledb#-installation).
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**Module** : [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installation
-```bash
-$ npm install pg-promise
-```
+
### Exemple
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**Module** : [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### Installation
-```bash
-$ npm install redis
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
-## Serveur SQL
+```mjs title="index.mjs"
+import redis from 'redis';
-**Module** : [tedious](https://github.com/tediousjs/tedious)
+const client = redis.createClient();
-### Installation
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
-```bash
-$ npm install tedious
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
```
+## SQL Server
+
+**Module**: [tedious](https://github.com/tediousjs/tedious)
+
+### Installation
+
+
+
### Exemple
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**Module** : [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Installation
-```bash
-$ npm install sqlite3
-```
+
### Exemple
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -463,17 +588,15 @@ db.close();
## Elasticsearch
-**Module** : [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Installation
-```bash
-$ npm install elasticsearch
-```
+
### Exemple
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/fr/guide/migrating-4.mdx b/src/content/pages/fr/guide/migrating-4.mdx
index f88de3d5a3..a8ce458f9e 100644
--- a/src/content/pages/fr/guide/migrating-4.mdx
+++ b/src/content/pages/fr/guide/migrating-4.mdx
@@ -4,40 +4,23 @@ description: Un guide pour migrer vos applications Express.js de la version 3 à
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 est un changement ininterrompu de Express 3. Cela signifie qu'une application Express 3 existante ne fonctionnera _pas_ si vous mettez à jour la version Express dans ses dépendances.
Cet article couvre :
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Changements dans Express 4
Il y a plusieurs changements significatifs dans Express 4 :
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
Voir aussi:
@@ -253,7 +236,7 @@ it, définit certains itinéraires, et le monte sur un chemin sur l'application
Par exemple, créez un fichier de routeur nommé `birds.js` dans le répertoire de l'application,
avec le contenu suivant:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -274,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Ensuite, chargez le module routeur dans l'application :
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -284,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
L'application sera maintenant en mesure de traiter les requêtes vers les chemins `/birds` et
`/birds/about`, et appellera le middleware `timeLog`
spécifique à la route.
@@ -299,10 +312,7 @@ Le tableau suivant liste d'autres changements mineurs mais importants dans Expre
| Node.js |
-
- Express 4 nécessite Node.js 0.10.x ou ultérieur et a abandonné la prise en charge de Node.js
- 0.8.x.
- |
+ Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` |
@@ -380,7 +390,7 @@ Les fichiers d'intérêt sont `app.js` et `package.json`.
Considérez une application Express v.3 avec le fichier `app.js` suivant :
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -414,6 +424,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
Le fichier `package.json` de la version 3 pourrait ressembler à
@@ -440,9 +484,7 @@ Commencez le processus de migration en installant le middleware requis pour l'ap
Express 4 et en mettant à jour Express et Pug vers leur dernière version
respective avec la commande suivante :
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Effectuez les modifications suivantes à `app.js`:
@@ -492,7 +534,7 @@ Lancer la commande `npm` ci-dessus mettra à jour `package.json` comme suit:
Then, remove invalid code, load the required middleware, and make other
changes as necessary. Le fichier `app.js` ressemblera à ceci :
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -542,6 +584,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
Sauf si vous avez besoin de travailler directement avec le module `http` (socket.io/SPDY/HTTPS), le chargement n'est pas nécessaire et l'application peut être simplement démarrée de cette façon :
@@ -577,18 +668,14 @@ le générateur d'applications Express 3 puis installer le nouveau
Si vous avez déjà le générateur d'application Express 3 installé sur votre système,
vous devez le désinstaller :
-```bash
-$ npm uninstall -g express
-```
+
Selon la façon dont vos droits de fichier et de répertoire sont configurés,
vous pourriez avoir besoin d'exécuter cette commande avec `sudo`.
Installez maintenant le nouveau générateur :
-```bash
-$ npm install -g express-generator
-```
+
Selon la façon dont vos droits de fichier et de répertoire sont configurés,
vous pourriez avoir besoin d'exécuter cette commande avec `sudo`.
@@ -629,9 +716,9 @@ Si vous regardez le script `npm start` dans le paquet. son`fichier,
vous remarquerez que la commande qui démarre l'application est`node . bin/www`, qui était `node app.js\`
dans Express 3.
-Parce que le fichier `app.js` qui a été généré par le générateur Express 4
-est maintenant un nœud. , il ne peut plus être démarré indépendamment en tant qu'application
-(sauf si vous modifiez le code). Le module doit être chargé dans un fichier Node.js
+Because the `app.js` file that was generated by the Express 4 generator
+is now a Node.js module, it can no longer be started independently as an app
+(unless you modify the code). Le module doit être chargé dans un fichier Node.js
et démarré via le fichier Node.js. Le fichier Node.js est `./bin/www`
dans ce cas.
diff --git a/src/content/pages/fr/guide/migrating-5.mdx b/src/content/pages/fr/guide/migrating-5.mdx
index 955fd4fe10..6e7e1d16ba 100644
--- a/src/content/pages/fr/guide/migrating-5.mdx
+++ b/src/content/pages/fr/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: Un guide complet pour migrer vos applications Express.js de la vers
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
L'Express 5 n'est pas très différent de l'Express 4 ; bien qu'il maintienne la même API de base, il y a toujours des changements qui cèdent la compatibilité avec la version précédente. Par conséquent, une application construite avec Express 4 pourrait ne pas fonctionner si vous la mettez à jour pour utiliser Express 5.
@@ -11,9 +12,7 @@ L'Express 5 n'est pas très différent de l'Express 4 ; bien qu'il maintienne la
Pour installer cette version, vous devez avoir une **version 18 ou supérieure de Node.js**. Ensuite, exécutez la commande suivante dans le répertoire de votre application :
-```sh
-npm install "express@5"
-```
+
Vous pouvez ensuite exécuter vos tests automatisés pour voir ce qui échoue, et corriger les problèmes en fonction des mises à jour listées ci-dessous. Après avoir résolu des échecs de test, exécutez votre application pour voir quelles erreurs se produisent. Vous découvrirez immédiatement si l'application utilise des méthodes ou des propriétés qui ne sont pas prises en charge.
@@ -23,15 +22,11 @@ Pour vous aider à migrer votre serveur express nous avons créé un ensemble de
Exécutez la commande suivante pour exécuter tous les codemods disponibles :
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
Si vous voulez exécuter un code spécifique, vous pouvez exécuter la commande suivante :
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
Vous pouvez trouver la liste des codes disponibles [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Initialement, `del` a été utilisé à la place de `delete`, parce que `delete`
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -80,9 +73,7 @@ Les noms de méthodes suivantes ont été pluralisés. Dans Express 4, l'utilisa
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -103,7 +94,7 @@ Ou vous pouvez mettre à jour votre code manuellement :
Un caractère de deux points (:) dans le nom de l'application`. aram(name, fn)` est un reste d'Express 3, et pour des raisons de compatibilité ascendante, Express 4 l'a supporté avec une notification de dépréciation. Express 5 l'ignorera silencieusement et utilisera le paramètre de nom sans le préfixer avec un deux-points.
-Cela ne devrait pas affecter votre code si vous suivez la documentation Express 4 de [app.param](/4x/api#app.param), car il ne fait aucune mention du côlon principal.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### param(nom)
@@ -113,9 +104,7 @@ Cette méthode potentiellement confuse et dangereuse de récupération des donn
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -140,9 +129,7 @@ Express 5 ne prend plus en charge la signature `res.json(obj, status)`. Au lieu
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -161,9 +148,7 @@ Express 5 ne prend plus en charge la signature `res.jsonp(obj, status)`. Au lieu
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -182,16 +167,19 @@ Express 5 ne prend plus en charge la signature `res.redirect(url, status)`. À l
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 ne supporte plus la chaîne magique `back` dans les méthodes `res.red
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -224,9 +210,7 @@ Express 5 ne prend plus en charge la signature `res.send(obj, status)`. Au lieu
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -246,9 +230,7 @@ Si vous avez besoin d'envoyer un numéro en utilisant les `res. la fonction end(
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -267,9 +249,7 @@ La fonction `res.sendfile()` a été remplacée par une version à chameau `res.
Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Ou vous pouvez mettre à jour votre code manuellement :
@@ -284,6 +264,10 @@ Ou vous pouvez mettre à jour votre code manuellement :
Les options `hidden` et `from` pour `res.sendFile()` ne sont plus supportées. Utilisez `dotfiles` et `root` à la place.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### Comment mettre à jour
```diff
@@ -293,12 +277,30 @@ Les options `hidden` et `from` pour `res.sendFile()` ne sont plus supportées. U
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### options express.static()
Les options `hidden` et `from` pour `express.static()` ne sont plus supportées. Utilisez `dotfiles` et `root` à la place. Notez que `from` n'a jamais été documenté dans l'API mais a été accepté comme un alias pour `root`. La valeur par défaut de `dotfiles` est maintenant `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### Comment mettre à jour
+Vous pouvez automatiquement mettre à jour votre code en exécutant la commande suivante :
+
+
+
+Ou vous pouvez mettre à jour votre code manuellement :
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ Les options `hidden` et `from` pour `express.static()` ne sont plus supportées.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
La signature `router.param(fn)` a été utilisée pour modifier le comportement de la fonction `router.param(name, fn)`. Il est obsolète depuis la version 4.11.0, et Express 5 ne le supporte plus du tout.
@@ -449,6 +458,25 @@ Servez explicitement des répertoires de points spécifiques en utilisant l'opti
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### Comment mettre à jour
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### Écouter
Dans Express 5, la méthode `app.listen` invoquera la fonction de rappel fournie par l'utilisateur (si fournie) lorsque le serveur reçoit un événement d'erreur. Dans Express 4, de telles erreurs seraient lancées. Ce changement déplace la responsabilité de gestion des erreurs vers la fonction callback dans Express 5. S'il y a une erreur, elle sera passée au callback en tant qu'argument.
diff --git a/src/content/pages/fr/resources/community.mdx b/src/content/pages/fr/resources/community.mdx
index ea91595d5c..fb20584bed 100644
--- a/src/content/pages/fr/resources/community.mdx
+++ b/src/content/pages/fr/resources/community.mdx
@@ -68,16 +68,16 @@ Express est un projet de la Fondation OpenJS. Veuillez consulter la [politique d
### Mot de passe
### Glyphe
@@ -86,7 +86,7 @@ Express est un projet de la Fondation OpenJS. Veuillez consulter la [politique d
Ce logo a été créé par [SAWARATSUKI](https://github.com/SAWARATSUKI).
diff --git a/src/content/pages/fr/resources/glossary.mdx b/src/content/pages/fr/resources/glossary.mdx
index 18e1653ce7..c71688d73a 100644
--- a/src/content/pages/fr/resources/glossary.mdx
+++ b/src/content/pages/fr/resources/glossary.mdx
@@ -27,7 +27,7 @@ Une fonction qui est appelée par la couche de routage Express avant le gestionn
- `var foo = require('middleware')` est appelé _requiring_ ou _using_ un module Node.js. Puis l'instruction `var mw = foo()` retourne typiquement le middleware.
- `app.use(mw)` est appelé _adding the middleware to the global processing stack_.
-- `app.get('/foo', mw, function (req, res) { ... })` est appelé \_ajoutant le middleware à la pile de traitement "GET /foo".
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/fr/resources/index.mdx b/src/content/pages/fr/resources/index.mdx
index eda9cbb4a6..cb218b83f2 100644
--- a/src/content/pages/fr/resources/index.mdx
+++ b/src/content/pages/fr/resources/index.mdx
@@ -23,7 +23,7 @@ Trouvez des ressources pour vous aider à apprendre, à contribuer et à vous co
diff --git a/src/content/pages/fr/resources/middleware/body-parser.mdx b/src/content/pages/fr/resources/middleware/body-parser.mdx
index 04521b8b03..c7f32bdb9a 100644
--- a/src/content/pages/fr/resources/middleware/body-parser.mdx
+++ b/src/content/pages/fr/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Analyse corporelle du middleware de Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Autres analyseurs de corps qui pourraient vous intéresser:
## Installation
-```sh
-$ npm install body-parser
-```
+
## API
@@ -111,8 +110,8 @@ est `'100kb'`.
##### reviver
L'option `reviver` est passée directement à `JSON.parse` en tant que deuxième argument
-. Vous pouvez trouver plus d'informations sur cet argument
-[dans la documentation MDN sur JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strict
diff --git a/src/content/pages/fr/resources/middleware/compression.mdx b/src/content/pages/fr/resources/middleware/compression.mdx
index 2f8216beb0..a0dd21ab2a 100644
--- a/src/content/pages/fr/resources/middleware/compression.mdx
+++ b/src/content/pages/fr/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: middleware de compression Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
@@ -297,7 +296,7 @@ Le projet Express.js salue toutes les contributions constructives. Les contribut
du code pour les corrections de bugs et les améliorations, aux ajouts et corrections à la documentation, tests
supplémentaires, triant les demandes de fusion entrantes et les problèmes, et plus encore !
-Voir le [Guide de contribution](https://github.com/expressjs/express/blob/master/Contributing.md) pour plus de détails techniques sur la contribution.
+Voir le [Guide de contribution] (https://github.com/expressjs/express/blob/master/Contributing.md) pour plus de détails techniques sur la contribution.
## Licence
diff --git a/src/content/pages/fr/resources/middleware/cookie-parser.mdx b/src/content/pages/fr/resources/middleware/cookie-parser.mdx
index f3b6197743..627dc5bb14 100644
--- a/src/content/pages/fr/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/fr/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Analyser les cookies de requête HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/cookie-session.mdx b/src/content/pages/fr/resources/middleware/cookie-session.mdx
index 8d5c77adad..a5cb4775e6 100644
--- a/src/content/pages/fr/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/fr/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie session middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/cors.mdx b/src/content/pages/fr/resources/middleware/cors.mdx
index 342da2175a..197fa3ee6c 100644
--- a/src/content/pages/fr/resources/middleware/cors.mdx
+++ b/src/content/pages/fr/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS est un [Node.js](https://nodejs.org/en/) middleware pour [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) qui définit [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) en-têtes de réponse. Ces en-têtes indiquent aux navigateurs quelles origines peuvent lire les réponses de votre serveur.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. Ces en-têtes indiquent aux navigateurs quelles origines peuvent lire les réponses de votre serveur.
@@ -39,9 +40,7 @@ Ceci est un module [Node.js](https://nodejs.org/en/) disponible via
[npm registry](https://www.npmjs.com/). L'installation se fait à l'aide de la commande
[`npm install`](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Usage
diff --git a/src/content/pages/fr/resources/middleware/errorhandler.mdx b/src/content/pages/fr/resources/middleware/errorhandler.mdx
index 8ff80de7be..48d6e11175 100644
--- a/src/content/pages/fr/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/fr/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Gestionnaire d'erreurs uniquement pour le développement du middlew
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/index.mdx b/src/content/pages/fr/resources/middleware/index.mdx
new file mode 100644
index 0000000000..b0ffd77ce9
--- /dev/null
+++ b/src/content/pages/fr/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Libellé |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ Cette information se réfère à des sites tiers, des produits ou des modules tiers qui ne sont pas
+ maintenus par l'équipe Expressjs. La liste ci-dessous ne constitue pas une approbation ou une
+ recommandation de l'équipe du projet Expressjs.
+
+
+| Middleware module | Libellé |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/fr/resources/middleware/method-override.mdx b/src/content/pages/fr/resources/middleware/method-override.mdx
index 411949ae6f..8995b82a0e 100644
--- a/src/content/pages/fr/resources/middleware/method-override.mdx
+++ b/src/content/pages/fr/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Remplacer les verbes HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/morgan.mdx b/src/content/pages/fr/resources/middleware/morgan.mdx
index 85a84e0922..193f5f18e0 100644
--- a/src/content/pages/fr/resources/middleware/morgan.mdx
+++ b/src/content/pages/fr/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: Le middleware de l'enregistreur de requêtes HTTP pour Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ Ceci est un module [Node.js](https://nodejs.org/en/) disponible via
[npm registry](https://www.npmjs.com/). L'installation se fait à l'aide de la commande
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ Si aucun format n'est donné, alors la valeur par défaut est `web`.
La version HTTP de la requête.
-##### :method
+#####
La méthode HTTP de la requête.
-##### :pid
+#####
L'ID de processus du processus Node.js gérant la requête.
-##### :referrer
+#####
L'en-tête Référent de la requête. Cela utilisera l'en-tête standard de Referer mal orthographié s'il existe, sinon Referrer.
@@ -239,7 +238,7 @@ sont écrits, en millisecondes.
L'argument `digits` est un nombre qui spécifie le nombre de chiffres à
inclus sur le nombre, par défaut à `3`, qui fournit une précision de microseconde.
-##### :status
+#####
Le code de statut de la réponse.
@@ -255,7 +254,7 @@ a fini d'être écrite à la connexion, en millisecondes.
L'argument `digits` est un nombre qui spécifie le nombre de chiffres à
inclus sur le nombre, par défaut à `3`, qui fournit une précision de microseconde.
-##### :url
+#####
L'URL de la requête. Cela utilisera `req.originalUrl` si existe, sinon `req.url`.
diff --git a/src/content/pages/fr/resources/middleware/multer.mdx b/src/content/pages/fr/resources/middleware/multer.mdx
index 0e9d78ece1..6f6eecf409 100644
--- a/src/content/pages/fr/resources/middleware/multer.mdx
+++ b/src/content/pages/fr/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware pour gérer les multi-pièces/form-données
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ Ce README est également disponible dans d'autres langues :
## Installation
-```sh
-$ npm install multer
-```
+
## Usage
@@ -284,15 +283,16 @@ Un objet spécifiant les limites de taille des propriétés optionnelles suivant
Les valeurs entières suivantes sont disponibles :
-| Clés | Libellé | Par défaut |
-| --------------- | ------------------------------------------------------------------------------------- | ---------- |
-| `fieldNameSize` | Taille maximale du nom du champ | 100 octets |
-| `fieldSize` | Taille maximale du champ (en octets) | 1 Mo |
-| `champs` | Nombre maximum de champs hors fichier | Infini |
-| `fileSize` | Pour les formes multiparties, la taille maximale du fichier (en octets) | Infini |
-| `fichiers` | Pour les formulaires en plusieurs parties, le nombre maximum de champs de fichier | Infini |
-| `Parties` | Pour les formes multiparties, le nombre maximum de parties (champs + fichiers) | Infini |
-| `headerPairs` | Pour les formes multiparties, le nombre maximum de clés d'en-tête =>valeur à analyser | 2000 |
+| Clés | Libellé | Par défaut |
+| ------------------- | ------------------------------------------------------------------------------------- | ---------- |
+| `fieldNameSize` | Taille maximale du nom du champ | 100 octets |
+| `fieldSize` | Taille maximale du champ (en octets) | 1 Mo |
+| `champs` | Nombre maximum de champs hors fichier | Infini |
+| `fileSize` | Pour les formes multiparties, la taille maximale du fichier (en octets) | Infini |
+| `fichiers` | Pour les formulaires en plusieurs parties, le nombre maximum de champs de fichier | Infini |
+| `Parties` | Pour les formes multiparties, le nombre maximum de parties (champs + fichiers) | Infini |
+| `headerPairs` | Pour les formes multiparties, le nombre maximum de clés d'en-tête =>valeur à analyser | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infini |
Spécifier les limites peut aider à protéger votre site contre les attaques par déni de service (DoS).
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Gestion des erreurs
En cas d'erreur, Multer délègue l'erreur à Express. Vous pouvez
diff --git a/src/content/pages/fr/resources/middleware/response-time.mdx b/src/content/pages/fr/resources/middleware/response-time.mdx
index e0a98e0514..b2e183a6ce 100644
--- a/src/content/pages/fr/resources/middleware/response-time.mdx
+++ b/src/content/pages/fr/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Temps de réponse pour les serveurs Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/serve-favicon.mdx b/src/content/pages/fr/resources/middleware/serve-favicon.mdx
index e0dc198dcf..b0904066a1 100644
--- a/src/content/pages/fr/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/fr/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon servant les middleware avec la mise en cache
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/serve-index.mdx b/src/content/pages/fr/resources/middleware/serve-index.mdx
index 2e43b98a62..ad6cec7fae 100644
--- a/src/content/pages/fr/resources/middleware/serve-index.mdx
+++ b/src/content/pages/fr/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Servir les listes d'annuaires
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/serve-static.mdx b/src/content/pages/fr/resources/middleware/serve-static.mdx
index dbbf30f1b0..9c80de3b10 100644
--- a/src/content/pages/fr/resources/middleware/serve-static.mdx
+++ b/src/content/pages/fr/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Servir les fichiers statiques
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/resources/middleware/session.mdx b/src/content/pages/fr/resources/middleware/session.mdx
index 49d183661c..acd2784d4e 100644
--- a/src/content/pages/fr/resources/middleware/session.mdx
+++ b/src/content/pages/fr/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Schéma de session simple pour Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Installation
@@ -18,9 +19,7 @@ Ceci est un module [Node.js](https://nodejs.org/en/) disponible via
[npm registry](https://www.npmjs.com/). L'installation se fait à l'aide de la commande
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -146,7 +145,8 @@ Spécifie la `string` pour être la valeur de l'attribut [`Priority` `Set-Cookie
Plus d'informations sur les différents niveaux de priorité peuvent être trouvées dans
[la spécification][rfc-west-cookie-priority-00-4.1].
-**Note** Ceci est un attribut qui n'a pas encore été entièrement normalisé, et peut changer à l'avenir.
+**Note** Ceci est un attribut qui n'a pas encore été entièrement normalisé, et peut changer dans
+le futur.
Cela signifie également que de nombreux clients peuvent ignorer cet attribut jusqu'à ce qu'ils le comprennent.
##### Site web du même type
@@ -164,8 +164,7 @@ Par défaut, c'est `false`.
Plus d'informations sur les différents niveaux d'application peuvent être trouvées dans
[la spécification][rfc-6265bis-03-4.1.2.7].
-**Note** Ceci est un attribut qui n'a pas encore été entièrement normalisé, et peut changer dans
-le futur. Cela signifie également que de nombreux clients peuvent ignorer cet attribut jusqu'à ce qu'ils le comprennent.
+**Note** Ceci est un attribut qui n'a pas encore été entièrement normalisé, et peut changer à l'avenir. Cela signifie également que de nombreux clients peuvent ignorer cet attribut jusqu'à ce qu'ils le comprennent.
**Note** Il y a un [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
qui requiert que l'attribut `Secure` soit défini à `true` lorsque l'attribut `SameSite` a été
diff --git a/src/content/pages/fr/resources/middleware/timeout.mdx b/src/content/pages/fr/resources/middleware/timeout.mdx
index 2c8c59d5bf..97bc929ecf 100644
--- a/src/content/pages/fr/resources/middleware/timeout.mdx
+++ b/src/content/pages/fr/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Expiration de la requête du middleware pour connexion/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Délai d'une demande dans le cadre de l'application Connect/Express.
@@ -20,9 +21,7 @@ Ceci est un module [Node.js](https://nodejs.org/en/) disponible via
[npm registry](https://www.npmjs.com/). L'installation se fait à l'aide de la commande
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/fr/resources/middleware/vhost.mdx b/src/content/pages/fr/resources/middleware/vhost.mdx
index f45d33ef79..956a7af2a7 100644
--- a/src/content/pages/fr/resources/middleware/vhost.mdx
+++ b/src/content/pages/fr/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Hébergement de domaine virtuel
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/fr/support.md b/src/content/pages/fr/support.md
index 38a184145f..881bffdf4d 100644
--- a/src/content/pages/fr/support.md
+++ b/src/content/pages/fr/support.md
@@ -7,14 +7,14 @@ Seule la dernière version d'une ligne de publication majeure est prise en charg
Les versions qui sont EdlV (fin de vie) _peuvent_ recevoir des mises à jour pour les vulnérabilités critiques de sécurité, mais l'équipe Express n'offre aucune garantie et ne prévoit pas de résoudre ou de corriger les problèmes rencontrés.
-| Version majeure | Version minimale de Node.js | Date de début du support | Date de fin du support |
-| ------------------- | --------------------------- | ------------------------ | ---------------------- |
-| [**v5.x**](/5x/api) | 18 | Septembre 2024 | **en cours** |
-| [**v4.x**](/4x/api) | 0.10.0 | Avril 2014 | **en cours** |
-| [**v3.x**](/3x/api) | 0.8.0 | Octobre 2012 | Juillet 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | Mars 2011 | Juillet 2012 |
-| **v1.x** | 0.2.0 | Décembre 2010 | Mars 2011 |
-| **v0.14.x** | 0.1.98 | Décembre 2010 | Décembre 2010 |
+| Version majeure | Version minimale de Node.js | Date de début du support | Date de fin du support |
+| -------------------------------------------------------------- | --------------------------- | ------------------------ | ---------------------- |
+| [**v5.x**](/5x/api) | 18 | Septembre 2024 | **en cours** |
+| [**v4.x**](/4x/api) | 0.10.0 | Avril 2014 | **en cours** |
+| [**v3.x**](/3x/api) | 0.8.0 | Octobre 2012 | Juillet 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | Mars 2011 | Juillet 2012 |
+| **v1.x** | 0.2.0 | Décembre 2010 | Mars 2011 |
+| **v0.14.x** | 0.1.98 | Décembre 2010 | Décembre 2010 |
## Options de support commercial
diff --git a/src/content/pages/it/advanced/best-practice-performance.md b/src/content/pages/it/advanced/best-practice-performance.md
index eff2e8a75b..f880a6c053 100644
--- a/src/content/pages/it/advanced/best-practice-performance.md
+++ b/src/content/pages/it/advanced/best-practice-performance.md
@@ -33,7 +33,7 @@ Ecco alcune cose che puoi fare nel tuo codice per migliorare le prestazioni dell
La compressione di Gzip può ridurre notevolmente la dimensione del corpo della risposta e quindi aumentare la velocità di una web app. Usa il middleware [compression](https://www.npmjs.com/package/compression) per la compressione gzip nella tua app Express. Per esempio:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-Per un sito web ad alto traffico in produzione, il modo migliore per mettere in atto la compressione è implementarla a un livello di proxy inverso (vedere [Usa un proxy inverso](#use-a-reverse-proxy)). In tal caso, non è necessario utilizzare middleware di compressione. Per maggiori dettagli sull'attivazione della compressione gzip in Nginx, vedere [Modulo ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) nella documentazione Nginx.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### Non utilizzare funzioni sincrone
+### Don't use synchronous functions
-Le funzioni e i metodi sincroni legano il processo di esecuzione fino al loro ritorno. Una singola chiamata ad una funzione sincrona potrebbe tornare in pochi microsecondi o millisecondi, tuttavia nei siti web ad alto traffico, queste chiamate si sommano e riducono le prestazioni dell'app. Evitare il loro uso in produzione.
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Sebbene Node e molti moduli forniscano versioni sincrone e asincrone delle loro funzioni, utilizzare sempre la versione asincrona in produzione. L'unico momento in cui una funzione sincrona può essere giustificata è all'avvio iniziale.
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-Puoi usare il flag da riga di comando `--trace-sync-io` per stampare un avviso e uno stack trace ogni volta che la tua applicazione utilizza un'API sincrona. Naturalmente, non si desidera utilizzare questo in produzione, ma piuttosto per garantire che il codice è pronto per la produzione. Vedi la [documentazione delle opzioni a riga di comando del nodo](https://nodejs.org/api/cli.html#trace-sync-io) per maggiori informazioni.
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Effettuare la registrazione correttamente
+### Do logging correctly
-In generale, ci sono due motivi per la registrazione dalla tua app: Per il debug e per la registrazione delle attività delle app (essenzialmente, tutto il resto). Usare `console.log()` o `console.error()` per stampare i messaggi di log sul terminale è una pratica comune nello sviluppo. Ma [queste funzioni sono sincrone](https://nodejs.org/api/console.html#console) quando la destinazione è un terminale o un file, in modo che non siano adatti per la produzione, a meno che non convogliate l'uscita ad un altro programma.
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### Per il debug
+#### For debugging
-Se stai registrando a fini di debug, invece di usare `console.log()`, usa uno speciale modulo di debug come [debug](https://www.npmjs.com/package/debug). Questo modulo consente di utilizzare la variabile di ambiente DEBUG per controllare quali messaggi di debug vengono inviati a `console.error()`, se presenti. Per mantenere la tua app puramente asincrona, dovresti ancora reindirizzare `console.error()` ad un altro programma. Ma allora, non stai davvero andando a debug nella produzione, vero?
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### Per attività app
+#### For app activity
-Se stai registrando le attività delle app (ad esempio, tracciando traffico o chiamate API), invece di usare `console. og()`, usa una libreria di registrazione come [Pino](https://www.npmjs.com/package/pino), che è l'opzione più veloce ed efficiente disponibile.
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### Gestisci correttamente le eccezioni
+### Handle exceptions properly
-Le app del nodo si bloccano quando incontrano un'eccezione non catturata. Non gestire le eccezioni e intraprendere azioni appropriate renderà il tuo crash di app Express e andare offline. Se segui i consigli in [Assicurati che la tua app riavvii automaticamente](#ensure-your-app-automatically-restarts) qui sotto, allora la tua app recupererà da un crash. Fortunatamente, le applicazioni Express in genere hanno un breve tempo di avvio. Tuttavia, si desidera evitare di schiantarsi in primo luogo, e per farlo, è necessario gestire le eccezioni correttamente.
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-Per garantire la gestione di tutte le eccezioni, utilizzare le seguenti tecniche:
+To ensure you handle all exceptions, use the following techniques:
-- [Usa try-catch](#use-try-catch)
-- [Usa promesse](#use-promises)
+- [Use try-catch](#use-try-catch)
+- [Use promises](#use-promises)
-Prima di immergersi in questi argomenti, si dovrebbe avere una comprensione di base della gestione degli errori Node/Express: utilizzando error-first callback e gli errori di propagazione in middleware. Il nodo utilizza una convenzione "error-first callback" per restituire gli errori dalle funzioni asincrone, dove il primo parametro della funzione callback è l'oggetto errore, seguito da dati di risultato in parametri successivi. Per indicare nessun errore, passare null come primo parametro. La funzione di callback deve seguire in modo corrispondente la convenzione di callback errore-first callback per gestire in modo significativo l'errore. E in Express, la migliore pratica è quella di utilizzare la funzione next() per propagare gli errori attraverso la catena middleware.
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-Per maggiori informazioni sui fondamenti della gestione degli errori, consultare:
+For more on the fundamentals of error handling, see:
-- [Gestione degli errori in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Usa try-catch
+#### Use try-catch
-Try-catch è una struttura in linguaggio JavaScript che puoi usare per catturare le eccezioni in codice sincrono. Usa try-catch, per esempio, per gestire gli errori di analisi JSON come mostrato di seguito.
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-Ecco un esempio di utilizzo di try-catch per gestire una potenziale eccezione di processo-crashing.
-Questa funzione middleware accetta un parametro del campo di query denominato "params" che è un oggetto JSON.
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-Tuttavia, try-catch funziona solo per il codice sincrono. Poiché la piattaforma Nodo è principalmente asincrona (in particolare in un ambiente di produzione), il try-catch non prenderà molte eccezioni.
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Usa promesse
+#### Use promises
-Quando un errore viene lanciato in una funzione `async` o una promessa rifiutata è attesa all'interno di una funzione `async`, questi errori verranno passati al gestore degli errori come se chiamasse `next(err)`
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-Inoltre, è possibile utilizzare funzioni asincrone per il vostro middleware, e il router gestirà gli errori se la promessa fallisce, per esempio:
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-La migliore pratica è quella di gestire gli errori il più vicino possibile al sito. Quindi, mentre questo è ora gestito nel router, è meglio catturare l'errore nel middleware e gestirlo senza fare affidamento su middleware di gestione degli errori separati.
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### Cosa non fare
+#### What not to do
-Una cosa che dovresti _non_ fare è ascoltare per l'evento `uncaughtException`, emessa quando una bolla di eccezione ritorna fino al ciclo evento. L'aggiunta di un ascoltatore di eventi per `uncaughtException` cambierà il comportamento predefinito del processo che sta incontrando un'eccezione; il processo continuerà a funzionare nonostante l'eccezione. Questo potrebbe sembrare un buon modo per impedire che la tua app si blocchi, ma continuare ad eseguire l'app dopo un'eccezione non catturata è una pratica pericolosa e non è raccomandato, perché lo stato del processo diventa inaffidabile e imprevedibile.
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-Inoltre, l'utilizzo di `uncaughtException` è ufficialmente riconosciuto come [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Quindi ascoltare `uncaughtException` è solo una cattiva idea. Questo è il motivo per cui consigliamo cose come più processi e supervisori: crash e riavvio è spesso il modo più affidabile per recuperare da un errore.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-Inoltre non consigliamo di utilizzare [domains](https://nodejs.org/api/domain.html). Generalmente non risolve il problema ed è un modulo deprecato.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## Cose da fare nel tuo ambiente / configurazione
+## Things to do in your environment / setup
-Ecco alcune cose che puoi fare nel tuo ambiente di sistema per migliorare le prestazioni della tua app:
+Here are some things you can do in your system environment to improve your app's performance:
- [Imposta NODE_ENV a "production"](#set-node_env-to-production)
- [Assicurati che l'app si riavvii automaticamente](#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Ecco alcune cose che puoi fare nel tuo ambiente di sistema per migliorare le pre
- [Usa un balancer](#use-a-load-balancer)
- [Usa un proxy inverso](#use-a-reverse-proxy)
-### Imposta NODE_ENV a "produzione"
+### Set NODE_ENV to "production"
-La variabile d' ambiente NODE_ENV specifica l' ambiente in cui un' applicazione è in esecuzione (solitamente, sviluppo o produzione). Una delle cose più semplici che puoi fare per migliorare le prestazioni è impostare NODE_ENV a `produzione`.
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-Impostando NODE_ENV a "production" makes Express:
+Setting NODE_ENV to "production" makes Express:
-- Modelli visualizzazione della cache.
-- File CSS della cache generati dalle estensioni CSS.
-- Genera messaggi di errore meno dettagliati.
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-[Tests indicate](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) che solo facendo questo può migliorare le prestazioni dell'app di un fattore di tre!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-Se è necessario scrivere un codice specifico per l'ambiente, è possibile controllare il valore di NODE_ENV con `process.env.NODE_ENV`. Essere consapevoli che il controllo del valore di qualsiasi variabile ambientale comporta una penalità di prestazione, e quindi dovrebbe essere fatto con parsimonia.
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-In fase di sviluppo, in genere imposterai le variabili di ambiente nella tua shell interattiva, ad esempio usando `export` o il tuo file `.bash_profile`. Ma in generale, non dovresti farlo su un server di produzione; invece, usa il sistema di ingresso del tuo sistema operativo (systemd). La sezione successiva fornisce maggiori dettagli sull'utilizzo del sistema di init in generale, ma l'impostazione `NODE_ENV` è così importante per le prestazioni (e facile da fare), che è evidenziata qui.
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-Con il sistema, usa la direttiva `Environment` nel tuo file unitario. Per esempio:
+With systemd, use the `Environment` directive in your unit file. Per esempio:
```sh
Environment=NODE_ENV=production
```
-Per ulteriori informazioni, vedere [Uso delle variabili ambientali nelle unità systemd](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### Assicurati che l'app si riavvii automaticamente
+### Ensure your app automatically restarts
-In produzione, non vuoi che la tua applicazione sia offline, mai. Ciò significa che è necessario assicurarsi che si riavvia sia se l'applicazione si blocca e se il server stesso si blocca. Anche se si spera che nessuno di questi eventi accada, realisticamente si deve rendere conto di entrambe le eventualità mediante:
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- Utilizzando un gestore di processo per riavviare l'applicazione (e Node) quando si blocca.
-- Utilizzando il sistema di init fornito dal sistema operativo per riavviare il gestore di processo quando il sistema operativo si blocca. È anche possibile utilizzare il sistema init senza un gestore di processo.
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-Le applicazioni del nodo si bloccano se incontrano un'eccezione non catturata. La cosa più importante che devi fare è assicurarsi che la tua app sia ben testata e gestisca tutte le eccezioni (vedi [gestire le eccezioni correttamente](#handle-exceptions-properly) per i dettagli). Ma come un fail-safe, mettere un meccanismo in atto per garantire che se e quando l'app si blocca, si riavvierà automaticamente.
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### Usa un gestore di processo
+#### Use a process manager
-In fase di sviluppo, hai avviato la tua app semplicemente dalla riga di comando con `node server.js` o qualcosa di simile. Ma fare questo in produzione è una ricetta per il disastro. Se l'app si blocca, sarà offline fino al riavvio. Per garantire il riavvio dell'app in caso di crash usa un gestore di processo. Un process-manager è un "container" per le applicazioni che facilita l'implementazione, fornisce un'elevata disponibilità e consente di gestire l'applicazione durante il runtime.
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-Oltre a riavviare la tua app quando si blocca, un gestore di processo può permetterti di:
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- Ottieni informazioni sulle prestazioni di runtime e sul consumo di risorse.
-- Modifica le impostazioni dinamicamente per migliorare le prestazioni.
-- Clustering di controllo (pm2).
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-Storicamente, era popolare usare un manager di processo Node.js come [PM2](https://github.com/Unitech/pm2). Vedere la loro documentazione se si desidera farlo. Tuttavia, si consiglia di utilizzare il sistema init per la gestione dei processi.
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### Usa un sistema init
+#### Use an init system
-Il livello successivo di affidabilità è quello di garantire che l'app si riavvia quando il server si riavvia. I sistemi possono ancora andare giù per una varietà di motivi. Per garantire che la tua app si riavvii in caso di crash del server, usa il sistema init integrato nel tuo sistema operativo. Il sistema di init principale oggi in uso è [systemd](https://wiki.debian.org/systemd).
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Ci sono due modi per utilizzare i sistemi init con la tua app Express:
+There are two ways to use init systems with your Express app:
-- Eseguire l'app in un gestore di processo e installare il gestore di processo come un servizio con il sistema init. Il gestore di processo riavvierà l'app quando l'app si blocca e il sistema init riavvierà il gestore di processo quando il sistema operativo riavvia. Questo è l'approccio raccomandato.
-- Esegui la tua app (e Node) direttamente con il sistema init. Questo è un po 'più semplice, ma non si ottengono i vantaggi aggiuntivi di utilizzare un manager di processo.
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-Systemd è un sistema Linux e service manager. La maggior parte delle principali distribuzioni Linux hanno adottato systemd come sistema di init predefinito.
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-Un file di configurazione del servizio di sistema è chiamato _unit file_, con un nome di file che termina in `.service`. Ecco un file unità di esempio per gestire direttamente un'app Node. Sostituisci i valori racchiusi in `` per il tuo sistema e l'app:
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-Per ulteriori informazioni sul sistema, vedere [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Esegui la tua app in un cluster
+### Run your app in a cluster
-In un sistema multi-core, è possibile aumentare le prestazioni di un'applicazione Nodo di molte volte lanciando un cluster di processi. Un cluster esegue più istanze dell'app, idealmente una istanza su ogni nucleo della CPU, distribuendo così il carico e le attività tra le istanze.
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
-
+
-IMPORTANTE: Poiché le istanze dell'app vengono eseguite come processi separati, non condividono lo stesso spazio di memoria. Cioè, gli oggetti sono locali per ogni istanza dell'app. Pertanto, non è possibile mantenere lo stato nel codice dell'applicazione. Tuttavia, è possibile utilizzare un datastore in memoria come [Redis](http://redis.io/) per memorizzare i dati e lo stato relativi alla sessione. Questa avvertenza si applica essenzialmente a tutte le forme di ridimensionamento orizzontale, sia che si tratti di raggruppamento con più processi o più server fisici.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-Nelle applicazioni raggruppate, i processi di lavoro possono bloccarsi individualmente senza influenzare il resto dei processi. Oltre ai vantaggi delle prestazioni, l'isolamento del guasto è un altro motivo per eseguire un cluster di processi app. Ogni volta che un processo di lavoro si blocca, assicurarsi sempre di registrare l'evento e generare un nuovo processo utilizzando cluster.fork().
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### Uso del modulo cluster Node
+#### Using Node's cluster module
-Il cluster è reso possibile con il [modulo cluster di Node](https://nodejs.org/api/cluster.html). Ciò consente a un processo master di generare processi di lavoro e distribuire le connessioni in entrata tra i lavoratori.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### Uso PM2
+#### Using PM2
-Se distribuisci la tua applicazione con PM2, puoi approfittare del clustering _without_ modificando il codice dell'applicazione. Dovresti prima assicurarti che la tua [applicazione sia senza condizione](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) il che significa che nessun dato locale viene memorizzato nel processo (ad esempio sessioni, connessioni websocket e simili).
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-Quando si esegue un'applicazione con PM2, è possibile abilitare la modalità **cluster** per eseguirla in un cluster con un certo numero di istanze a propria scelta, come il corrispondente numero di CPU disponibili sulla macchina. È possibile modificare manualmente il numero di processi nel cluster utilizzando lo strumento da riga di comando `pm2` senza interrompere l'app.
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-Per abilitare la modalità cluster, avvia la tua applicazione così:
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-Questo può anche essere configurato all'interno di un file di processo PM2 (`ecosystem.config. s` o simile) impostando `exec_mode` su `cluster` e `instances` sul numero di lavoratori da avviare.
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-Una volta in esecuzione, l'applicazione può essere ridimensionata così:
+Once running, the application can be scaled like so:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-Per ulteriori informazioni sul clustering con PM2, vedere [Modalità cluster](https://pm2.keymetrics.io/docs/usage/cluster-mode/) nella documentazione PM2.
+For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### Risultati richiesta cache
+### Cache request results
-Un'altra strategia per migliorare le prestazioni nella produzione è quella di nascondere il risultato delle richieste, in modo che l'app non ripeta l'operazione per servire la stessa richiesta ripetutamente.
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Usa un server di cache come [Varnish](https://www.varnish-cache.org/) o [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (vedi anche [Nginx Caching](https://serversforhackers.com/nginx-caching/)) per migliorare notevolmente la velocità e le prestazioni della tua app.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Usa un bilanciatore di carico
+### Use a load balancer
-Non importa quanto sia ottimizzata un'app, una singola istanza può gestire solo una quantità limitata di carico e traffico. Un modo per scalare un'app è quello di eseguire più istanze di esso e distribuire il traffico tramite un balancer. La configurazione di un bilanciatore di carico può migliorare le prestazioni e la velocità della tua app e permetterle di scalare più di quanto sia possibile con una singola istanza.
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-Un bilanciatore di carico è di solito un proxy inverso che orchestra il traffico da e verso più istanze di applicazione e server. Puoi configurare facilmente un bilanciatore di carico per la tua app utilizzando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-Con il bilanciamento del carico, potrebbe essere necessario assicurarsi che le richieste associate a un particolare ID di sessione si connettano al processo che le ha originate. Questo è conosciuto come _session affinity_, o _sticky sessions_, e può essere affrontato dal suggerimento di cui sopra per utilizzare un archivio dati come Redis per i dati di sessione (a seconda della tua applicazione). Per una discussione, vedere [Utilizzo di nodi multipli](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### Usa un proxy inverso
+### Use a reverse proxy
-Un proxy inverso si siede davanti ad una web app ed esegue operazioni di supporto sulle richieste, oltre a dirigere le richieste verso l'app. Può gestire pagine di errore, compressione, caching, servire i file, e bilanciamento del carico tra le altre cose.
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Spostare le attività che non richiedono la conoscenza dello stato dell'applicazione per un proxy inverso libera Express per eseguire attività di applicazione specializzate. Per questo motivo, si raccomanda di eseguire Express dietro un proxy inverso come [Nginx](https://www.nginx.org/) o [HAProxy](https://www.haproxy.org/) in produzione.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/it/advanced/best-practice-security.mdx b/src/content/pages/it/advanced/best-practice-security.mdx
index 0c843b6779..7628d34278 100644
--- a/src/content/pages/it/advanced/best-practice-security.mdx
+++ b/src/content/pages/it/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Scopri le migliori pratiche di sicurezza fondamentali per le app Ex
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Il termine _"produzione"_ si riferisce allo stadio del ciclo di vita del software quando un'applicazione o API è generalmente disponibile per i suoi utenti finali o consumatori. Al contrario, nella fase di _"sviluppo"_ stai ancora scrivendo attivamente e testando il codice, e l'applicazione non è aperta ad accesso esterno. Gli ambienti di sistema corrispondenti sono conosciuti rispettivamente come ambienti _production_ e _development_.
@@ -18,21 +19,19 @@ Policies and Procedures.
Le migliori pratiche di sicurezza per le applicazioni Express in produzione includono:
-- [Migliori Pratiche Di Produzione: Sicurezza](#production-best-practices-security)
- - [Overview](#overview)
- - [Non utilizzare versioni deprecate o vulnerabili di Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Usa TLS](#use-tls)
- - [Non fidarti dell'input dell'utente](#do-not-trust-user-input)
- - [Previene reindirizzamenti aperti](#prevent-open-redirects)
- - [Usa Elmet](#use-helmet)
- - [Riduci l'impronta digitale](#reduce-fingerprinting)
- - [Usa i cookie in modo sicuro](#use-cookies-securely)
- - [Non utilizzare il nome predefinito del cookie di sessione](#dont-use-the-default-session-cookie-name)
- - [Imposta opzioni di sicurezza dei cookie](#set-cookie-security-options)
- - [Prevenire attacchi di forza brutale contro l'autorizzazione](#prevent-brute-force-attacks-against-authorization)
- - [Assicurati che le tue dipendenze siano sicure](#ensure-your-dependencies-are-secure)
- - [Evitare altre vulnerabilità conosciute](#avoid-other-known-vulnerabilities)
- - [Ulteriori considerazioni](#additional-considerations)
+- [Non utilizzare versioni deprecate o vulnerabili di Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Usa TLS](#use-tls)
+- [Non fidarti dell'input dell'utente](#do-not-trust-user-input)
+ - [Previene reindirizzamenti aperti](#prevent-open-redirects)
+- [Usa Elmet](#use-helmet)
+- [Riduci l'impronta digitale](#reduce-fingerprinting)
+- [Usa i cookie in modo sicuro](#use-cookies-securely)
+ - [Non utilizzare il nome predefinito del cookie di sessione](#dont-use-the-default-session-cookie-name)
+ - [Imposta opzioni di sicurezza dei cookie](#set-cookie-security-options)
+- [Prevenire attacchi di forza brutale contro l'autorizzazione](#prevent-brute-force-attacks-against-authorization)
+- [Assicurati che le tue dipendenze siano sicure](#ensure-your-dependencies-are-secure)
+ - [Evitare altre vulnerabilità conosciute](#avoid-other-known-vulnerabilities)
+- [Ulteriori considerazioni](#additional-considerations)
## Non utilizzare versioni deprecate o vulnerabili di Express
@@ -44,7 +43,7 @@ Assicurati inoltre di non utilizzare nessuna delle versioni Express vulnerabili
Se la tua app si occupa o trasmette dati sensibili, usa [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) per proteggere la connessione e i dati. Questa tecnologia crittografa i dati prima che vengano inviati dal client al server, impedendo così alcuni hack comuni (e facili). Anche se le richieste Ajax e POST potrebbero non essere visibilmente evidenti e sembrano "nascoste" nei browser, il loro traffico di rete è vulnerabile a [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) e [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-Potresti avere familiarità con la crittografia Secure Socket Layer (SSL). [TLS è semplicemente la prossima progressione di SSL](). In altre parole, se si utilizza SSL prima, considerare l'aggiornamento a TLS. In generale, si consiglia Nginx per gestire TLS. Per un buon riferimento per configurare TLS su Nginx (e altri server), vedere [Configurazioni server consigliate (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+Potresti avere familiarità con la crittografia Secure Socket Layer (SSL). In generale, si consiglia Nginx per gestire TLS. In altre parole, se si utilizza SSL prima, considerare l'aggiornamento a TLS. In altre parole, se si utilizza SSL prima, considerare l'aggiornamento a TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Inoltre, uno strumento utile per ottenere un certificato TLS gratuito è [Let's Encrypt](https://letsencrypt.org/about/), un gratuito, automatizzato, e autorità di certificazione aperta (CA) fornite dal [Gruppo di ricerca sulla sicurezza Internet (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Ogni intestazione può essere configurata o disabilitata. Per saperne di più su
Installare Elmo come qualsiasi altro modulo:
-```bash
-$ npm install helmet
-```
+
Quindi per usarlo nel tuo codice:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Riduci l'impronta digitale
Può aiutare a fornire un ulteriore livello di sicurezza per ridurre la capacità degli aggressori di determinare
@@ -177,7 +184,7 @@ Utilizzando il nome predefinito del cookie di sessione puoi aprire la tua app ag
Per evitare questo problema, usa i nomi generici dei cookie, ad esempio usando il middleware [express-session](https://www.npmjs.com/package/express-session):
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Imposta opzioni di sicurezza cookie
Impostare le seguenti opzioni di cookie per migliorare la sicurezza:
@@ -200,7 +219,7 @@ Impostare le seguenti opzioni di cookie per migliorare la sicurezza:
Ecco un esempio che usa [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Prevenire attacchi di forza brutale contro l'autorizzazione
Assicurati che gli endpoint di accesso siano protetti per rendere i dati privati più sicuri.
@@ -259,7 +300,7 @@ $ snyk test
### Evitare altre vulnerabilità note
-Tieni d'occhio [Progetto di Sicurezza Nodi](https://npmjs.com/advisories) o [Snyk](https://snyk.io/vuln/) gli avvisi che possono influenzare Express o altri moduli che la tua app utilizza. In generale, queste banche dati sono risorse eccellenti per la conoscenza e gli strumenti sulla sicurezza del nodo.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. In generale, queste banche dati sono risorse eccellenti per la conoscenza e gli strumenti sulla sicurezza del nodo.
Infine, Express apps—come qualsiasi altra web app—può essere vulnerabile a una varietà di attacchi basati sul web. Conoscere se stessi con conosciute [vulnerabilità web](https://www.owasp.org/www-project-top-ten/) e prendere precauzioni per evitarli.
diff --git a/src/content/pages/it/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/it/advanced/healthcheck-graceful-shutdown.md
index 580db6bbdf..31db4aa703 100644
--- a/src/content/pages/it/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/it/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Controlli sanitari
-Un bilanciatore del carico utilizza controlli sanitari per determinare se un'istanza di applicazione è sana e può accettare le richieste. Ad esempio, [Kubernetes ha due controlli di salute](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+Un bilanciatore del carico utilizza controlli sanitari per determinare se un'istanza di applicazione è sana e può accettare le richieste. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, che determina quando riavviare un contenitore.
- `pronte`, che determina quando un contenitore è pronto per iniziare ad accettare il traffico. Quando un baccello non è pronto, viene rimosso dai balanceri di carico di servizio.
diff --git a/src/content/pages/it/advanced/security-updates.mdx b/src/content/pages/it/advanced/security-updates.mdx
index 6091eb215a..90918d2a9c 100644
--- a/src/content/pages/it/advanced/security-updates.mdx
+++ b/src/content/pages/it/advanced/security-updates.mdx
@@ -39,7 +39,7 @@ Policies and Procedures.
- 4.17.3
- La dipendenza `qs` è stata aggiornata per indirizzare una [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp). Questo può influenzare la tua applicazione se vengono utilizzate le seguenti API: `req.query`, `req.body`, `req.param`.
- 4.16.0
- - La dipendenza `inoltrata` è stata aggiornata per indirizzare una [vulnerability](https://npmjs.com/advisories/527). Questo può influenzare la tua applicazione se vengono utilizzate le seguenti API: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
+ - The dependency `forwarded` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-mpcf-4gmh-23w8). Questo può influenzare la tua applicazione se vengono utilizzate le seguenti API: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
- La dipendenza `mime` è stata aggiornata per affrontare una [vulnerability](https://npmjs.com/advisories/535), ma questo problema non influisce su Express.
- La dipendenza `send` è stata aggiornata per fornire una protezione contro una [vulnerabilità Node.js 8.5.0](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Questo influenza solo l'esecuzione di Express sulla specifica versione di Node.js 8.5.0.
- 4.15.5
diff --git a/src/content/pages/it/guide/database-integration.mdx b/src/content/pages/it/guide/database-integration.mdx
index 3f7840b13a..7139dd6704 100644
--- a/src/content/pages/it/guide/database-integration.mdx
+++ b/src/content/pages/it/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Scopri come integrare vari database con le applicazioni Express.js,
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Aggiungere la possibilità di collegare i database alle applicazioni Express è solo una questione di caricare un driver Node.js appropriato per il database nella tua app. Questo documento spiega brevemente come aggiungere e utilizzare alcuni dei moduli Node.js più popolari per i sistemi di database nell'app Express:
@@ -34,13 +35,11 @@ Questi driver di database sono tra molti che sono disponibili. Per altre opzioni
### Installazione
-```bash
-$ npm install cassandra-driver
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**Modulo**: [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installazione
-```bash
-$ npm install couchbase
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**Modulo**: [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### Installazione
-```bash
-$ npm install nano
-```
+
### Esempio
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**Modulo**: [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Installazione
-```bash
-$ npm install level levelup leveldown
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**Modulo**: [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installazione
-```bash
-$ npm install mysql
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**Modulo**: [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installazione
-```bash
-$ npm install mongodb
-```
+
-### Esempio (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### Esempio (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-Se vuoi un driver modello oggetto per MongoDB, guarda [Mongoose](https://github.com/LearnBoost/mongoose).
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**Modulo**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Installazione
-```bash
-$ npm install neo4j-driver
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
-**Modulo**: [oracledb](https://github.com/oracle/node-oracledb)
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Installazione
-NOTA: [Vedi i prerequisiti di installazione](https://github.com/oracle/node-oracledb#-installation).
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**Modulo**: [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installazione
-```bash
-$ npm install pg-promise
-```
+
### Esempio
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**Modulo**: [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### Installazione
-```bash
-$ npm install redis
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
-## Server SQL
+```mjs title="index.mjs"
+import redis from 'redis';
-**Modulo**: [tedious](https://github.com/tediousjs/tedious)
+const client = redis.createClient();
-### Installazione
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
-```bash
-$ npm install tedious
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
```
+## SQL Server
+
+**Module**: [tedious](https://github.com/tediousjs/tedious)
+
+### Installazione
+
+
+
### Esempio
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**Modulo**: [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Installazione
-```bash
-$ npm install sqlite3
-```
+
### Esempio
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -463,17 +588,15 @@ db.close();
## Elasticsearch
-**Modulo**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Installazione
-```bash
-$ npm install elasticsearch
-```
+
### Esempio
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/it/guide/migrating-4.mdx b/src/content/pages/it/guide/migrating-4.mdx
index f34ff36235..47e1fab229 100644
--- a/src/content/pages/it/guide/migrating-4.mdx
+++ b/src/content/pages/it/guide/migrating-4.mdx
@@ -4,42 +4,25 @@ description: Una guida per la migrazione delle applicazioni Express.js dalla ver
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 è un cambiamento di rottura rispetto a Express 3. Ciò significa che un'app Express 3 esistente non funzionerà\_ se aggiorni la versione Express nelle sue dipendenze.
Questo articolo comprende:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Modifiche in Express 4
Nel documento Express 4 sono stati apportati diversi cambiamenti significativi:
-
-
-Cfr. anche:
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
+
+anche:
- [Nuove funzionalità in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x)
- [Migrazione da 3.x a 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
@@ -253,7 +236,7 @@ L'esempio seguente crea un router come modulo, carica middleware in
Ad esempio, crea un file router chiamato `birds.js` nella directory app,
con i seguenti contenuti:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -274,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Quindi, caricare il modulo router nell'app:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -284,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
L'app sarà ora in grado di gestire le richieste ai percorsi `/birds` e
`/birds/about`, e chiamerà il middleware `timeLog`
che è specifico per il percorso.
@@ -299,10 +312,7 @@ La seguente tabella elenca altre modifiche di piccole dimensioni ma importanti i
| Node.js |
-
- Express 4 richiede Node.js 0.10.x o versioni successive e ha abbandonato il supporto per
- Node.js 0.8.x.
- |
+ Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` |
@@ -321,8 +331,7 @@ La seguente tabella elenca altre modifiche di piccole dimensioni ma importanti i
| `json spaces` |
- La proprietà dell'applicazione `json spaces` è disabilitata per impostazione predefinita in
- Express 4.
+ The `json spaces` application property is disabled by default in Express 4.
|
@@ -380,7 +389,7 @@ I file di interesse sono `app.js` e `package.json`.
Considera un'applicazione Express v.3 con il seguente file `app.js`:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -414,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
Il file `package.json` che accompagna la versione 3 potrebbe sembrare
@@ -440,17 +483,15 @@ Inizia il processo di migrazione installando il middleware richiesto per l'app
Express 4 e aggiornando Express e Pug alla rispettiva versione
con il seguente comando:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Effettuare le seguenti modifiche a `app.js`:
-1. Le funzioni integrate di Express middleware `express.favicon`,
+1. The built-in Express middleware functions `express.favicon`,
`express.logger`, `express.methodOverride`,
- `express.session`, `express.bodyParser` e
- `express.errorHandler` non sono più disponibili nell'oggetto `express`
- . Devi installare manualmente le loro alternative
+ `express.session`, `express.bodyParser` and
+ `express.errorHandler` are no longer available on the
+ `express` object. Devi installare manualmente le loro alternative
e caricarle nell'app.
2. Non è più necessario caricare la funzione `app.router`.
@@ -492,7 +533,7 @@ L'esecuzione del comando `npm` sopra aggiornerà `package.json` come segue:
Quindi, rimuovere il codice non valido, caricare il middleware richiesto e fare altre modifiche
se necessario. Il file `app.js` sarà simile a questo:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -542,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
A meno che non sia necessario lavorare direttamente con il modulo `http` (socket.io/SPDY/HTTPS), il caricamento non è richiesto e l'applicazione può essere semplicemente avviata in questo modo:
@@ -577,18 +667,14 @@ the Express 3 app generator and then install the new
Se hai già installato il generatore di app Express 3 sul tuo sistema,
devi disinstallarlo:
-```bash
-$ npm uninstall -g express
-```
+
A seconda di come i privilegi di file e directory sono configurati,
potrebbe essere necessario eseguire questo comando con `sudo`.
Ora installa il nuovo generatore:
-```bash
-$ npm install -g express-generator
-```
+
A seconda di come i privilegi di file e directory sono configurati,
potrebbe essere necessario eseguire questo comando con `sudo`.
diff --git a/src/content/pages/it/guide/migrating-5.mdx b/src/content/pages/it/guide/migrating-5.mdx
index d159f9f3c7..0880ecd5cb 100644
--- a/src/content/pages/it/guide/migrating-5.mdx
+++ b/src/content/pages/it/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: Una guida completa per la migrazione delle applicazioni Express.js
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 5 non è molto diverso da Express 4; anche se mantiene la stessa API di base, ci sono ancora cambiamenti che rompono la compatibilità con la versione precedente. Pertanto, un'applicazione costruita con Express 4 potrebbe non funzionare se lo si aggiorna per utilizzare Express 5.
@@ -11,9 +12,7 @@ Express 5 non è molto diverso da Express 4; anche se mantiene la stessa API di
Per installare questa versione, è necessario avere una **Node.js versione 18 o superiore**. Quindi, esegui il seguente comando nella directory dell'applicazione:
-```sh
-npm install "express@5"
-```
+
È quindi possibile eseguire i test automatici per vedere cosa non funziona, e risolvere i problemi in base agli aggiornamenti elencati di seguito. Dopo aver affrontato i fallimenti di test, eseguire l'app per vedere quali errori si verificano. Scoprirai subito se l'app utilizza metodi o proprietà che non sono supportati.
@@ -23,15 +22,11 @@ Per aiutarti a migrare il tuo server espresso, abbiamo creato un set di codemods
Eseguire il seguente comando per eseguire tutte le codemods disponibili:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
Se si desidera eseguire un codice specifico, è possibile eseguire il seguente comando:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
Puoi trovare la lista dei codici disponibili [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Inizialmente, `del` è stato usato invece di `delete`, perché `delete` è una p
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -80,9 +73,7 @@ I seguenti nomi di metodo sono stati pluralizzati. In Express 4, utilizzando i v
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -103,7 +94,7 @@ Oppure è possibile aggiornare il codice manualmente:
Un carattere principale (:) nel nome della `app. aram(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatity, Express 4 supported it with a deprecation notice. Express 5 lo ignorerà silenziosamente e userà il parametro del nome senza prefissarlo con un colon.
-Questo non dovrebbe influenzare il tuo codice se segui la documentazione Express 4 di [app.param](/4x/api#app.param), in quanto non fa alcuna menzione del colon principale.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(nome)
@@ -113,9 +104,7 @@ Questo metodo potenzialmente confuso e pericoloso di recupero dei dati del modul
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -140,9 +129,7 @@ Express 5 non supporta più la firma `res.json(obj, status)`. Invece, impostare
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -161,9 +148,7 @@ Express 5 non supporta più la firma `res.jsonp(obj, status)`. Invece, impostare
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -182,16 +167,19 @@ Express 5 non supporta più la firma `res.redirect(url, status)`. Invece, utiliz
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Oppure è possibile aggiornare il codice manualmente:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 non supporta più la stringa magica `back` nei metodi `res.redirect()`
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -224,9 +210,7 @@ Express 5 non supporta più la firma `res.send(obj, status)`. Invece, imposta lo
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -246,9 +230,7 @@ Se è necessario inviare un numero utilizzando `res. la funzione end()`, cita il
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -267,9 +249,7 @@ La funzione `res.sendfile()` è stata sostituita da una versione a cassa in camm
È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Oppure è possibile aggiornare il codice manualmente:
@@ -284,6 +264,10 @@ Oppure è possibile aggiornare il codice manualmente:
Le opzioni `hidden` e `from` per `res.sendFile()` non sono più supportate. Usa invece `dotfiles` e `root`.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### Come aggiornare
```diff
@@ -293,12 +277,30 @@ Le opzioni `hidden` e `from` per `res.sendFile()` non sono più supportate. Usa
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### opzioni express.static()
Le opzioni `hidden` e `from` per `express.static()` non sono più supportate. Usa invece `dotfiles` e `root`. Nota che `from` non è mai stato documentato nell'API, ma è stato accettato come alias per `root`. Il valore predefinito di `dotfiles` è ora `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### Come aggiornare
+È possibile aggiornare automaticamente il codice eseguendo il seguente comando:
+
+
+
+Oppure è possibile aggiornare il codice manualmente:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ Le opzioni `hidden` e `from` per `express.static()` non sono più supportate. Us
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
La firma `router.param(fn)` è stata utilizzata per modificare il comportamento della funzione `router.param(name, fn)`. È stato deprecato dal v4.11.0, e Express 5 non lo supporta più.
@@ -449,6 +458,25 @@ Servire directory di punti specifiche usando esplicitamente il `dotfiles: "allow
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### Come aggiornare
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### app.listen
In Express 5, il metodo `app.listen` richiamerà la funzione di callback fornita dall'utente (se fornita) quando il server riceve un evento di errore. In Express 4, tali errori verrebbero lanciati. Questa modifica sposta la responsabilità di gestione degli errori alla funzione di callback in Express 5. Se c'è un errore, verrà passato al callback come argomento.
diff --git a/src/content/pages/it/resources/glossary.mdx b/src/content/pages/it/resources/glossary.mdx
index 2c3d37a903..908d0de024 100644
--- a/src/content/pages/it/resources/glossary.mdx
+++ b/src/content/pages/it/resources/glossary.mdx
@@ -27,7 +27,7 @@ Una funzione che viene invocata dallo strato di routing Express prima del gestor
- `var foo = require('middleware')` si chiama _requiring_ o _using_ un modulo Node.js. Quindi la dichiarazione `var mw = foo()` restituisce tipicamente il middleware.
- `app.use(mw)` si chiama _aggiungendo il middleware allo stack globale di elaborazione_.
-- `app.get('/foo', mw, function (req, res) { ... })` si chiama \_aggiungendo il middleware allo stack di elaborazione "GET /foo" .
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/it/resources/index.mdx b/src/content/pages/it/resources/index.mdx
index 3d7e795976..91420c4d76 100644
--- a/src/content/pages/it/resources/index.mdx
+++ b/src/content/pages/it/resources/index.mdx
@@ -23,7 +23,7 @@ Trova le risorse per aiutarti a imparare, contribuire e connetterti con l'ecosis
diff --git a/src/content/pages/it/resources/middleware/body-parser.mdx b/src/content/pages/it/resources/middleware/body-parser.mdx
index 8ee04e2e0a..438222f6d5 100644
--- a/src/content/pages/it/resources/middleware/body-parser.mdx
+++ b/src/content/pages/it/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Node.js body parsing middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Altri analizzatori del corpo che potrebbero interessarti:
## Installazione
-```sh
-$ npm install body-parser
-```
+
## API
@@ -111,8 +110,8 @@ specifica il numero di byte; se si tratta di una stringa, il valore viene passat
##### reviver
L'opzione `reviver` viene passata direttamente a `JSON.parse` come secondo argomento
-. Puoi trovare maggiori informazioni su questo argomento
-[nella documentazione MDN su JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### rigoroso
diff --git a/src/content/pages/it/resources/middleware/compression.mdx b/src/content/pages/it/resources/middleware/compression.mdx
index c4314ee848..98ae7417d4 100644
--- a/src/content/pages/it/resources/middleware/compression.mdx
+++ b/src/content/pages/it/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js middleware di compressione
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/cookie-parser.mdx b/src/content/pages/it/resources/middleware/cookie-parser.mdx
index 47bca64196..0c81ed4e99 100644
--- a/src/content/pages/it/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/it/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Analizza i cookie di richiesta HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/cookie-session.mdx b/src/content/pages/it/resources/middleware/cookie-session.mdx
index df37530247..580690ecc8 100644
--- a/src/content/pages/it/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/it/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie session middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/cors.mdx b/src/content/pages/it/resources/middleware/cors.mdx
index 6645ec5143..21b8d121aa 100644
--- a/src/content/pages/it/resources/middleware/cors.mdx
+++ b/src/content/pages/it/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Il CORS è un middleware [Node.js](https://nodejs.org/en/) per [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) che imposta le intestazioni di risposta [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS). Queste intestazioni dicono ai browser quali origini possono leggere le risposte dal tuo server.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. Queste intestazioni dicono ai browser quali origini possono leggere le risposte dal tuo server.
@@ -39,9 +40,7 @@ Questo è un modulo [Node.js](https://nodejs.org/en/) disponibile attraverso la
[npm registry](https://www.npmjs.com/). L'installazione viene eseguita usando il comando
[`npm install`](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Utilizzo
diff --git a/src/content/pages/it/resources/middleware/errorhandler.mdx b/src/content/pages/it/resources/middleware/errorhandler.mdx
index e218d9de79..fba0d4c25f 100644
--- a/src/content/pages/it/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/it/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: middleware gestore errori solo sviluppo
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/index.mdx b/src/content/pages/it/resources/middleware/index.mdx
new file mode 100644
index 0000000000..29c702da45
--- /dev/null
+++ b/src/content/pages/it/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Descrizione |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ Queste informazioni si riferiscono a siti, prodotti o moduli di terze parti che non sono mantenuti
+ dal team Expressjs. L'elenco qui non costituisce un'approvazione o una raccomandazione da parte
+ del team di progetto Expressjs.
+
+
+| Middleware module | Descrizione |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/it/resources/middleware/method-override.mdx b/src/content/pages/it/resources/middleware/method-override.mdx
index e9d043b947..35a0f0c912 100644
--- a/src/content/pages/it/resources/middleware/method-override.mdx
+++ b/src/content/pages/it/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Ignora i verbi HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/morgan.mdx b/src/content/pages/it/resources/middleware/morgan.mdx
index 9b22a48b37..288aaebc6c 100644
--- a/src/content/pages/it/resources/middleware/morgan.mdx
+++ b/src/content/pages/it/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: Richiesta HTTP middleware logger per Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ Questo è un modulo [Node.js](https://nodejs.org/en/) disponibile attraverso la
[npm registry](https://www.npmjs.com/). L'installazione viene eseguita usando il comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ Se non viene fornito alcun formato, allora il valore predefinito è `web`.
La versione HTTP della richiesta.
-##### :method
+#####
Il metodo HTTP della richiesta.
-##### :pid
+#####
L'ID di processo del processo Node.js che gestisce la richiesta.
-##### :referrer
+#####
L'intestazione Referrer della richiesta. Questo userà l'intestazione standard errata Referer se esiste, altrimenti Referrer.
@@ -239,7 +238,7 @@ sono scritte, in millisecondi.
L'argomento `digits` è un numero che specifica il numero di cifre da
includere sul numero, default di `3`, che fornisce precisione microsecondo.
-##### :status
+#####
Il codice di stato della risposta.
@@ -255,7 +254,7 @@ ha finito di essere scritta alla connessione, in millisecondi.
L'argomento `digits` è un numero che specifica il numero di cifre da
includere sul numero, default di `3`, che fornisce precisione microsecondo.
-##### :url
+#####
L'URL della richiesta. Questo userà `req.originalUrl` se esiste, altrimenti `req.url`.
diff --git a/src/content/pages/it/resources/middleware/multer.mdx b/src/content/pages/it/resources/middleware/multer.mdx
index 41f80d3ebc..9fb6c0a567 100644
--- a/src/content/pages/it/resources/middleware/multer.mdx
+++ b/src/content/pages/it/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware per la gestione di dati multipart/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ Questo README è disponibile anche in altre lingue:
## Installazione
-```sh
-$ npm install multer
-```
+
## Utilizzo
@@ -263,8 +262,7 @@ null come primo parametro), fare riferimento a
#### `MemoryStorage`
-Il motore di memorizzazione memoria memorizza i file in memoria come oggetti `Buffer`.
-non ha alcuna opzione.
+Il motore di memorizzazione memoria memorizza i file in memoria come oggetti `Buffer`. non ha alcuna opzione.
```javascript
const storage = multer.memoryStorage();
@@ -284,15 +282,16 @@ Un oggetto che specifica i limiti di dimensione delle seguenti proprietà opzion
Sono disponibili i seguenti valori interi:
-| Chiave | Descrizione | Predefinito |
-| --------------- | ------------------------------------------------------------------------------------------- | ----------- |
-| `fieldNameSize` | Dimensione massima nome campo | 100 byte |
-| `fieldSize` | Dimensione massima del campo (in byte) | 1MB |
-| `fields` | Numero massimo di campi non file | Infinito |
-| `fileSize` | Per forme multiple, la dimensione massima del file (in byte) | Infinito |
-| `files` | Per forme multiple, il numero massimo di campi di file | Infinito |
-| `parts` | Per forme multiple, il numero massimo di parti (campi + file) | Infinito |
-| `headerPairs` | Per forme multiparti, il numero massimo di chiavi intestazione=>valore coppie da analizzare | 2000 |
+| Chiave | Descrizione | Predefinito |
+| ------------------- | ------------------------------------------------------------------------------------------- | ----------- |
+| `fieldNameSize` | Dimensione massima nome campo | 100 byte |
+| `fieldSize` | Dimensione massima del campo (in byte) | 1MB |
+| `fields` | Numero massimo di campi non file | Infinito |
+| `fileSize` | Per forme multiple, la dimensione massima del file (in byte) | Infinito |
+| `files` | Per forme multiple, il numero massimo di campi di file | Infinito |
+| `parts` | Per forme multiple, il numero massimo di parti (campi + file) | Infinito |
+| `headerPairs` | Per forme multiparti, il numero massimo di chiavi intestazione=>valore coppie da analizzare | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinito |
Specificare i limiti può aiutare a proteggere il vostro sito dagli attacchi di negazione del servizio (DoS).
@@ -317,6 +316,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Gestione errori
Quando si incontra un errore, Multer delegherà l'errore a Express. Puoi visualizzare
diff --git a/src/content/pages/it/resources/middleware/response-time.mdx b/src/content/pages/it/resources/middleware/response-time.mdx
index 1b690ea8b7..e18c59ccd7 100644
--- a/src/content/pages/it/resources/middleware/response-time.mdx
+++ b/src/content/pages/it/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Tempo di risposta per i server Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/serve-favicon.mdx b/src/content/pages/it/resources/middleware/serve-favicon.mdx
index 1d71d36a31..6b7ce5de0a 100644
--- a/src/content/pages/it/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/it/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon che serve middleware con cache
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/serve-index.mdx b/src/content/pages/it/resources/middleware/serve-index.mdx
index e731949e5e..47aea2486d 100644
--- a/src/content/pages/it/resources/middleware/serve-index.mdx
+++ b/src/content/pages/it/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Serve elenchi directory
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/serve-static.mdx b/src/content/pages/it/resources/middleware/serve-static.mdx
index 92e2c2db72..87483166f7 100644
--- a/src/content/pages/it/resources/middleware/serve-static.mdx
+++ b/src/content/pages/it/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Serve file statici
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/resources/middleware/session.mdx b/src/content/pages/it/resources/middleware/session.mdx
index 8fb8e2e92c..dbb7891298 100644
--- a/src/content/pages/it/resources/middleware/session.mdx
+++ b/src/content/pages/it/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Middleware semplice sessione per Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Installazione
@@ -18,9 +19,7 @@ Questo è un modulo [Node.js](https://nodejs.org/en/) disponibile attraverso la
[npm registry](https://www.npmjs.com/). L'installazione viene eseguita usando il comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -124,9 +123,7 @@ Specifica il valore `boolean` per l'attributo [`Partitioned` `Set-Cookie`](https
. Quando veritiero, l'attributo `Partitioned` è impostato, altrimenti non lo è.
Per impostazione predefinita, l'attributo `Partitioned` non è impostato.
-**Nota** Questo è un attributo che non è stato ancora completamente standardizzato e che potrebbe
-cambiare in futuro. Questo significa anche che molti client possono ignorare questo attributo fino a quando
-lo capiscono.
+**Nota** Questo è un attributo che non è stato ancora completamente standardizzato e che potrebbe cambiare in futuro. Questo significa anche che molti clienti possono ignorare questo attributo fino a quando non lo capiscono.
Per maggiori informazioni su [la proposta](https://github.com/privacycg/CHIPS).
@@ -146,8 +143,10 @@ Specifica che la `string` sia il valore per l'attributo `Set-Cookie`][rfc-west-c
Ulteriori informazioni sui diversi livelli di priorità sono disponibili in
[la specifica][rfc-west-cookie-priority-00-4.1].
-**Nota** Questo è un attributo che non è stato ancora completamente standardizzato e che potrebbe cambiare in futuro.
-Questo significa anche che molti clienti possono ignorare questo attributo fino a quando non lo capiscono.
+**Nota** Questo è un attributo che non è stato ancora completamente standardizzato e che potrebbe
+cambiare in futuro.
+Questo significa anche che molti client possono ignorare questo attributo fino a quando
+lo capiscono.
##### cookie.sameSite
@@ -165,7 +164,8 @@ Ulteriori informazioni sui diversi livelli di esecuzione sono disponibili in
[la specifica][rfc-6265bis-03-4.1.2.7].
**Nota** Questo è un attributo che non è stato ancora completamente standardizzato e che potrebbe cambiare in
-il futuro. Questo significa anche che molti clienti possono ignorare questo attributo fino a quando non lo capiscono.
+il futuro. Questo significa anche che molti client possono ignorare questo attributo fino a quando
+lo capiscono.
**Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been
diff --git a/src/content/pages/it/resources/middleware/timeout.mdx b/src/content/pages/it/resources/middleware/timeout.mdx
index c1290c5844..ea56992b93 100644
--- a/src/content/pages/it/resources/middleware/timeout.mdx
+++ b/src/content/pages/it/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Richiedi timeout middleware per Connect/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Timeout una richiesta nel framework dell'applicazione Connect/Express.
@@ -20,9 +21,7 @@ Questo è un modulo [Node.js](https://nodejs.org/en/) disponibile attraverso la
[npm registry](https://www.npmjs.com/). L'installazione viene eseguita usando il comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/it/resources/middleware/vhost.mdx b/src/content/pages/it/resources/middleware/vhost.mdx
index 197b10414c..35148f2b8e 100644
--- a/src/content/pages/it/resources/middleware/vhost.mdx
+++ b/src/content/pages/it/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Hosting di dominio virtuale
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/it/support.md b/src/content/pages/it/support.md
index fdaefa46e4..6e50530606 100644
--- a/src/content/pages/it/support.md
+++ b/src/content/pages/it/support.md
@@ -7,14 +7,14 @@ description: Trova informazioni sul programma di supporto per le diverse version
Versioni che sono EOL (end-of-life) _may_ ricevere aggiornamenti per le vulnerabilità di sicurezza critiche, ma il team Express non offre alcuna garanzia e non prevede di affrontare o risolvere i problemi riscontrati.
-| Versione Maggiore | Versione Minima Node.js | Data Inizio Supporto | Data Di Fine Supporto |
-| ------------------- | ----------------------- | -------------------- | --------------------- |
-| [**v5.x**](/5x/api) | 18 | Settembre 2024 | **in corso** |
-| [**v4.x**](/4x/api) | 0.10.0 | Aprile 2014 | **in corso** |
-| [**v3.x**](/3x/api) | 0.8.0 | Ottobre 2012 | Luglio 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | Marzo 2011 | Luglio 2012 |
-| **v1.x** | 0.2.0 | Dicembre 2010 | Marzo 2011 |
-| **v0.14.x** | 0.1.98 | Dicembre 2010 | Dicembre 2010 |
+| Versione Maggiore | Versione Minima Node.js | Data Inizio Supporto | Data Di Fine Supporto |
+| -------------------------------------------------------------- | ----------------------- | -------------------- | --------------------- |
+| [**v5.x**](/5x/api) | 18 | Settembre 2024 | **in corso** |
+| [**v4.x**](/4x/api) | 0.10.0 | Aprile 2014 | **in corso** |
+| [**v3.x**](/3x/api) | 0.8.0 | Ottobre 2012 | Luglio 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | Marzo 2011 | Luglio 2012 |
+| **v1.x** | 0.2.0 | Dicembre 2010 | Marzo 2011 |
+| **v0.14.x** | 0.1.98 | Dicembre 2010 | Dicembre 2010 |
## Opzioni Di Supporto Commerciale
diff --git a/src/content/pages/ja/advanced/best-practice-performance.md b/src/content/pages/ja/advanced/best-practice-performance.md
index 3add17f699..ff14aef294 100644
--- a/src/content/pages/ja/advanced/best-practice-performance.md
+++ b/src/content/pages/ja/advanced/best-practice-performance.md
@@ -13,7 +13,7 @@ description: 実稼働中の Express アプリケーションのパフォーマ
- [Do logging correctly](#do-logging-correctly)
- [Handle exceptions properly](#handle-exceptions-properly)
- あなたの環境/セットアップで行うべきこと(オプスパート):
- - [NODE_ENV を "production"に設定](#set-node_env-to-production)
+ - [NODE_ENV を "production"に設定] (#set-node_env-to-production)
- [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
- [Run your app in a cluster](#run-your-app-in-a-cluster)
- [Cache request results](#cache-request-results)
@@ -33,7 +33,7 @@ description: 実稼働中の Express アプリケーションのパフォーマ
Gzip 圧縮は応答本体のサイズを大幅に減らすことができるので、ウェブアプリの速度を向上させます。 エクスプレスアプリでgzip圧縮用の [compression](https://www.npmjs.com/package/compression) ミドルウェアを使用してください。 例:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). その場合、圧縮ミドルウェアを使用する必要はありません。 Nginx で gzip 圧縮を有効にする方法については、Nginx ドキュメントの [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) を参照してください。
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### 同期関数を使用しない
+### Don't use synchronous functions
-同期関数とメソッドは、実行中のプロセスを返すまで結びつけます。 同期関数への単一の呼び出しは、数マイクロ秒またはミリ秒で戻る可能性があります。 しかし、交通量の多いウェブサイトでは、これらの呼び出しはアプリのパフォーマンスを向上させ、削減します。 生産での使用を避けます。
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Node と多くのモジュールは同期バージョンと非同期バージョンの関数を提供しますが、本番環境では常に非同期バージョンを使用します。 同期関数を正当化できる唯一の時間は、最初の起動時です。
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-`--trace-sync-io` コマンドラインフラグを使用すると、アプリケーションが同期 API を使用するたびに警告とスタックトレースを表示できます。 もちろん、本番環境では使用したくないのではなく、コードが本番環境で使用できるようにしてください。 詳細は [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) を参照してください。
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### 正しくログを行う
+### Do logging correctly
-一般的に、アプリからログを記録するには、次の2つの理由があります。デバッグとアプリアクティビティのロギング(基本的には他のすべて)です。 `console.log()` または `console.error()` を使って、ターミナルにログメッセージを出力するのが一般的です。 デスティネーションが端末やファイルの場合、[これらの関数は同期されます](https://nodejs.org/api/console.html#console) 別のプログラムに出力を送らない限り生産には向いていません
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### デバッグ用
+#### For debugging
-デバッグの目的でログを記録する場合は、 `console.log()` の代わりに、 [debug](https://www.npmjs.com/package/debug) のような特別なデバッグモジュールを使用してください。 このモジュールにより、DEBUG 環境変数を使用して `console.error()` に送信されるデバッグメッセージを制御することができます。 アプリケーションを純粋に非同期に保つために、`console.error()`を別のプログラムにパイプします。 しかし、実際に本番環境でデバッグするつもりはありませんね。
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### アプリのアクティビティ用
+#### For app activity
-アプリのアクティビティを記録している場合 (トラフィックや API コールのトラッキングなど)、コンソールを使用する代わりに。 og()\`は、 [Pino](https://www.npmjs.com/package/pino)のようなロギングライブラリを使用します。これは利用可能な最速かつ最も効率的なオプションです。
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### 例外を適切に処理する
+### Handle exceptions properly
-ノードアプリは、キャッチされていない例外に遭遇するとクラッシュします。 例外を処理せず、適切なアクションを実行すると、Express アプリがクラッシュしてオフラインになります。 If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. 幸いなことに、Expressアプリは通常、短い起動時間を持っています。 それにもかかわらず、あなたは最初の場所でクラッシュを避けたいし、それを行うには、適切な例外を処理する必要があります。
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-すべての例外を確実に処理するには、以下の手法を使用します。
+To ensure you handle all exceptions, use the following techniques:
- [Use try-catch](#use-try-catch)
- [Use promises](#use-promises)
-これらのトピックに取り組む前に、Node/Express エラー処理の基本的な理解を持っている必要があります。すなわち、error-first コールバックの使用、およびミドルウェアのエラーの伝播です。 ノードは、非同期関数からエラーを返すために "error-first callback" 規則を使用します。 コールバック関数の最初のパラメータがエラーオブジェクトであり、続くパラメータの結果データが続きます。 エラーがないことを示すには、最初のパラメータとして null を指定します。 コールバック関数は、エラーを有意義に処理するために、error-first コールバック規約に従わなければなりません。 Express では、next() 関数を使用してミドルウェアチェーンを通じてエラーを伝播させるのがベストプラクティスです。
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-エラー処理の基礎については、以下を参照してください。
+For more on the fundamentals of error handling, see:
-- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Try-catchを使用
+#### Use try-catch
-Try-catch は同期コードで例外をキャッチするために使用できる JavaScript 言語構造です。 例えば、以下のように JSON 解析エラーを処理するには、try-catch を使用します。
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-ここでは、プロセスクラッシュの可能性がある例外を処理するために try-catch を使用した例を示します。
-このミドルウェア関数は、JSONオブジェクトである"params"という名前のクエリフィールドパラメータを受け取ります。
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-しかし、try-catch は同期コードでのみ動作します。 Node プラットフォームは主に (特に本番環境では) 非同期であるため、try-catch は多くの例外をキャッチしません。
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Promiseの使用
+#### Use promises
-`async` 関数内でエラーがスローされた場合、または `async` 関数内で rejected Promise が待機されます。 これらのエラーは、`next(err)`を呼び出すかのようにエラーハンドラに渡されます。
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-また、ミドルウェアに非同期関数を使用することもできますし、promiseが失敗した場合にルーターがエラーを処理します。例えば:
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,87 +137,87 @@ app.use(async (req, res, next) => {
});
```
-ベストプラクティスは、できるだけサイトに近いエラーを処理することです。 これはルータで処理されていますが ミドルウェアでエラーをキャッチし、別々のエラー処理ミドルウェアに頼らずに処理するのが最善です。
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### 何をしないか
+#### What not to do
-`unchaughtException`をリッスンするのは\_しないでください。 イベントループに戻るまで例外が発生した場合に発生します。 `uncaughtException` に対してイベントリスナーを追加すると、例外に遭遇するプロセスのデフォルトの動作が変更されます。 例外にもかかわらずこのプロセスは続けられます これはアプリがクラッシュするのを防ぐ良い方法に思えるかもしれません。 しかし、未取得の例外が危険な方法であり、推奨されていない場合、アプリを実行し続けます。 プロセスの状態は信頼できず予測不能になるからです
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-さらに、 `uncaughtException` を使用すると、公式に [crude](https://nodejs.org/api/process.html#event-uncaughtexception) として認識されます。 ですから、 `unchaughtException` を聴くのは悪い考えです。 このため、複数のプロセスやスーパーバイザのようなものをお勧めします。クラッシュと再起動は、多くの場合、エラーから回復する最も信頼性の高い方法です。
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-また、 [domains](https://nodejs.org/api/domain.html) の使用はお勧めしません。 これは一般的に問題を解決せず、非推奨のモジュールです。
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## 環境/設定
+## Things to do in your environment / setup
-以下は、アプリのパフォーマンスを向上させるためにシステム環境でできるいくつかのことです。
+Here are some things you can do in your system environment to improve your app's performance:
-- [NODE_ENV を "production"に設定](#set-node_env-to-production)
+- [NODE_ENV を "production"に設定] (#set-node_env-to-production)
- [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
- [Run your app in a cluster](#run-your-app-in-a-cluster)
- [Cache request results](#cache-request-results)
- [Use a load balancer](#use-a-load-balancer)
- [Use a reverse proxy](#use-a-reverse-proxy)
-### NODE_ENV を "production" に設定
+### Set NODE_ENV to "production"
-NODE_ENV 環境変数は、アプリケーションが実行されている環境 (通常は開発または実装) を指定します。 パフォーマンスを向上させるためにできる最も簡単なことの一つは、NODE_ENV を `production` に設定することです。
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-NODE_ENV を "production" に設定すると Express:
+Setting NODE_ENV to "production" makes Express:
-- ビューテンプレートのキャッシュ。
-- CSS 拡張機能から生成された CSS ファイルをキャッシュします。
-- あまり冗長なエラーメッセージを生成します。
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-[Tests indicate](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) これを行うだけでアプリのパフォーマンスが3倍向上することができます!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-環境固有のコードを書く必要がある場合は、 `process.env.NODE_ENV` でNODE_ENVの値を確認できます。 環境変数の値をチェックするとパフォーマンスペナルティが発生するため、慎重に行う必要があります。
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-開発では、通常、 `export` または `.bash_profile` ファイルを使用して、対話型シェルで環境変数を設定します。 しかし、一般的には、本番サーバーでそれを行うべきではありません。代わりに、OS の init システム (systemd) を使用します。 次のセクションでは、init システム一般の使用法についての詳細を説明します。 しかし、`NODE_ENV`を設定することはパフォーマンスにとってとても重要です(そして実行しやすいので、ここでハイライトされています)。
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-systemdでは、ユニットファイルの中で`Environment`ディレクティブを使用します。 例:
+With systemd, use the `Environment` directive in your unit file. 例:
```sh
Environment=NODE_ENV=production
```
-詳細については、[systemd 単位で環境変数を使用する](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/)を参照してください。
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### アプリが自動的に再起動することを確認します
+### Ensure your app automatically restarts
-本番環境では、アプリケーションをオフラインにしたくありません。 つまり、アプリがクラッシュした場合とサーバー自体がクラッシュした場合の両方が再起動することを確認する必要があります。 これらのイベントのどちらも発生しないことを願っていますが、現実的には両方のイベントを次のように説明する必要があります。
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- プロセス・マネージャーを使用して、クラッシュしたときにアプリ(およびノード)を再起動します。
-- OS がクラッシュしたときに、OS が提供する init システムを使用して、プロセス マネージャを再起動します。 プロセス管理者なしで init システムを使用することもできます。
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-ノードアプリケーションは、キャッチされていない例外が発生した場合にクラッシュします。 The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). しかし、フェイルセーフとして、アプリがクラッシュしたときに自動的に再起動するようにメカニズムを導入します。
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### プロセス管理者を使用する
+#### Use a process manager
-開発では、コマンドラインから `node server.js` などでアプリを起動しました。 しかし、生産でこれを行うことは災害のレシピです。 アプリがクラッシュすると、再起動するまでオフラインになります。 クラッシュした場合にアプリを再起動させるには、プロセスマネージャーを使用します。 プロセス マネージャは、デプロイを容易にし、高可用性を提供し、実行時にアプリケーションを管理することができるアプリケーションの「コンテナ」です。
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-クラッシュ時にアプリを再起動することに加え、プロセスマネージャーは以下を可能にします:
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- ランタイムのパフォーマンスとリソース消費に関する洞察を得ます。
-- パフォーマンスを向上させるために動的に設定を変更します。
-- 制御クラスタリング (pm2)
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-歴史的には、 [PM2](https://github.com/Unitech/pm2) のような Node.js プロセス管理者を使用することが一般的でした。 これを行いたい場合は、ドキュメントを参照してください。 ただし、プロセス管理に init システムを使用することをお勧めします。
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### init システムを使用します
+#### Use an init system
-信頼性の次の層は、サーバーの再起動時にアプリが再起動することを確認することです。 システムはまださまざまな理由でダウンすることができます。 サーバーがクラッシュした場合にアプリが再起動するようにするには、OS に組み込まれた init システムを使用します。 今日使用されている主な init システムは [systemd](https://wiki.debian.org/systemd) です。
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Express アプリで init システムを使用するには、次の 2 つの方法があります。
+There are two ways to use init systems with your Express app:
-- プロセス・マネージャーでアプリを実行し、init システムを使用したサービスとしてプロセス・マネージャをインストールします。 アプリがクラッシュしたときにプロセスマネージャーがアプリを再起動し、OS の再起動時に init システムがプロセスマネージャーを再起動します。 これは推奨されるアプローチです。
-- init システムを使用して、アプリケーションを直接実行します。 これはいくらか簡単ですが、プロセスマネージャーを使用することの追加の利点を得ることはありません。
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-SystemdはLinuxシステムとサービスマネージャーです。 ほとんどの主要な Linux ディストリビューションでは、systemd をデフォルトの init システムとして採用しています。
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-systemd サービスの設定ファイルは *unit file*と呼ばれ、ファイル名は `.service` で終わります。 Nodeアプリケーションを直接管理するためのユニットファイルの例を示します。 ``で囲まれたシステムとアプリの値を置き換えます。
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-systemd の詳細については、[systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html)を参照してください。
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### クラスターでアプリを実行
+### Run your app in a cluster
-マルチコアシステムでは、プロセスのクラスタを起動することで、Node アプリケーションのパフォーマンスを何度も向上させることができます。 クラスタはアプリケーションの複数のインスタンスを実行し、理想的には各 CPU コアで 1 つのインスタンスを実行し、負荷とタスクをインスタンス間で分配します。
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.

-重要: アプリケーション・インスタンスは別々のプロセスとして実行されるため、同じメモリ・スペースは共有されません。 つまり、オブジェクトはアプリの各インスタンスに対してローカルです。 したがって、アプリケーションコードで状態を維持することはできません。 ただし、 [Redis](http://redis.io/) のようなインメモリデータストアを使用してセッション関連のデータや状態を保存することができます。 この注意は、基本的には全ての形態の水平スケーリングに適用され、複数のプロセスまたは複数の物理サーバーでのクラスタリングに適用されます。
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-クラスター化されたアプリケーションでは、ワーカープロセスは他のプロセスに影響を与えることなく個別にクラッシュする可能性があります。 パフォーマンス上の利点とは別に、アプリケーションプロセスのクラスタを実行するもう一つの理由は、障害の分離です。 ワーカープロセスがクラッシュするたびに、常にイベントをログに記録し、cluster.fork() を使用して新しいプロセスを生成するようにしてください。
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### ノードのクラスタモジュールの使用
+#### Using Node's cluster module
-ノードの [cluster module](https://nodejs.org/api/cluster.html) でクラスタリングが可能になりました。 これにより、マスタープロセスはワーカープロセスを生成し、ワーカー間の受信接続を分配することができます。
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### PM2の使用
+#### Using PM2
-PM2を使用してアプリケーションをデプロイする場合は、*without*アプリケーションコードを変更するクラスタリングを利用できます。 [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) を最初に確認してください。 つまり、プロセスにローカルデータは保存されません(セッション、WebSocket接続など)。
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-PM2を使用してアプリケーションを実行する場合、**クラスタモード**を有効にして、選択した複数のインスタンスを使用してクラスタで実行できます。 例えば、マシン上の利用可能なCPU数と一致するなど。 `pm2`コマンドラインツールを使って、クラスタ内のプロセス数を手動で変更できます。
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-クラスタモードを有効にするには、以下のようにアプリケーションを起動します。
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-これは PM2 プロセス ファイル (`ecosystem.config ) 内で設定することもできます。 `exec_mode`を`cluster`に、`instances\`を開始するワーカーの数に設定します。
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-一度実行すると、アプリケーションは次のようにスケーリングできます。
+Once running, the application can be scaled like so:
```bash
@@ -284,22 +293,22 @@ $ pm2 scale my-app 2
For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### キャッシュリクエストの結果
+### Cache request results
-本番環境のパフォーマンスを向上させるもう一つの戦略は、リクエストの結果をキャッシュすることです。 アプリが同じリクエストを繰り返し処理しないようにします。
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-[Varnish](https://www.varnish-cache.org/) や [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) のようなキャッシュサーバーを使用して、アプリの速度とパフォーマンスを大幅に向上させます。([Nginx Caching](https://serversforhackers.com/nginx-caching/)) を参照してください。
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### ロードバランサーを使用
+### Use a load balancer
-どんなに最適化されたアプリであっても、1つのインスタンスは限られた負荷とトラフィックしか処理できません。 アプリを拡張する方法の1つは、アプリの複数のインスタンスを実行し、ロードバランサを介してトラフィックを分散することです。 ロードバランサを設定すると、アプリのパフォーマンスと速度が向上し、1つのインスタンスでより多くのスケールが可能になります。
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-ロードバランサは通常、複数のアプリケーションインスタンスとサーバーとの間でトラフィックをオーケストレーションするリバースプロキシです。 アプリのロードバランサーは、 [Nginx](https://nginx.org/en/docs/http/load_balancing.html) または [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) を使用して簡単に設定できます。
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-ロードバランシングでは、特定のセッション ID に関連付けられているリクエストがそれらを起動したプロセスに接続されていることを確認する必要があります。 これは*session affinity*または*sticky sessions*として知られています。 そして、セッションデータにRedisなどのデータストアを使用するために上記の提案によって対処される場合があります(アプリケーションによって異なります)。 For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### リバースプロキシを使用
+### Use a reverse proxy
-リバースプロキシは Web アプリの前にあり、リクエストをアプリに指示するのとは別に、リクエストに対するサポート操作を行います。 これは、エラーページ、圧縮、キャッシュ、ファイルの提供、および他の間の負荷分散を処理することができます。
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-アプリケーション状態の知識を必要としないタスクをリバースプロキシに引き渡すと、Express を解放して専用のアプリケーションタスクを実行できます。 このため、Express はプロダクション環境で [Nginx](https://www.nginx.org/) や [HAProxy](https://www.haproxy.org/) のようなリバースプロキシの後ろで Express を実行することをお勧めします。
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/ja/advanced/best-practice-security.mdx b/src/content/pages/ja/advanced/best-practice-security.mdx
index 94ce783866..77ab6f0be4 100644
--- a/src/content/pages/ja/advanced/best-practice-security.mdx
+++ b/src/content/pages/ja/advanced/best-practice-security.mdx
@@ -4,8 +4,9 @@ description: 運用中のExpressアプリのセキュリティベストプラク
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-_"production"_ という用語は、アプリケーションや API がエンドユーザーや消費者に一般的に提供されるソフトウェアのライフサイクルにおける段階を指します。 対照的に、*"development"*段階では、コードを積極的に書いたりテストしたりしており、アプリケーションは外部からのアクセスに開かれていません。 対応するシステム環境はそれぞれ _production_ と _development_ と呼ばれています。
+_"production"_ という用語は、アプリケーションや API がエンドユーザーや消費者に一般的に提供されるソフトウェアのライフサイクルにおける段階を指します。 対照的に、\*"development"\*段階では、コードを積極的に書いたりテストしたりしており、アプリケーションは外部からのアクセスに開かれていません。 対応するシステム環境はそれぞれ _production_ と _development_ と呼ばれています。 対照的に、*"development"*段階では、コードを積極的に書いたりテストしたりしており、アプリケーションは外部からのアクセスに開かれていません。 対応するシステム環境はそれぞれ _production_ と _development_ と呼ばれています。
開発環境と生産環境は通常、異なる設定であり、非常に異なる要件を持っています。 開発で問題のあるものは、生産では受け入れられないかもしれません。 たとえば、開発環境では、デバッグ用のエラーの詳細なロギングを行うことができます。 同じ行動が本番環境ではセキュリティ上の懸念になることがあります 開発では拡張性、信頼性、パフォーマンスを心配する必要はありませんが、それらの懸念は生産において重要になります。
@@ -18,39 +19,38 @@ Express でセキュリティ上の脆弱性を発見したと思われる場合
実稼働中の Express アプリケーションのセキュリティのベスト プラクティスは以下のとおりです。
-- [プロダクションのベストプラクティス: セキュリティ](#production-best-practices-security)
- - [Overview](#overview)
- - [Expressの非推奨バージョンや脆弱バージョンを使用しないでください](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Use TLS](#use-tls)
- - [Do not trust user input](#do-not-trust-user-input)
- - [Prevent open redirects](#prevent-open-redirects)
- - [Use Helmet](#use-helmet)
- - [Reduce fingerprinting](#reduce-fingerprinting)
- - [Use cookies securely](#use-cookies-securely)
- - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
- - [Set cookie security options](#set-cookie-security-options)
- - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
- - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
- - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
- - [Additional considerations](#additional-considerations)
+- [Expressの非推奨バージョンや脆弱バージョンを使用しないでください](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Use TLS](#use-tls)
+- [Do not trust user input](#do-not-trust-user-input)
+ - [Prevent open redirects](#prevent-open-redirects)
+- [Use Helmet](#use-helmet)
+- [Reduce fingerprinting](#reduce-fingerprinting)
+- [Use cookies securely](#use-cookies-securely)
+ - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
+ - [Set cookie security options](#set-cookie-security-options)
+- [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
+- [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
+ - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
+- [Additional considerations](#additional-considerations)
## 非推奨または脆弱なバージョンの Express を使用しない
-Express 2.x と 3.x はメンテナンスされなくなりました。 これらのバージョンのセキュリティとパフォーマンスの問題は修正されません。 それらを使用しないでください! If you haven't moved to version 4, follow the [migration guide](/guide/migrating-4) or consider [Commercial Support Options](/support#commercial-support-options).
+Express 2.x と 3.x はメンテナンスされなくなりました。 これらのバージョンのセキュリティとパフォーマンスの問題は修正されません。 それらを使用しないでください! これらのバージョンのセキュリティとパフォーマンスの問題は修正されません。 それらを使用しないでください! If you haven't moved to version 4, follow the [migration guide](/guide/migrating-4) or consider [Commercial Support Options](/support#commercial-support-options).
Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](/advanced/security-updates). もしそうであれば、安定版リリースのいずれかにアップデートしてください。
## TLS を使用
-機密データを扱ったり転送したりする場合は、[Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) を使用して接続とデータを保護します。 この技術は、クライアントからサーバーに送信される前にデータを暗号化し、一般的な(そして簡単な)ハッキングを防ぎます。 Ajax と POST リクエストは目に見えて明らかではなく、ブラウザーでは「非表示」に見えるかもしれません。 彼らのネットワークトラフィックは、[パケットスニッフィング](https://en.wikipedia.org/wiki/Packet_analyzer)と[man-in-the-middle攻撃](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)に対して脆弱です。
+機密データを扱ったり転送したりする場合は、[Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) を使用して接続とデータを保護します。 この技術は、クライアントからサーバーに送信される前にデータを暗号化し、一般的な(そして簡単な)ハッキングを防ぎます。 機密データを扱ったり転送したりする場合は、[Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) を使用して接続とデータを保護します。 この技術は、クライアントからサーバーに送信される前にデータを暗号化し、一般的な(そして簡単な)ハッキングを防ぎます。 Ajax と POST リクエストは目に見えて明らかではなく、ブラウザーでは「非表示」に見えるかもしれません。 彼らのネットワークトラフィックは、[パケットスニッフィング](https://en.wikipedia.org/wiki/Packet_analyzer)と[man-in-the-middle攻撃](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)に対して脆弱です。
-SSL(Secure Socket Layer)暗号化に精通しているかもしれません。 [TLS は、単に SSLの次の進行である]()。 言い換えれば、以前SSLを使用していた場合は、TLSへのアップグレードを検討してください。 一般的に、Nginx は TLS を扱うことをお勧めします。 Nginx (および他のサーバ) で TLS を設定するための参考情報については、[推奨サーバー構成 (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations)を参照してください。
+SSL(Secure Socket Layer)暗号化に精通しているかもしれません。 [TLS is simply the next progression of SSL](https://learn.microsoft.com/en-us/windows/win32/secauthn/tls-versus-ssl). 言い換えれば、以前SSLを使用していた場合は、TLSへのアップグレードを検討してください。 一般的に、Nginx は TLS を扱うことをお勧めします。 For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Also, a handy tool to get a free TLS certificate is [Let's Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
## ユーザー入力を信頼しない
Webアプリケーションの場合、最も重要なセキュリティ要件の1つは、適切なユーザー入力検証と処理です。 これは多くの形態で来て、我々はここでそれらのすべてをカバーしません。
+最終的に、アプリケーションが受け入れるユーザー入力の種類を検証し、正しく処理する責任はあなたのものです。 これは多くの形態で来て、我々はここでそれらのすべてをカバーしません。
最終的に、アプリケーションが受け入れるユーザー入力の種類を検証し、正しく処理する責任はあなたのものです。
### 開いているリダイレクトを防止
@@ -79,7 +79,7 @@ app.use((req, res) => {
[Helmet][helmet] は、HTTPヘッダーを適切に設定することで、よく知られているWeb脆弱性からアプリを保護するのに役立ちます。
-Helmet は、セキュリティ関連の HTTP レスポンスヘッダーを設定するミドルウェア機能です。 ヘルメットは、デフォルトで次のヘッダーを設定します。
+Helmet は、セキュリティ関連の HTTP レスポンスヘッダーを設定するミドルウェア機能です。 ヘルメットは、デフォルトで次のヘッダーを設定します。 ヘルメットは、デフォルトで次のヘッダーを設定します。
- `Content-Security-Policy`: 多くの攻撃を軽減するためにあなたのページで何が起こるかを許可する強力なリスト
- `Cross-Origin-Opener-Policy`: あなたのページを分離するのに役立ちます
@@ -92,20 +92,18 @@ Helmet は、セキュリティ関連の HTTP レスポンスヘッダーを設
- `X-Download-Options`: 強制的にダウンロードを保存します (Internet Explorerのみ)
- `X-Frame-Options`: [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) 攻撃を軽減する従来のヘッダー
- `X-Permitted-Cross-Domain-Policies`: Acrobat など、Adobe 製品のクロスドメイン動作を制御します
-- `X-Powered-By`: Webサーバーに関する情報。 簡単な攻撃で使用できるため削除されました
+- `X-Powered-By`: Webサーバーに関する情報。 簡単な攻撃で使用できるため削除されました 簡単な攻撃で使用できるため削除されました
- `X-XSS-Protection`: [XSS アタック](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)を軽減しようとするレガシーヘッダーが悪化するため、ヘルメットは無効にします
-各ヘッダーは、設定または無効にできます。 詳細については、[its documentation website][helmet] をご覧ください。
+各ヘッダーは、設定または無効にできます。 詳細については、[its documentation website][helmet] をご覧ください。 詳細については、[its documentation website][helmet] をご覧ください。
他のモジュールと同様にヘルメットをインストール:
-```bash
-$ npm install helmet
-```
+
次に、コードでそれを使用します:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,13 +112,26 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## フィンガープリントを減らす
サーバーが使用する
ソフトウェアを判断する攻撃者の能力を低下させるために、セキュリティの追加層を提供するのに役立ちます。 「指紋」として知られています セキュリティ問題自体ではありませんが、
アプリケーションの指紋化能力を低下させることで、セキュリティ全体の姿勢が改善されます。
サーバーソフトウェアは、例えば、
-HTTPレスポンスヘッダのように、特定のリクエストにどのように応答するかの癖でフィンガープリントすることができます。
+HTTPレスポンスヘッダのように、特定のリクエストにどのように応答するかの癖でフィンガープリントすることができます。 Though not a security issue itself,
+reducing the ability to fingerprint an application improves its overall security posture.
+Server software can be fingerprinted by quirks in how it responds to specific requests, for example in
+the HTTP response headers.
By default, Express sends the `X-Powered-By` response header that you can
disable using the `app.disable()` method:
@@ -133,7 +144,8 @@ app.disable('x-powered-by');
`X-Powered-By header` を無効にすると、洗練された攻撃者が Express を実行していることを
判断できません。 カジュアルなエクスプロイトを妨げるかもしれませんが、アプリがExpressを実行していることを
-判断する他の方法があります。
+判断する他の方法があります。 It may discourage a casual exploit, but there are other ways to
+determine an app is running Express.
@@ -141,7 +153,10 @@ Expressはまた、独自のフォーマットされた「404 Not Found」メッ
応答メッセージを送信します。 これらは、
[自分の見つからないハンドラを追加する](/starter/faq#how-do-i-handle-404-responses)
と
-[自分のエラーハンドラを書く](/guide/error-handling#writing-error-handlers): によって変更できます。
+[自分のエラーハンドラを書く](/guide/error-handling#writing-error-handlers): によって変更できます。 These can be changed by
+[adding your own not found handler](/starter/faq#how-do-i-handle-404-responses)
+and
+[writing your own error handler](/guide/error-handling#writing-error-handlers):
```js
// last app.use calls right before app.listen():
@@ -167,17 +182,17 @@ app.use((err, req, res, next) => {
- `express.session`ミドルウェアをExpress 3.xに置き換える[express-session](https://www.npmjs.com/package/express-session)
- `express.cookieSession` ミドルウェアをExpress 3.xに置き換える[cookie-session](https://www.npmjs.com/package/cookie-session)
-これらの2つのモジュールの主な違いは、クッキーセッションデータの保存方法です。 [express-session](https://www.npmjs.com/package/express-session) ミドルウェアは、セッションデータをサーバー上に保存します。セッションIDは、セッションデータではなく、クッキー自体にのみ保存します。 デフォルトでは、インメモリストレージを使用し、本番環境用に設計されていません。 本番環境では、スケーラブルな session-store を設定する必要があります。[compatible session store](https://github.com/expressjs/session#compatible-session-stores) のリストを参照してください。
+The main difference between these two modules is how they save cookie session data. これらの2つのモジュールの主な違いは、クッキーセッションデータの保存方法です。 [express-session](https://www.npmjs.com/package/express-session) ミドルウェアは、セッションデータをサーバー上に保存します。セッションIDは、セッションデータではなく、クッキー自体にのみ保存します。 デフォルトでは、インメモリストレージを使用し、本番環境用に設計されていません。 本番環境では、スケーラブルな session-store を設定する必要があります。[compatible session store](https://github.com/expressjs/session#compatible-session-stores) のリストを参照してください。 By default, it uses in-memory storage and is not designed for a production environment. In production, you'll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores).
-対照的に、 [cookie-session](https://www.npmjs.com/package/cookie-session) middleware は、セッションキーだけではなく、セッション全体を Cookie にシリアライズします。 セッションデータが比較的小さく、(オブジェクトではなく)プリミティブ値としてエンコードしやすい場合にのみ使用してください。 ブラウザはクッキーごとに少なくとも4096バイトをサポートすることになっていますが。 制限を超えないようにするには、ドメインあたり4093バイトのサイズを超えないようにします。 また、クッキーデータがクライアントに表示されることに注意してください ですから、もしそれを安全または不明瞭に保つ理由がある場合は、 `express-session` はより良い選択かもしれません。
+対照的に、 [cookie-session](https://www.npmjs.com/package/cookie-session) middleware は、セッションキーだけではなく、セッション全体を Cookie にシリアライズします。 セッションデータが比較的小さく、(オブジェクトではなく)プリミティブ値としてエンコードしやすい場合にのみ使用してください。 ブラウザはクッキーごとに少なくとも4096バイトをサポートすることになっていますが。 制限を超えないようにするには、ドメインあたり4093バイトのサイズを超えないようにします。 また、クッキーデータがクライアントに表示されることに注意してください ですから、もしそれを安全または不明瞭に保つ理由がある場合は、 `express-session` はより良い選択かもしれません。 Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don't exceed the limit, don't exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then `express-session` may be a better choice.
### デフォルトのセッションクッキー名を使用しない
-デフォルトのセッションクッキー名を使用すると、あなたのアプリを攻撃することができます。 提起されたセキュリティ上の問題は `X-Powered-By` と似ています。潜在的な攻撃者がそれを使用してサーバーにフィンガープリントを行い、それに応じて攻撃を標的にすることができます。
+デフォルトのセッションクッキー名を使用すると、あなたのアプリを攻撃することができます。 提起されたセキュリティ上の問題は `X-Powered-By` と似ています。潜在的な攻撃者がそれを使用してサーバーにフィンガープリントを行い、それに応じて攻撃を標的にすることができます。 The security issue posed is similar to `X-Powered-By`: a potential attacker can use it to fingerprint the server and target attacks accordingly.
この問題を回避するには、ジェネリックな Cookie 名を使用してください。例えば、 [express-session](https://www.npmjs.com/package/express-session) ミドルウェアを使用してください。
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,19 +203,31 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Cookie のセキュリティオプションを設定
セキュリティを強化するために、次のクッキーオプションを設定します。
- `secure` - HTTPS経由でのみCookieを送信できるようにします。
- `httpOnly` - CookieがクライアントJavaScriptではなくHTTP(S)上でのみ送信されることを保証し、クロスサイトスクリプティング攻撃から保護します。
-- `domain` - Cookie のドメインを示します。URL がリクエストされているサーバーのドメインと比較するために使用します。 一致する場合は、次にパス属性を確認します。
-- `path` - クッキーのパスを示します。リクエストパスと比較するために使用します。 これとドメインが一致した場合は、リクエストにクッキーを送信します。
+- `domain` - Cookie のドメインを示します。URL がリクエストされているサーバーのドメインと比較するために使用します。 一致する場合は、次にパス属性を確認します。 If they match, then check the path attribute next.
+- `path` - クッキーのパスを示します。リクエストパスと比較するために使用します。 これとドメインが一致した場合は、リクエストにクッキーを送信します。 If this and domain match, then send the cookie in the request.
- `expires` - 永続的クッキーの有効期限を設定するために使用します。
[cookie-session](https://www.npmjs.com/package/cookie-session) ミドルウェアを使用した例を以下に示します。
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +248,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## 承認に対するブルートフォース攻撃を防止
プライベートデータをより安全にするために、ログインエンドポイントが保護されていることを確認してください。
@@ -228,15 +277,15 @@ app.use(
シンプルで強力な手法は、2つの指標を使用して認証試行をブロックすることです。
1. 同じユーザー名とIPアドレスによる連続失敗回数。
-2. 長期間IPアドレスからの失敗回数。 たとえば、1 日で 100 回失敗した場合、IP アドレスをブロックします。
+2. 長期間IPアドレスからの失敗回数。 たとえば、1 日で 100 回失敗した場合、IP アドレスをブロックします。 For example, block an IP address if it makes 100 failed attempts in one day.
-[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) パッケージは、このテクニックを簡単かつ高速にするためのツールを提供します。 You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)
+[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) package provides tools to make this technique easy and fast. [rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) パッケージは、このテクニックを簡単かつ高速にするためのツールを提供します。 You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)
## 依存関係が安全であることを確認する
-npm を使用してアプリケーションの依存関係を管理するのは強力で便利です。 ただし、使用するパッケージには、アプリケーションにも影響を与える可能性のある重大なセキュリティ脆弱性が含まれている場合があります。 アプリのセキュリティは、依存関係の「最も弱いリンク」と同じくらい強力です。
+npm を使用してアプリケーションの依存関係を管理するのは強力で便利です。 ただし、使用するパッケージには、アプリケーションにも影響を与える可能性のある重大なセキュリティ脆弱性が含まれている場合があります。 アプリのセキュリティは、依存関係の「最も弱いリンク」と同じくらい強力です。 But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the "weakest link" in your dependencies.
-npm@6 以降、npm は自動的にすべてのインストール リクエストをレビューします。 また、`npm audit` を使用して依存関係のツリーを分析することもできます。
+Since npm@6, npm automatically reviews every install request. npm@6 以降、npm は自動的にすべてのインストール リクエストをレビューします。 また、`npm audit` を使用して依存関係のツリーを分析することもできます。
```bash
$ npm audit
@@ -244,7 +293,7 @@ $ npm audit
もっと安全な場合は、 [Snyk](https://snyk.io/) を検討してください。
-Snyk は [コマンド ライン ツール](https://www.npmjs.com/package/snyk) と [Github 統合](https://snyk.io/docs/github) の両方を提供しており、依存関係の既知の脆弱性についてアプリケーションを [Snyk のオープン ソース 脆弱性 データベース](https://snyk.io/vuln/) でチェックします。 CLI を以下のようにインストールします。
+Snyk は [コマンド ライン ツール](https://www.npmjs.com/package/snyk) と [Github 統合](https://snyk.io/docs/github) の両方を提供しており、依存関係の既知の脆弱性についてアプリケーションを [Snyk のオープン ソース 脆弱性 データベース](https://snyk.io/vuln/) でチェックします。 CLI を以下のようにインストールします。 Install the CLI as follows:
```bash
$ npm install -g snyk
@@ -259,13 +308,13 @@ $ snyk test
### その他の既知の脆弱性を回避する
-Keep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. 一般的に、これらのデータベースは、Node セキュリティに関する知識とツールのための優れたリソースです。
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. 一般的に、これらのデータベースは、Node セキュリティに関する知識とツールのための優れたリソースです。
Finally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
## その他の考慮事項
-優れた [Node.js セキュリティ チェックリスト](https://blog.risingstack.com/node-js-security-checklist/) からのさらなる推奨事項をいくつか紹介します。 これらの推奨事項の詳細については、そのブログ記事を参照してください。
+優れた [Node.js セキュリティ チェックリスト](https://blog.risingstack.com/node-js-security-checklist/) からのさらなる推奨事項をいくつか紹介します。 これらの推奨事項の詳細については、そのブログ記事を参照してください。 Refer to that blog post for all the details on these recommendations:
- クロスサイト・スクリプティング(XSS)やコマンドインジェクション攻撃から保護するため、常にユーザー入力をフィルタリングしてサニタイズします。
- パラメータ化されたクエリまたは準備された文を使用してSQLインジェクション攻撃を防御します。
diff --git a/src/content/pages/ja/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/ja/advanced/healthcheck-graceful-shutdown.md
index 6611117c3a..a20eef9a3e 100644
--- a/src/content/pages/ja/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/ja/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## 健康チェック
-ロードバランサは、ヘルスチェックを使用して、アプリケーションインスタンスが健全かどうかを判断し、リクエストを受け入れることができます。 例えば、[Kubernetes には2つのヘルスチェックがあります](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+ロードバランサは、ヘルスチェックを使用して、アプリケーションインスタンスが健全かどうかを判断し、リクエストを受け入れることができます。 For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness` コンテナを再起動するタイミングを決定します。
- コンテナがいつトラフィックを受け入れる準備ができているかを決める準備が整います。 ポッドの準備ができていない場合は、サービスロードバランサーから取り外されます。
diff --git a/src/content/pages/ja/advanced/security-updates.mdx b/src/content/pages/ja/advanced/security-updates.mdx
index 13c8db554a..fee78e581a 100644
--- a/src/content/pages/ja/advanced/security-updates.mdx
+++ b/src/content/pages/ja/advanced/security-updates.mdx
@@ -9,6 +9,8 @@ import Alert from '@components/primitives/Alert/Alert.astro';
Node.js の脆弱性は Express に直接影響します。 そのため、Node.js
脆弱性を監視する と最新の
+安定版の Node.js を使用していることを確認してください。 そのため、Node.js
+脆弱性を監視する と最新の
安定版の Node.js を使用していることを確認してください。
@@ -37,18 +39,18 @@ Express でセキュリティ上の脆弱性を発見したと思われる場合
- 4.19.0, 4.19.1
- `res.location` と `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc), [CVE-2024-29041](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-29041)のオープンリダイレクトの脆弱性を修正しました。
- 4.17.3
- - 依存関係の `qs` が [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp) に更新されました。 `req.query`、`req.body`、`req.param`という以下のAPIを使用すると、アプリケーションに影響を与える可能性があります。
+ - 依存関係の `qs` が [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp) に更新されました。 `req.query`、`req.body`、`req.param`という以下のAPIを使用すると、アプリケーションに影響を与える可能性があります。 `req.query`、`req.body`、`req.param`という以下のAPIを使用すると、アプリケーションに影響を与える可能性があります。
- 4.16.0
- - 依存関係の `forwarded` が [vulnerability](https://npmjs.com/advisories/527) に更新されました。 以下の API が使用されている場合、アプリケーションに影響を与える可能性があります: `req.host` 、 `req.hostname` 、 `req.ips` 、 `req.protocol` 。
- - 依存関係の `mime` が [vulnerability](https://npmjs.com/advisories/535) 宛先に更新されましたが、この問題は Express には影響しません。
- - 依存関係の `send` が更新され、[Node.js 8.5.0 脆弱性](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/)に対する保護が提供されました。 これは、Express が特定の Node.js バージョン 8.5.0 で実行されることにのみ影響します。
+ - The dependency `forwarded` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-mpcf-4gmh-23w8). 依存関係の `forwarded` が [vulnerability](https://npmjs.com/advisories/527) に更新されました。 以下の API が使用されている場合、アプリケーションに影響を与える可能性があります: `req.host` 、 `req.hostname` 、 `req.ips` 、 `req.protocol` 。
+ - The dependency `mime` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-wrvr-8mpx-r7pp), but this issue does not impact Express.
+ - 依存関係の `send` が更新され、[Node.js 8.5.0 脆弱性](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/)に対する保護が提供されました。 これは、Express が特定の Node.js バージョン 8.5.0 で実行されることにのみ影響します。 これは、Express が特定の Node.js バージョン 8.5.0 で実行されることにのみ影響します。
- 4.15.5
- 依存関係の `debug` が [vulnerability](https://snyk.io/vuln/npm:debug:20170905) アドレスに更新されましたが、この問題は Express には影響しません。
- - 依存関係の `fresh` が [vulnerability](https://npmjs.com/advisories/526) に更新されました。 `express.static` 、 `req.fresh` 、 `res.json` 、 `res.json` 、 `res.send` 、 `res.send` 、 `res.sendFile` 、 `res.sendFile` 、 `res.sendStatus` などのAPIが使用されると、アプリケーションに影響します。
+ - The dependency `fresh` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-9qj9-36jm-prpv). 依存関係の `fresh` が [vulnerability](https://npmjs.com/advisories/526) に更新されました。 `express.static` 、 `req.fresh` 、 `res.json` 、 `res.json` 、 `res.send` 、 `res.send` 、 `res.sendFile` 、 `res.sendFile` 、 `res.sendStatus` などのAPIが使用されると、アプリケーションに影響します。
- 4.15.3
- - 依存関係の `ms` が [vulnerability](https://snyk.io/vuln/npm:ms:20170412) に更新されました。 信頼されていない文字列が次の API で `maxAge` オプションに渡されると、アプリケーションに影響を与える可能性があります。`express.static` 、 `res.sendfile` 、 `res.sendFile` です。
+ - The dependency `ms` has been updated to address a [vulnerability](https://security.snyk.io/vuln/npm:ms:20170412). 依存関係の `ms` が [vulnerability](https://snyk.io/vuln/npm:ms:20170412) に更新されました。 信頼されていない文字列が次の API で `maxAge` オプションに渡されると、アプリケーションに影響を与える可能性があります。`express.static` 、 `res.sendfile` 、 `res.sendFile` です。
- 4.15.2
- - 依存関係`qs`が [vulnerability](https://snyk.io/vuln/npm:qs:20170213)アドレスに更新されましたが、この問題はExpressには影響しません。 4.15.2 へのアップデートは良い方法ですが、脆弱性に対処する必要はありません。
+ - 依存関係`qs`が [vulnerability](https://snyk.io/vuln/npm:qs:20170213)アドレスに更新されましたが、この問題はExpressには影響しません。 4.15.2 へのアップデートは良い方法ですが、脆弱性に対処する必要はありません。 4.15.2 へのアップデートは良い方法ですが、脆弱性に対処する必要はありません。
- 4.11.1
- `express.static`、`res.sendfile`、`res.sendFile`におけるルートパス開示の脆弱性を修正しました。
- 4.10.7
@@ -56,7 +58,7 @@ Express でセキュリティ上の脆弱性を発見したと思われる場合
- 4.8.8
- `express.static` ([advisory](http://npmjs.com/advisories/32) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)のディレクトリトラバーサルの脆弱性を修正しました。
- 4.8.4
- - Node.js 0.10 は、`express.static` と `res.sendfile` に影響を与える特定の状況で `fd` をリークできます。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。
+ - Node.js 0.10 は、`express.static` と `res.sendfile` に影響を与える特定の状況で `fd` をリークできます。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。
- 4.8.0
- クエリ文字列に非常に高いインデックスを持つ疎行列は、プロセスがメモリ不足になり、サーバーがクラッシュする可能性があります。
- 非常にネストされたクエリ文字列オブジェクトは、プロセスをブロックし、サーバーが一時的に応答しないようにする可能性があります。
@@ -79,7 +81,7 @@ Express でセキュリティ上の脆弱性を発見したと思われる場合
- 3.16.10
- `express.static`におけるディレクトリトラバーサルの脆弱性を修正しました。
- 3.16.6
- - Node.js 0.10 は、`express.static` と `res.sendfile` に影響を与える特定の状況で `fd` をリークできます。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。
+ - Node.js 0.10 は、`express.static` と `res.sendfile` に影響を与える特定の状況で `fd` をリークできます。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。 悪意のある要求は`fd`がリークし、最終的には`EMFILE`エラーとサーバーの応答性が低下する可能性があります。
- 3.16.0
- クエリ文字列のインデックスが非常に高いスパース配列は、プロセスがメモリ不足になり、サーバーがクラッシュする可能性があります。
- 非常にネストされたクエリ文字列オブジェクトは、プロセスをブロックし、サーバーが一時的に応答しないようにする可能性があります。
diff --git a/src/content/pages/ja/guide/database-integration.mdx b/src/content/pages/ja/guide/database-integration.mdx
index 288e0fc5c0..dfb086d24e 100644
--- a/src/content/pages/ja/guide/database-integration.mdx
+++ b/src/content/pages/ja/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: MongoDB、MySQL、PostgreSQLなどのセットアップ例を含む
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Expressアプリケーションにデータベースを接続する機能を追加することは、アプリケーション内のデータベースに適切なNode.jsドライバをロードするだけです。 このドキュメントでは、Express アプリケーションで最も人気のある Node.js モジュールのいくつかを追加して使用する方法を簡単に説明します。
@@ -34,13 +35,11 @@ Expressアプリケーションにデータベースを接続する機能を追
### インストール
-```bash
-$ npm install cassandra-driver
-```
+
### 例
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**モジュール**: [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### インストール
-```bash
-$ npm install couchbase
-```
+
### 例
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**モジュール**: [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### インストール
-```bash
-$ npm install nano
-```
+
### 例
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**モジュール**: [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### インストール
-```bash
-$ npm install level levelup leveldown
-```
+
### 例
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**モジュール**: [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### インストール
-```bash
-$ npm install mysql
-```
+
### 例
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**モジュール**: [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### インストール
-```bash
-$ npm install mongodb
-```
+
-### 例 (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### 例 (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-MongoDB用のオブジェクトモデルドライバが必要な場合は、 [Mongoose](https://github.com/LearnBoost/mongoose) を参照してください。
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**モジュール**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### インストール
-```bash
-$ npm install neo4j-driver
-```
+
### 例
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
-**モジュール**: [oracledb](https://github.com/oracle/node-oracledb)
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### インストール
-注意: [インストール前提条件を参照](https://github.com/oracle/node-oracledb#-installation)。
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### 例
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**モジュール**: [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### インストール
-```bash
-$ npm install pg-promise
-```
+
### 例
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**モジュール**: [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### インストール
-```bash
-$ npm install redis
-```
+
### 例
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
+```mjs title="index.mjs"
+import redis from 'redis';
+
+const client = redis.createClient();
+
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
+
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
+```
+
## SQL Server
-**モジュール**: [tedious](https://github.com/tediousjs/tedious)
+**Module**: [tedious](https://github.com/tediousjs/tedious)
### インストール
-```bash
-$ npm install tedious
-```
+
### 例
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**モジュール**: [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### インストール
-```bash
-$ npm install sqlite3
-```
+
### 例
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -463,17 +588,15 @@ db.close();
## Elasticsearch
-**モジュール**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### インストール
-```bash
-$ npm install elasticsearch
-```
+
### 例
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/ja/guide/migrating-4.mdx b/src/content/pages/ja/guide/migrating-4.mdx
index f65e401430..15d828e277 100644
--- a/src/content/pages/ja/guide/migrating-4.mdx
+++ b/src/content/pages/ja/guide/migrating-4.mdx
@@ -4,39 +4,23 @@ description: Express.jsアプリケーションをバージョン3からバー
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-エクスプレス4はエクスプレス3からの変更です。 つまり、Expressバージョンを依存関係で更新すると、既存のExpress 3アプリは動作しなくなります。
+エクスプレス4はエクスプレス3からの変更です。 つまり、Expressバージョンを依存関係で更新すると、既存のExpress 3アプリは動作しなくなります。 つまり、Expressバージョンを依存関係で更新すると、既存のExpress 3アプリは動作しなくなります。
この記事のカバー:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Express 4の変更
Express 4にはいくつかの大きな変更点があります。
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
こちらもご参照ください:
@@ -48,10 +32,12 @@ Express 4にはいくつかの大きな変更点があります。
Express 4はもうConnectに依存せず、組み込みの
ミドルウェアをコアから削除します。ただし、`express.static`関数は除外します。 This means that
Express is now an independent routing and middleware web framework, and
+Express versioning and releases are not affected by middleware updates. This means that
+Express is now an independent routing and middleware web framework, and
Express versioning and releases are not affected by middleware updates.
組み込みのミドルウェアがなければ、アプリケーションの実行に必要なすべての
-ミドルウェアを明示的に追加する必要があります。 以下の手順に従ってください:
+ミドルウェアを明示的に追加する必要があります。 以下の手順に従ってください: 以下の手順に従ってください:
1. モジュールをインストール: `npm install --save \`
2. アプリでは、次のモジュールを必要とします: `require('module-name')`
@@ -191,12 +177,14 @@ Here is the [complete list](https://github.com/senchalabs/connect#middleware) of
ほとんどの場合、古いバージョン3のミドルウェアを
のExpress 4に置き換えることができます。 詳細については、
+GitHub のモジュールドキュメントを参照してください。 詳細については、
GitHub のモジュールドキュメントを参照してください。
#### `app.use`はパラメータを受け付けます
バージョン 4 では、変数 parameter を使用して、ミドルウェア関数がロードされるパスを定義できます。 次に、ルートハンドラからパラメータの値を読み込みます。
例:
+例:
```js
app.use('/book/:id', (req, res, next) => {
@@ -221,7 +209,8 @@ the `router` middleware.
新しい`app.route()`メソッドを使用すると、ルートパスのチェーン可能なルートハンドラ
を作成できます。 パスは単一の場所で指定されているため、モジュラールートを作成することは、冗長性とタイプミスを削減するのに役立ちます。 For more
-information about routes, see [`Router()` documentation](/4x/api#router).
+information about routes, see [`Router()` documentation](/4x/api#router). パスは単一の場所で指定されているため、モジュラールートを作成することは、冗長性とタイプミスを削減するのに役立ちます。 For more
+information about routes, see [`Router()` documentation](/4x/api/router/).
以下は、`app.route()`関数を使用して定義されたルートハンドラの例です。
@@ -244,6 +233,7 @@ app
ルートを整理するのに役立つもう一つの機能は、新しいクラス
`express.Router` で、モジュラーマウント可能な
ルートハンドラを作成するために使用できます。 `Router`インスタンスは完全なミドルウェアと
+ルーティングシステムです。このため、しばしば"mini-app"と呼ばれます。 `Router`インスタンスは完全なミドルウェアと
ルーティングシステムです。このため、しばしば"mini-app"と呼ばれます。
The following example creates a router as a module, loads middleware in
@@ -252,7 +242,7 @@ it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named `birds.js` in the app directory,
with the following content:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +263,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
次に、アプリにルーターモジュールをロードします。
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,6 +295,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to the `/birds` and
`/birds/about` paths, and will call the `timeLog`
middleware that is specific to the route.
@@ -305,14 +325,15 @@ middleware that is specific to the route.
|
`http`モジュールは、
(socket.io/SPDY/HTTPS)で直接動作する必要がない限り、もはや必要ありません。
- アプリは、`app.listen()`関数を使用して起動できます。
+ アプリは、`app.listen()`関数を使用して起動できます。 The app can be started by using the
+ `app.listen()` function.
|
| `app.configure()` |
- `app.configure()`関数が削除されました。 `process.env.NODE_ENV` または `app.get('env')`
- 関数を使用して環境を検出し、それに応じてアプリを構成します。
+ The `app.configure()` function has been removed. Use the `process.env.NODE_ENV` or
+ `app.get('env')` function to detect the environment and configure the app accordingly.
|
@@ -360,7 +381,7 @@ middleware that is specific to the route.
| `res.setHeader('Set-Cookie', val)` |
機能は基本的なクッキー値の設定に限定されるようになりました。 追加された 機能には、
- `res.cookie()` を使用します。
+ `res.cookie()` を使用します。 Use `res.cookie()` for added functionality.
|
@@ -369,6 +390,7 @@ middleware that is specific to the route.
Express 3アプリケーションをExpress 4に移行する例を以下に示します。
関心のあるファイルは `app.js` と `package.json` です。
+The files of interest are `app.js` and `package.json`.
### バージョン3アプリ
@@ -376,7 +398,7 @@ Express 3アプリケーションをExpress 4に移行する例を以下に示
次の `app.js` ファイルを含む Express v.3 アプリケーションを考えてみましょう。
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -410,6 +432,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
The accompanying version 3 `package.json` file might look
@@ -436,22 +492,20 @@ something like this:
Express 4アプリに必要なミドルウェアをインストールし、ExpressとPugを最新の
バージョンにアップデートして移行を開始します。
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
`app.js`に以下の変更を加えます。
-1. 組み込みの Express ミドルウェア関数 `express.favicon` ,
- `express.logger` , `express.methodOverride` ,
- `express.session` , `express.bodyParser` と
- `express.errorHandler` は、
- `express` オブジェクトでは使用できなくなりました。 代わりの
- を手動でインストールし、アプリにロードする必要があります。
+1. The built-in Express middleware functions `express.favicon`,
+ `express.logger`, `express.methodOverride`,
+ `express.session`, `express.bodyParser` and
+ `express.errorHandler` are no longer available on the
+ `express` object. You must install their alternatives
+ manually and load them in the app.
-2. `app.router`関数をロードする必要がなくなりました。
- 有効なExpress 4アプリオブジェクトではないため、
- `app.use(app.router);` コードを削除します。
+2. You no longer need to load the `app.router` function.
+ It is not a valid Express 4 app object, so remove the
+ `app.use(app.router);` code.
3. ミドルウェア関数が正しい順序でロードされていることを確認してください - アプリのルートをロードした後に `errorHandler` をロードします。
@@ -485,10 +539,10 @@ $ npm install serve-favicon morgan method-override express-session body-parser m
#### `app.js`
-次に、無効なコードを削除し、必要なミドルウェアをロードし、必要に応じて他の
-変更を行います。 `app.js`ファイルは次のようになります。
+Then, remove invalid code, load the required middleware, and make other
+changes as necessary. The `app.js` file will look like this:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -538,6 +592,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
`http` モジュール (socket.io/SPDY/HTTPS) で直接作業する必要がない限り、読み込みは必要ありません。この方法でアプリを起動できます。
@@ -552,7 +655,7 @@ app.listen(app.get('port'), () => {
### アプリの実行
移行処理が完了し、アプリは
-エクスプレス4アプリになりました。 確認するには、次のコマンドを使用してアプリを起動します。
+エクスプレス4アプリになりました。 確認するには、次のコマンドを使用してアプリを起動します。 To confirm, start the app by using the following command:
```bash
$ node .
@@ -573,18 +676,14 @@ the Express 3 app generator and then install the new
すでにExpress 3アプリジェネレータがシステムにインストールされている場合、
アンインストールする必要があります。
-```bash
-$ npm uninstall -g express
-```
+
ファイルとディレクトリ権限の設定に応じて、
`sudo` でこのコマンドを実行する必要があります。
新しいジェネレータをインストールします。
-```bash
-$ npm install -g express-generator
-```
+
ファイルとディレクトリ権限の設定に応じて、
`sudo` でこのコマンドを実行する必要があります。
@@ -630,12 +729,15 @@ Because the `app.js` file that was generated by the Express 4 generator
is now a Node.js module, it can no longer be started independently as an app
(unless you modify the code). モジュールは Node.js ファイル
にロードされ、Node.js ファイルを介して開始する必要があります。 Node.js ファイルは `./bin/www`
-です。
+です。 The Node.js file is `./bin/www`
+in this case.
Expressアプリの作成やアプリの起動には、`bin`ディレクトリも拡張機能のない`www`
ファイルも必須ではありません。 それらは
発電機による提案ですので、
-のニーズに合わせて変更してください。
+のニーズに合わせて変更してください。 They are
+just suggestions made by the generator, so feel free to modify them to suit your
+needs.
To get rid of the `www` directory and keep things the "Express 3 way",
delete the line that says `module.exports = app;` at the end of the
@@ -657,7 +759,8 @@ var debug = require('debug')('app4');
次に、 `start": `package.json` ファイル中の "node ./bin/www"` を `"start": "node app.js"` に変更します。
-これで `./bin/www` の機能を
+You have now moved the functionality of `./bin/www` back to
+`app.js`. これで `./bin/www` の機能を
`app.js` に戻しました。 This change is not recommended, but the exercise helps you
to understand how the `./bin/www` file works, and why the `app.js` file
no longer starts on its own.
diff --git a/src/content/pages/ja/guide/migrating-5.mdx b/src/content/pages/ja/guide/migrating-5.mdx
index 8ec04751cf..3997d49a21 100644
--- a/src/content/pages/ja/guide/migrating-5.mdx
+++ b/src/content/pages/ja/guide/migrating-5.mdx
@@ -4,18 +4,17 @@ description: Express.jsアプリケーションをバージョン4からバー
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-エクスプレス5はエクスプレス4と大きく異なりません。 同じ基本APIを維持していますが、以前のバージョンとの互換性を破る変更はまだあります。 したがって、Express 5を使用するように更新すると、Express 4で構築されたアプリケーションが動作しない可能性があります。
+エクスプレス5はエクスプレス4と大きく異なりません。 同じ基本APIを維持していますが、以前のバージョンとの互換性を破る変更はまだあります。 したがって、Express 5を使用するように更新すると、Express 4で構築されたアプリケーションが動作しない可能性があります。 したがって、Express 5を使用するように更新すると、Express 4で構築されたアプリケーションが動作しない可能性があります。
## インストール
-このバージョンをインストールするには、**Node.js version 18以上**が必要です。 次に、アプリケーションディレクトリで次のコマンドを実行します。
+このバージョンをインストールするには、**Node.js version 18以上**が必要です。 次に、アプリケーションディレクトリで次のコマンドを実行します。 次に、アプリケーションディレクトリで次のコマンドを実行します。
-```sh
-npm install "express@5"
-```
+
-その後、自動テストを実行して何が失敗するかを確認し、以下に示すアップデートに従って問題を解決することができます。 テストに失敗した後、どのエラーが発生したかを確認するためにアプリケーションを実行します。 サポートされていないメソッドやプロパティを使用している場合は、すぐに確認できます。
+その後、自動テストを実行して何が失敗するかを確認し、以下に示すアップデートに従って問題を解決することができます。 テストに失敗した後、どのエラーが発生したかを確認するためにアプリケーションを実行します。 サポートされていないメソッドやプロパティを使用している場合は、すぐに確認できます。 テストに失敗した後、どのエラーが発生したかを確認するためにアプリケーションを実行します。 サポートされていないメソッドやプロパティを使用している場合は、すぐに確認できます。
## Express 5 Codemods
@@ -23,15 +22,11 @@ npm install "express@5"
使用可能なすべてのコードを実行するには、次のコマンドを実行します。
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
特定のコードを実行したい場合は、次のコマンドを実行できます。
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
利用可能なコードリスト [here](https://codemod.link/express) があります。
@@ -41,17 +36,15 @@ npx codemod@latest @expressjs/name-of-the-codemod
### app.del()
-Express 5では、`app.del()`関数がサポートされなくなりました。 この関数を使うと、エラーがスローされます。 HTTP DELETEルートを登録するには、代わりに`app.delete()`関数を使用します。
+Express 5では、`app.del()`関数がサポートされなくなりました。 この関数を使うと、エラーがスローされます。 HTTP DELETEルートを登録するには、代わりに`app.delete()`関数を使用します。 この関数を使うと、エラーがスローされます。 HTTP DELETEルートを登録するには、代わりに`app.delete()`関数を使用します。
-`delete`はJavaScriptで予約されているキーワードであるため、最初は`delete`の代わりに`del`が使用されていました。 しかし、ECMAScript 6 では、 `delete` などの予約キーワードをプロパティ名として使用することができます。
+`delete`はJavaScriptで予約されているキーワードであるため、最初は`delete`の代わりに`del`が使用されていました。 しかし、ECMAScript 6 では、 `delete` などの予約キーワードをプロパティ名として使用することができます。 しかし、ECMAScript 6 では、 `delete` などの予約キーワードをプロパティ名として使用することができます。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
または、手動でコードを更新できます。
@@ -64,7 +57,7 @@ npx codemod@latest @expressjs/route-del-to-delete
### app.param(fn)
-`app.param(fn)`署名は、`app.param(name, fn)`関数の動作を変更するために使用されました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。
+`app.param(fn)`署名は、`app.param(name, fn)`関数の動作を変更するために使用されました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。
### 複数化されたメソッド名
@@ -80,9 +73,7 @@ npx codemod@latest @expressjs/route-del-to-delete
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
または、手動でコードを更新できます。
@@ -101,21 +92,19 @@ npx codemod@latest @expressjs/pluralize-method-names
### app.param(name, fn) の名前の先頭コロン (:)
-\`appの名前の先頭にあるコロン文字 (:) です。 aram(name, fn)関数はExpress 3の名残であり、後方互換性のため、Express 4は廃止予定の通知でサポートしています。 Express 5は黙って無視し、コロンをつけずに名前パラメータを使用します。
+\`appの名前の先頭にあるコロン文字 (:) です。 aram(name, fn)関数はExpress 3の名残であり、後方互換性のため、Express 4は廃止予定の通知でサポートしています。 Express 5は黙って無視し、コロンをつけずに名前パラメータを使用します。 Express 5は黙って無視し、コロンをつけずに名前パラメータを使用します。
-Express 4 の [app.param](/4x/api#app.param) のドキュメントに従っている場合、これはあなたのコードには影響しません。 主要な結腸については言及していません
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(name)
-これは、潜在的に混乱し、フォームデータを取得する危険な方法が削除されました。 ここで、`req.params`、`req.body`、または`req.query`オブジェクトの中で、送信されたパラメータ名を具体的に探す必要があります。
+これは、潜在的に混乱し、フォームデータを取得する危険な方法が削除されました。 これは、潜在的に混乱し、フォームデータを取得する危険な方法が削除されました。 ここで、`req.params`、`req.body`、または`req.query`オブジェクトの中で、送信されたパラメータ名を具体的に探す必要があります。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
または、手動でコードを更新できます。
@@ -134,15 +123,13 @@ npx codemod@latest @expressjs/explicit-request-params
### res.json(obj, status)
-Express 5 では署名 `res.json(obj, status)` がサポートされなくなりました。 代わりに、ステータスを設定し、 `res.json()` メソッドに次のようにチェーンさせます。`res.status(status).json(obj)` 。
+Express 5 では署名 `res.jsonp(obj, status)` がサポートされなくなりました。 代わりに、ステータスを設定し、 `res.jsonp()` メソッドを次のようにチェーンします。`res.status(status).jsonp(obj)` 。 Express 5 では署名 `res.json(obj, status)` がサポートされなくなりました。 代わりに、ステータスを設定し、 `res.json()` メソッドに次のようにチェーンさせます。`res.status(status).json(obj)` 。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
または、手動でコードを更新できます。
@@ -161,9 +148,7 @@ Express 5 では署名 `res.jsonp(obj, status)` がサポートされなくな
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
または、手動でコードを更新できます。
@@ -176,36 +161,37 @@ npx codemod@latest @expressjs/status-send-order
### res.redirect(url, status)
-Express 5 では署名 `res.redirect(url, status)` がサポートされなくなりました。 代わりに、`res.redirect(status, url)` という署名を使用します。
+Express 5 では署名 `res.redirect(url, status)` がサポートされなくなりました。 代わりに、`res.redirect(status, url)` という署名を使用します。 代わりに、`res.redirect(status, url)` という署名を使用します。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
または、手動でコードを更新できます。
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
### res.redirect('back') と res.location('back')
-Express 5では、`res.redirect()`と`res.location()`メソッドの魔法文字列`back`がサポートされなくなりました。 代わりに、 `req.get('Referrer') |'/'`の値を使用して前のページにリダイレクトします。 Express 4 では、`res.redirect('back')` と `res.location('back')` メソッドは廃止されました。
+Express 5では、`res.redirect()`と`res.location()`メソッドの魔法文字列`back`がサポートされなくなりました。 代わりに、 `req.get('Referrer') |'/'`の値を使用して前のページにリダイレクトします。 Express 4 では、`res.redirect('back')` と `res.location('back')` メソッドは廃止されました。 代わりに、 `req.get('Referrer') |'/'`の値を使用して前のページにリダイレクトします。 Express 4 では、`res.redirect('back')` と `res.location('back')` メソッドは廃止されました。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
または、手動でコードを更新できます。
@@ -218,15 +204,13 @@ npx codemod@latest @expressjs/back-redirect-deprecated
### res.send(body, status)
-Express 5 では署名 `res.send(obj, status)` がサポートされなくなりました。 代わりに、ステータスを設定し、 `res.status(status).send(obj)` のように、 `res.send()` メソッドを連鎖させます。
+Express 5 では署名 `res.send(obj, status)` がサポートされなくなりました。 代わりに、ステータスを設定し、 `res.status(status).send(obj)` のように、 `res.send()` メソッドを連鎖させます。 代わりに、ステータスを設定し、 `res.status(status).send(obj)` のように、 `res.send()` メソッドを連鎖させます。
#### 更新方法
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
または、手動でコードを更新できます。
@@ -246,9 +230,7 @@ Express 5では、`status` が数値である署名 `res.send(status)` がサポ
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
または、手動でコードを更新できます。
@@ -267,9 +249,7 @@ npx codemod@latest @expressjs/status-send-order
次のコマンドを実行することで、コードを自動的に更新できます。
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
または、手動でコードを更新できます。
@@ -282,7 +262,11 @@ npx codemod@latest @expressjs/camelcase-sendfile
### res.sendFile() オプション
-`res.sendFile()`の`hidden`と`from`オプションはサポートされなくなりました。 代わりに `dotfiles` と `root` を使用してください。
+`res.sendFile()`の`hidden`と`from`オプションはサポートされなくなりました。 代わりに `dotfiles` と `root` を使用してください。 代わりに `dotfiles` と `root` を使用してください。
+
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
#### 更新方法
@@ -293,12 +277,30 @@ npx codemod@latest @expressjs/camelcase-sendfile
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### express.static() オプション
-`express.static()`の`hidden`と`from`オプションはサポートされなくなりました。 代わりに `dotfiles` と `root` を使用してください。 `from`はAPIでは文書化されていませんが、`root`のエイリアスとして受け入れられています。 `dotfiles` のデフォルト値は `ignore"` になりました。
+`express.static()`の`hidden`と`from`オプションはサポートされなくなりました。 代わりに `dotfiles` と `root` を使用してください。 `from`はAPIでは文書化されていませんが、`root`のエイリアスとして受け入れられています。 `dotfiles` のデフォルト値は `ignore"` になりました。 代わりに `dotfiles` と `root` を使用してください。 `from`はAPIでは文書化されていませんが、`root`のエイリアスとして受け入れられています。 `dotfiles` のデフォルト値は `ignore"` になりました。
+
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
#### 更新方法
+次のコマンドを実行することで、コードを自動的に更新できます。
+
+
+
+または、手動でコードを更新できます。
+
```diff
const express = require('express');
const app = express();
@@ -307,14 +309,22 @@ npx codemod@latest @expressjs/camelcase-sendfile
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
-`router.param(fn)`署名は、`router.param(name, fn)`関数の動作を変更するために使用されました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。
+`router.param(fn)`署名は、`router.param(name, fn)`関数の動作を変更するために使用されました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。 v4.11.0以降非推奨となり、Express 5では全くサポートされなくなりました。
### express.static.mime
Express 5 では、`mime` は `static` フィールドのエクスポートされたプロパティではなくなりました。
MIME タイプの値を扱うには、[`mime-types` package](https://github.com/jshttp/mime-types) を使用します。
+MIME タイプの値を扱うには、[`mime-types` package](https://github.com/jshttp/mime-types) を使用します。
#### 更新方法
@@ -326,15 +336,15 @@ MIME タイプの値を扱うには、[`mime-types` package](https://github.com/
### MIMEタイプの変更
-[`mime-db`](https://github.com/jshttp/mime-db)の更新により、いくつかの MIME タイプが変更されました。 これらの変更は `express.static()` と `res.sendFile()` にのみ影響します。 変更の完全なリストについては、[`mime-db` changelog](https://github.com/jshttp/mime-db/blob/HEAD/HISTORY.md) を参照してください。
+[`mime-db`](https://github.com/jshttp/mime-db)の更新により、いくつかの MIME タイプが変更されました。 これらの変更は `express.static()` と `res.sendFile()` にのみ影響します。 [`mime-db`](https://github.com/jshttp/mime-db)の更新により、いくつかの MIME タイプが変更されました。 これらの変更は `express.static()` と `res.sendFile()` にのみ影響します。 変更の完全なリストについては、[`mime-db` changelog](https://github.com/jshttp/mime-db/blob/HEAD/HISTORY.md) を参照してください。
-Express 4 は `mime-db` バージョン **1.52.0** を使用し、Express 5 は IANA や その他のMIME タイプの仕様への更新を反映した新しいバージョンを使用します。 最も注目すべき変更は、JavaScript ファイル (`.js`) が `application/javascript` の代わりに `text/javascript` として提供されるようになったことです。
+Express 4 は `mime-db` バージョン **1.52.0** を使用し、Express 5 は IANA や その他のMIME タイプの仕様への更新を反映した新しいバージョンを使用します。 最も注目すべき変更は、JavaScript ファイル (`.js`) が `application/javascript` の代わりに `text/javascript` として提供されるようになったことです。 最も注目すべき変更は、JavaScript ファイル (`.js`) が `application/javascript` の代わりに `text/javascript` として提供されるようになったことです。
Express 5 では、`mime-db` アップデートからの MIME タイプへの変更は、壊れた変更とはみなされません。 MIMEタイプはマイナーバージョンやパッチバージョン間で変更される可能性があるため、依存関係を更新する際は注意が必要です。
### express:routerデバッグログ
-Expressチームが管理する別の依存関係([`router`](https://github.com/pillarjs/router)) によりルータの処理ロジックが実行されるようになりました。 デバッグログは別の名前空間に移動しました Express 5.1以前はデバッグログは存在しませんでした。 それらを取得するには、最新のExpress 5バージョンに更新するか、`package-lock.json`の`router`パッケージを更新してください。
+Expressチームが管理する別の依存関係([`router`](https://github.com/pillarjs/router)) によりルータの処理ロジックが実行されるようになりました。 デバッグログは別の名前空間に移動しました Express 5.1以前はデバッグログは存在しませんでした。 それらを取得するには、最新のExpress 5バージョンに更新するか、`package-lock.json`の`router`パッケージを更新してください。 Express 5.1以前はデバッグログは存在しませんでした。 それらを取得するには、最新のExpress 5バージョンに更新するか、`package-lock.json`の`router`パッケージを更新してください。
| v4 | v5 |
| -------------------------- | ----------------------------------- |
@@ -352,11 +362,11 @@ Expressチームが管理する別の依存関係([`router`](https://github.com/
## 変更済み
-これらの API はまだ存在しますが、動作は変更されています。 これらの変更を確認して、アプリが正常に動作することを確認してください。
+これらの API はまだ存在しますが、動作は変更されています。 これらの変更を確認して、アプリが正常に動作することを確認してください。 これらの変更を確認して、アプリが正常に動作することを確認してください。
### パス経路一致の構文
-パスルートマッチング構文は、文字列が`app.all()`、`app.use()`、`app.METHOD()`、`router.all()`、`router.METHOD()`、`router.METHOD()`、`router.METHOD()`、`router.use()` APIに最初のパラメータとして与えられた場合です。 パス文字列が受信リクエストと一致する方法を次のように変更しました:
+パスルートマッチング構文は、文字列が`app.all()`、`app.use()`、`app.METHOD()`、`router.all()`、`router.METHOD()`、`router.METHOD()`、`router.METHOD()`、`router.use()` APIに最初のパラメータとして与えられた場合です。 パス文字列が受信リクエストと一致する方法を次のように変更しました: パス文字列が受信リクエストと一致する方法を次のように変更しました:
- ワイルドカード`*`には名前が必要です。パラメータ`:`の動作に一致します。`/*`の代わりに`/*splat`を使用します。
@@ -369,7 +379,7 @@ Expressチームが管理する別の依存関係([`router`](https://github.com/
- `*spat` はルートパスのないパスにマッチします。 `/`と同様にルートパスをマッチさせる必要がある場合は、 `/{*spat}`を使用し、ワイルドカードを括弧で囲みます。
+ `*spat` はルートパスのないパスにマッチします。 `*spat` はルートパスのないパスにマッチします。 `/`と同様にルートパスをマッチさせる必要がある場合は、 `/{*spat}`を使用し、ワイルドカードを括弧で囲みます。
```js
app.get('/{*splat}', async (req, res) => {
@@ -388,7 +398,7 @@ Expressチームが管理する別の依存関係([`router`](https://github.com/
});
```
-- 正規表現文字はサポートされていません。 例:
+- 正規表現文字はサポートされていません。 例: 例:
```diff
-app.get('/[discussion|page]/:slug', async (req, res) => {
@@ -403,13 +413,13 @@ Expressチームが管理する別の依存関係([`router`](https://github.com/
### ミドルウェアとハンドラーから取り扱われる拒否された約束。
-rejected promiseを返すリクエストミドルウェアとハンドラは、「Error」として拒否された値をエラー処理ミドルウェアに転送することで処理されるようになりました。 つまり、 `async` 関数をミドルウェアとして、ハンドラを使うのはこれまで以上に簡単です。 `async` 関数でエラーがスローされるか、拒否された Promise が async 関数内で `await`ed になります。 これらのエラーは、`next(err)`を呼び出すかのようにエラーハンドラに渡されます。
+rejected promiseを返すリクエストミドルウェアとハンドラは、「Error」として拒否された値をエラー処理ミドルウェアに転送することで処理されるようになりました。 つまり、 `async` 関数をミドルウェアとして、ハンドラを使うのはこれまで以上に簡単です。 rejected promiseを返すリクエストミドルウェアとハンドラは、「Error」として拒否された値をエラー処理ミドルウェアに転送することで処理されるようになりました。 つまり、 `async` 関数をミドルウェアとして、ハンドラを使うのはこれまで以上に簡単です。 `async` 関数でエラーがスローされるか、拒否された Promise が async 関数内で `await`ed になります。 これらのエラーは、`next(err)`を呼び出すかのようにエラーハンドラに渡されます。
Express でのエラー処理の詳細については、[Error handling documentation](/guide/error-handling)を参照してください。
#### 更新方法
-手動でエラーをキャッチせずに `async/await` を直接使用できるようになりました。 `getUserById` がエラーまたは拒否をスローした場合、`next` は拒否された値で自動的に呼び出されます。
+手動でエラーをキャッチせずに `async/await` を直接使用できるようになりました。 手動でエラーをキャッチせずに `async/await` を直接使用できるようになりました。 `getUserById` がエラーまたは拒否をスローした場合、`next` は拒否された値で自動的に呼び出されます。
```diff
-app.get('/user/:id', (req, res, next) => {
@@ -442,16 +452,36 @@ Express でのエラー処理の詳細については、[Error handling document
#### 更新方法
-`dotfiles: "allow"`オプションを使用して、特定のドットディレクトリを明示的に提供します。 これにより、意図したドットディレクトリのみを安全に提供し、他のドットファイルのデフォルトの安全な動作を維持することができます。
+`dotfiles: "allow"`オプションを使用して、特定のドットディレクトリを明示的に提供します。 これにより、意図したドットディレクトリのみを安全に提供し、他のドットファイルのデフォルトの安全な動作を維持することができます。 これにより、意図したドットディレクトリのみを安全に提供し、他のドットファイルのデフォルトの安全な動作を維持することができます。
```diff
+app.use('/.well-known', express.static('public/.well-known', { dotfiles: 'allow' }));
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### 更新方法
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### app.listen
Express 5 では、サーバーがエラーイベントを受信したときに `app.listen` メソッドがユーザーが提供するコールバック関数を呼び出します。 Express 4では、そのようなエラーがスローされます。 この変更により、エラー処理の責任が Express 5 のコールバック関数に移行されます。 エラーがある場合は、コールバックに引数として渡されます。
+例: Express 4では、そのようなエラーがスローされます。 この変更により、エラー処理の責任が Express 5 のコールバック関数に移行されます。 エラーがある場合は、コールバックに引数として渡されます。
例:
```js ins={2-4}
@@ -465,11 +495,11 @@ const server = app.listen(8080, '0.0.0.0', (error) => {
### app.router
-Express 4 で削除された `app.router` オブジェクトは、Express 5 で復活しました。 新しいバージョンでは、このオブジェクトはベース Express ルータへの単なる参照です。 アプリが明示的にロードしなければならなかったExpress 3とは異なります。
+Express 4 で削除された `app.router` オブジェクトは、Express 5 で復活しました。 新しいバージョンでは、このオブジェクトはベース Express ルータへの単なる参照です。 アプリが明示的にロードしなければならなかったExpress 3とは異なります。 新しいバージョンでは、このオブジェクトはベース Express ルータへの単なる参照です。 アプリが明示的にロードしなければならなかったExpress 3とは異なります。
### req.body
-`req.body` プロパティは、本文が解析されていない場合に `undefined` を返します。 Express 4 ではデフォルトで `{}` を返します。
+`req.body` プロパティは、本文が解析されていない場合に `undefined` を返します。 Express 4 ではデフォルトで `{}` を返します。 Express 4 ではデフォルトで `{}` を返します。
```js del={4} ins={6}
app.post('/user', (req, res) => {
@@ -483,11 +513,11 @@ app.post('/user', (req, res) => {
### req.host
-Express 4では、`req.host`関数がポート番号を間違って剥奪しました。 Express 5ではポート番号が維持されています。
+Express 4では、`req.host`関数がポート番号を間違って剥奪しました。 Express 5ではポート番号が維持されています。 Express 5ではポート番号が維持されています。
### req.params
-`req.params` オブジェクトに文字列パスを使用する際に **null プロトタイプ** が追加されました。 しかし、パスが正規表現で定義されている場合、`req.params` は通常のプロトタイプを持つ標準オブジェクトのままです。 さらに、2つの重要な行動変更があります。
+`req.params` オブジェクトに文字列パスを使用する際に **null プロトタイプ** が追加されました。 しかし、パスが正規表現で定義されている場合、`req.params` は通常のプロトタイプを持つ標準オブジェクトのままです。 さらに、2つの重要な行動変更があります。 しかし、パスが正規表現で定義されている場合、`req.params` は通常のプロトタイプを持つ標準オブジェクトのままです。 さらに、2つの重要な行動変更があります。
**ワイルドカードパラメータは配列になりました:**
@@ -503,7 +533,7 @@ app.get('/*splat', (req, res) => {
**マッチしないパラメータは省略されました:**
-Express 4では、マッチしないワイルドカードは空文字列(`'`)であり、オプションのパラメータ(`?`を使用)には値が`undefined`のキーがありました。 Express 5 では、マッチしないパラメータは `req.params` から完全に省略されます。
+Express 4では、マッチしないワイルドカードは空文字列(`'`)であり、オプションのパラメータ(`?`を使用)には値が`undefined`のキーがありました。 Express 5 では、マッチしないパラメータは `req.params` から完全に省略されます。 Express 5 では、マッチしないパラメータは `req.params` から完全に省略されます。
```diff
-// v4: unmatched wildcard is empty string
@@ -530,7 +560,7 @@ Express 4では、マッチしないワイルドカードは空文字列(`'`)で
### req.query
-`req.query` プロパティはもはや書き込み可能なプロパティではなく、代わりにゲッターです。 デフォルトのクエリパーサが"extended"から"simple"に変更されました。
+`req.query` プロパティはもはや書き込み可能なプロパティではなく、代わりにゲッターです。 デフォルトのクエリパーサが"extended"から"simple"に変更されました。 デフォルトのクエリパーサが"extended"から"simple"に変更されました。
```js del={3}
app.get('/search', (req, res) => {
@@ -563,7 +593,7 @@ app.get('/user', (req, res) => {
### res.variable
-`field`引数がない場合、`res.vary`はエラーをスローします。 Express 4では、引数が省略された場合、コンソールに警告が表示されました。
+`field`引数がない場合、`res.vary`はエラーをスローします。 Express 4では、引数が省略された場合、コンソールに警告が表示されました。 Express 4では、引数が省略された場合、コンソールに警告が表示されました。
```js del={2}
app.get('/user', (req, res) => {
diff --git a/src/content/pages/ja/resources/community.mdx b/src/content/pages/ja/resources/community.mdx
index 89b4dc8851..3964581ebe 100644
--- a/src/content/pages/ja/resources/community.mdx
+++ b/src/content/pages/ja/resources/community.mdx
@@ -10,6 +10,8 @@ import LogoDisplay from '@components/patterns/LogoDisplay/LogoDisplay.astro';
Express技術委員会は、(必要に応じて)2週間ごとにオンラインで開催し、Expressの開発とメンテナンスについて議論します。
およびエクスプレスプロジェクトに関連するその他の問題。 Each meeting is typically announced in an
[expressjs/discussions issue](https://github.com/expressjs/discussions/issues) with a link to join or view the meeting, which is
+open to all observers. Each meeting is typically announced in an
+[expressjs/discussions issue](https://github.com/expressjs/discussions/issues) with a link to join or view the meeting, which is
open to all observers.
会議は記録されます。録音の一覧は、[Express.jsのYouTubeチャンネル](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g)を参照してください。
@@ -63,7 +65,7 @@ API の設計や認証からテンプレートエンジンの統合まで、す
## Express.jsロゴ
-ExpressはOpenJS財団のプロジェクトです。 Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Express.js logos and marks.
+ExpressはOpenJS財団のプロジェクトです。 ExpressはOpenJS財団のプロジェクトです。 Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Express.js logos and marks.
### ワードマーク
diff --git a/src/content/pages/ja/resources/contributing.mdx b/src/content/pages/ja/resources/contributing.mdx
index 86c6741534..017a31d6c7 100644
--- a/src/content/pages/ja/resources/contributing.mdx
+++ b/src/content/pages/ja/resources/contributing.mdx
@@ -5,11 +5,11 @@ description: Express.jsに貢献する方法については、問題の報告、
import Alert from '@components/primitives/Alert/Alert.astro';
-Express is an [OpenJS Foundation](https://openjsf.org/) project spread across three GitHub organizations: [expressjs](https://github.com/expressjs), [pillarjs](https://github.com/pillarjs), and [jshttp](https://github.com/jshttp). バグの報告、ドキュメントの改善、コードの提出など、すべての貢献は歓迎します。 以下のガイドラインでは、プロジェクトの運営方法と参加方法について説明します。
+Express is an [OpenJS Foundation](https://openjsf.org/) project spread across three GitHub organizations: [expressjs](https://github.com/expressjs), [pillarjs](https://github.com/pillarjs), and [jshttp](https://github.com/jshttp). バグの報告、ドキュメントの改善、コードの提出など、すべての貢献は歓迎します。 以下のガイドラインでは、プロジェクトの運営方法と参加方法について説明します。 以下のガイドラインでは、プロジェクトの運営方法と参加方法について説明します。
## 技術委員会
-Express技術委員会は、アクティブなプロジェクトメンバーで構成され、Expressプロジェクトの開発とメンテナンスをガイドします。 詳細については、[Express Community - Technical Committee](/resources/community/#technical-committee)を参照してください。
+Express技術委員会は、アクティブなプロジェクトメンバーで構成され、Expressプロジェクトの開発とメンテナンスをガイドします。 詳細については、[Express Community - Technical Committee](/resources/community/#technical-committee)を参照してください。 For more information, see [Express Community - Technical committee](/resources/community/#technical-committee).
## コミュニティ貢献ガイド
@@ -33,20 +33,22 @@ Express技術委員会は、アクティブなプロジェクトメンバーで
### ログの問題
-質問または問題の問題を記録します。 When in doubt, log an issue, and
+質問または問題の問題を記録します。 質問または問題の問題を記録します。 When in doubt, log an issue, and
any additional policies about what to include will be provided in the responses. 唯一
例外は、私的に送信されるべきセキュリティディスクロージャーです。
コミッターはあなたを別のリポジトリに誘導し、追加の説明を求め、問題が解決される前に
適切なメタデータを追加することができます。
-礼儀正しく、尊敬してください。 すべての参加者は、
+礼儀正しく、尊敬してください。 礼儀正しく、尊敬してください。 すべての参加者は、
プロジェクトの行動規範に従うことが期待されます。
### 貢献
このリポジトリのリソースへの変更は、プルリクエストでなければなりません。 これは、ドキュメント、コード、バイナリファイルなどのすべての変更
に適用されます。 長期的なコミッターやTCメンバーであっても、
+プルリクエストを使用する必要があります。 これは、ドキュメント、コード、バイナリファイルなどのすべての変更
+に適用されます。 長期的なコミッターやTCメンバーであっても、
プルリクエストを使用する必要があります。
レビューされずにプルリクエストをマージすることはできません。
@@ -55,11 +57,15 @@ any additional policies about what to include will be provided in the responses.
貢献者がレビューする時間があることを確認するために、プルリクエストは少なくとも36時間座る必要があります。
の週末やその他の休暇期間にも配慮しなければならず、アクティブなコミッターが
議論とレビューのプロセスに参加するまでの合理的な時間を確保することができます。
+の週末やその他の休暇期間にも配慮しなければならず、アクティブなコミッターが
+議論とレビューのプロセスに参加するまでの合理的な時間を確保することができます。
+各コントリビューションのデフォルトは、コミッターが異議を持たない場合に受け入れられることです。
各コントリビューションのデフォルトは、コミッターが異議を持たない場合に受け入れられることです。
During a review, committers may also request that a specific contributor who is most versed in a
particular area gives a "LGTM" before the PR can be merged. 土地への貢献のための追加の「サインオフ」
プロセスはありません。 Once all issues brought by committers are addressed it can
+be landed by any committer. Once all issues brought by committers are addressed it can
be landed by any committer.
別のコミッターによってプルリクエストで異議が提起された場合。
@@ -74,7 +80,7 @@ be landed by any committer.
### Triager になる
-誰でもトリアージになれます!
+誰でもトリアージになれます! 誰でもトリアージになれます!
[triage process document](https://github.com/expressjs/discussions/blob/HEAD/contributing/triager-guide.md)でトリガーになるプロセスの詳細をお読みください。
Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate
@@ -108,23 +114,28 @@ TCは、TCにエスカレートされた問題について「コンセンサス
会議では、その会議中に議題に関するすべての問題が解決されることは期待されておらず、プロジェクトキャプテン間で起こっている議論を
継続することを好むかもしれません。
-メンバーはいつでもTCに追加できます。 Any TC member can nominate another committer
+メンバーはいつでもTCに追加できます。 メンバーはいつでもTCに追加できます。 Any TC member can nominate another committer
to the TC and the TC uses its standard consensus seeking process to evaluate whether or
not to add this new member. TCは、最低3人のアクティブメンバーと最大10の
+で構成されます。 TCは、最低3人のアクティブメンバーと最大10の
で構成されます。 TCが5人未満の場合、アクティブなTCメンバーは
新しい誰かを指名する必要があります。 TCメンバーが辞任している場合、彼らは
+誰かに代わってもらうように指名することを奨励されます(必須ではありません)。 TCメンバーが辞任している場合、彼らは
誰かに代わってもらうように指名することを奨励されます(必須ではありません)。
TCメンバーは、役割で有効であるために必要な
としてGithub組織、npm組織、およびその他のリソースに管理者として追加されます。
TCメンバーが過去12ヶ月以内に参加し、
+連続したTCミーティングを見逃す必要があります。 TCメンバーが過去12ヶ月以内に参加し、
連続したTCミーティングを見逃す必要があります。 Our goal is to increase participation, not punish
people for any lack of participation, this guideline should be only be used as such
(replace an inactive member with a new active one, for example). この
+を満たしていないメンバーは辞退することが求められます。 この
を満たしていないメンバーは辞退することが求められます。 TCメンバーがステップダウンしない場合、
ディスカッションリポジトリで問題を開き、それらを非アクティブ状態に移動できます。
により停止または削除されたTCメンバーは、非アクティブ状態に移動されます。
+により停止または削除されたTCメンバーは、非アクティブ状態に移動されます。
Inactive status members can become active members by self nomination if the TC is not already
larger than the maximum of 10. 最大サイズで、
@@ -150,6 +161,7 @@ TCメンバーと同じように、レポキャプテンはコミッターの一
がGitHubとNPMの両方のアカウントで2FAを有効にしている必要があります。
**同じ**リポジトリのTCメンバーまたは既存のキャプテンは、キャプテン役に別のコミッター
+を指名することができます。 **同じ**リポジトリのTCメンバーまたは既存のキャプテンは、キャプテン役に別のコミッター
を指名することができます。 そのためには、この文書にPRを提出する必要があります。
**アクティブなプロジェクトキャプテン** セクション (並び替え順を維持しながら) をプロジェクト
名で更新します。 ノミネート者のGitHubハンドルとそのnpmユーザー名 (異なる場合)。
@@ -160,6 +172,7 @@ TCメンバーと同じように、レポキャプテンはコミッターの一
PRは、TCメンバーから少なくとも2件の承認が必要であり、コメントおよび/または反対のために
を許可する2週間の保留期間が必要です。 PRがマージされると、TCメンバーはそれを
+適切なGitHub/npmグループに追加します。 PRがマージされると、TCメンバーはそれを
適切なGitHub/npmグループに追加します。
#### アクティブなプロジェクトとキャプテンズ
@@ -256,11 +269,13 @@ Expressの将来のリリースである
see listed.
6. テストが合格した場合、変更をフォークに反映し、そこから
プルリクエストを作成することができます。 Issue 番号を含めることで、プル
+ リクエストのコメントを参照してください。例:`#123`。 Issue 番号を含めることで、プル
リクエストのコメントを参照してください。例:`#123`。
### 質問である問題
私たちは通常、あなたが書いているいくつかの
+アプリに固有の漠然とした問題や質問を閉じます。 私たちは通常、あなたが書いているいくつかの
アプリに固有の漠然とした問題や質問を閉じます。 Please double check the docs and other references before
being trigger happy with posting a question issue.
@@ -306,6 +321,9 @@ Expressチームとコミュニティは、すべてのセキュリティ脆弱
Express および関連プロジェクトのセキュリティを向上させていただきありがとうございます。
We appreciate your efforts in responsible disclosure and will make every effort
to acknowledge your contributions.
+Express および関連プロジェクトのセキュリティを向上させていただきありがとうございます。
+We appreciate your efforts in responsible disclosure and will make every effort
+to acknowledge your contributions.
A [Security triage team member](https://github.com/expressjs/security-wg#security-triage-team-expressjssecurity-triage)
or [the repo captain](https://github.com/expressjs/discussions/blob/master/docs/contributing/captains_and_committers.md)
@@ -329,6 +347,8 @@ You can find more information about our process in [this guide](https://github.c
[GitHub Security Advisories](https://github.com/advisories)を使用します。
これにより、報告書の
の機密性を維持しながら修正に協力することができます。
+これにより、報告書の
+の機密性を維持しながら修正に協力することができます。
脆弱性
([docs](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability) を報告するには:
@@ -336,6 +356,7 @@ You can find more information about our process in [this guide](https://github.c
1. 影響を受けるリポジトリの **セキュリティ** タブを開きます。
2. **脆弱性を報告**をクリックし、指定された手順に従ってください。
+このプロセスは、Express エコシステム内のリポジトリに適用されます。
このプロセスは、Express エコシステム内のリポジトリに適用されます。
If you are unsure whether a repository falls under this policy,
feel free to reach out via email.
@@ -346,7 +367,7 @@ feel free to reach out via email.
タイムリーな対応を確実にするために、外部ソースにリンクしたりファイルを添付したりするのではなく、関連するすべての詳細をメール本文に直接記入してください。
-リードメンテナは48時間以内にあなたのメールを認識し、次のステップの概要を説明する最初の回答を提供します。 セキュリティチームは、進捗状況を更新し続け、追加の詳細を要求することがあります。
+リードメンテナは48時間以内にあなたのメールを認識し、次のステップの概要を説明する最初の回答を提供します。 セキュリティチームは、進捗状況を更新し続け、追加の詳細を要求することがあります。 セキュリティチームは、進捗状況を更新し続け、追加の詳細を要求することがあります。
#### サードパーティーモジュール
@@ -356,6 +377,7 @@ feel free to reach out via email.
セキュリティチームがセキュリティバグレポートを受け取ると、セキュリティバグレポートは
プライマリハンドラに割り当てられます。 This person will coordinate the fix and release process,
+involving the following steps: This person will coordinate the fix and release process,
involving the following steps:
- 問題を確認し、影響を受けるバージョンを確認します。
@@ -370,7 +392,7 @@ involving the following steps:
### Express 脅威モデル
-Express脅威モデルは、フレームワークがセキュリティ責任を考慮している限界を定義します。 信頼される要素(開発者、ランタイム環境、アプリケーションコードなど)と信頼されない要素(ネットワーク接続からのデータなど)を決定します。 信頼された要素から生じる問題は範囲外とみなされ、Express は信頼されていないデータを安全に処理する責任を負います。
+Express脅威モデルは、フレームワークがセキュリティ責任を考慮している限界を定義します。 信頼される要素(開発者、ランタイム環境、アプリケーションコードなど)と信頼されない要素(ネットワーク接続からのデータなど)を決定します。 信頼された要素から生じる問題は範囲外とみなされ、Express は信頼されていないデータを安全に処理する責任を負います。 信頼される要素(開発者、ランタイム環境、アプリケーションコードなど)と信頼されない要素(ネットワーク接続からのデータなど)を決定します。 信頼された要素から生じる問題は範囲外とみなされ、Express は信頼されていないデータを安全に処理する責任を負います。
一般的に報告されている懸念の多くは、Expressのセキュリティ範囲外であり、アプリケーション開発者の責任です。 アンサニタイズされたユーザー入力からのプロトタイプ汚染、誤った設定された静的ファイルの提供、サードパーティーの依存関係での問題など。
diff --git a/src/content/pages/ja/resources/glossary.mdx b/src/content/pages/ja/resources/glossary.mdx
index 44aedb54e7..0ffed9d49e 100644
--- a/src/content/pages/ja/resources/glossary.mdx
+++ b/src/content/pages/ja/resources/glossary.mdx
@@ -7,15 +7,15 @@ import Alert from '@components/primitives/Alert/Alert.astro';
## アプリケーション
-一般に、特定の目的のために操作を実行するように設計された1つまたは複数のプログラム。 Express のコンテキストでは、Node.js プラットフォームで実行される Express API を使用するプログラムがあります。 [app object](/api#express) も参照しているかもしれません。
+一般に、特定の目的のために操作を実行するように設計された1つまたは複数のプログラム。 一般に、特定の目的のために操作を実行するように設計された1つまたは複数のプログラム。 Express のコンテキストでは、Node.js プラットフォームで実行される Express API を使用するプログラムがあります。 [app object](/api#express) も参照しているかもしれません。 Might also refer to an [app object](/api/express).
## API
-アプリケーションプログラミングインターフェイス。 略語が最初に使用されたときにスペルアウトします。
+アプリケーションプログラミングインターフェイス。 略語が最初に使用されたときにスペルアウトします。 略語が最初に使用されたときにスペルアウトします。
## エクスプレス
-Node.jsアプリケーション用の高速で、意見が異なる、ミニマリストなWebフレームワーク。 一般的には「Express」は「Express.js」よりも好まれますが、後者は許容されます。
+Node.jsアプリケーション用の高速で、意見が異なる、ミニマリストなWebフレームワーク。 一般的には「Express」は「Express.js」よりも好まれますが、後者は許容されます。 一般的には「Express」は「Express.js」よりも好まれますが、後者は許容されます。
## libuv
@@ -23,19 +23,19 @@ Node.jsアプリケーション用の高速で、意見が異なる、ミニマ
## middleware
-最後のリクエストハンドラの前に Express ルーティング層によって呼び出される関数 生の要求と最終目的のルートの間に座っています ミドルウェアに関する用語のいくつかの細かい点:
+最後のリクエストハンドラの前に Express ルーティング層によって呼び出される関数 生の要求と最終目的のルートの間に座っています ミドルウェアに関する用語のいくつかの細かい点: ミドルウェアに関する用語のいくつかの細かい点:
-- `var foo = require('middleware')` は Node.js モジュールの _requiring_ または _using_ と呼ばれます。 `var mw = foo()`という文は通常、ミドルウェアを返します。
+- `var foo = require('middleware')` は Node.js モジュールの _requiring_ または _using_ と呼ばれます。 `var mw = foo()`という文は通常、ミドルウェアを返します。 `var mw = foo()`という文は通常、ミドルウェアを返します。
- `app.use(mw)`は、ミドルウェアをグローバルな処理スタックに追加することを呼びます。
-- `app.get('/foo', mw, function (req, res) { ... })` は、ミドルウェアを "GET /foo" 処理の stack\_ に追加すると呼ばれます。
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
-スケーラブルなネットワークアプリケーションの構築に使用されるソフトウェアプラットフォーム。 Node.jsはJavaScriptをスクリプト言語として使用し、ノンブロッキングI/Oとシングルスレッドイベントループにより高いスループットを実現します。 [nodejs.org](https://nodejs.org/en/) を参照してください。 **使用上の注意**: 最初は、"Node.js"以降は"Node"です。
+スケーラブルなネットワークアプリケーションの構築に使用されるソフトウェアプラットフォーム。 スケーラブルなネットワークアプリケーションの構築に使用されるソフトウェアプラットフォーム。 Node.jsはJavaScriptをスクリプト言語として使用し、ノンブロッキングI/Oとシングルスレッドイベントループにより高いスループットを実現します。 [nodejs.org](https://nodejs.org/en/) を参照してください。 **使用上の注意**: 最初は、"Node.js"以降は"Node"です。 [nodejs.org](https://nodejs.org/en/) を参照してください。 **使用上の注意**: 最初は、"Node.js"以降は"Node"です。
## オープンソースのオープンソース
-形容詞として使われる場合、ハイフネートなど。例: "これはオープンソースソフトウェアです。 [Wikipediaのオープンソースソフトウェア](http://en.wikipedia.org/wiki/Open-source_software)を参照してください。
+形容詞として使われる場合、ハイフネートなど。例: "これはオープンソースソフトウェアです。 [Wikipediaのオープンソースソフトウェア](http://en.wikipedia.org/wiki/Open-source_software)を参照してください。 See [Open-source software on Wikipedia](https://en.wikipedia.org/wiki/Open-source_software).
@@ -46,7 +46,7 @@ Node.jsアプリケーション用の高速で、意見が異なる、ミニマ
## リクエスト
-HTTP リクエスト。 クライアントは、レスポンスを返すサーバーに HTTP リクエストメッセージを送信します。 リクエストは、GET、POST など、いくつかの [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) のうちの 1 つを使用する必要があります。
+HTTP リクエスト。 HTTPレスポンス。 サーバーはクライアントに HTTP 応答メッセージを返します。 レスポンスには、リクエストに関する完了ステータス情報が含まれており、メッセージ本文に要求されたコンテンツが含まれている場合もあります。 The request must use one of several [request methods](https://en.wikipedia.org/wiki/HTTP#Request_methods) such as GET, POST, and so on.
## 応答
@@ -54,7 +54,7 @@ HTTPレスポンス。 サーバーはクライアントに HTTP 応答メッセ
## route
-リソースを識別する URL の一部です。 例えば、`http://foo.com/products/id`では、"/products/id"がルートです。
+リソースを識別する URL の一部です。 リソースを識別する URL の一部です。 例えば、`http://foo.com/products/id`では、"/products/id"がルートです。
## ルーター:
diff --git a/src/content/pages/ja/resources/index.mdx b/src/content/pages/ja/resources/index.mdx
index db22ead333..4aed843d21 100644
--- a/src/content/pages/ja/resources/index.mdx
+++ b/src/content/pages/ja/resources/index.mdx
@@ -6,7 +6,7 @@ description: コミュニティ、ガイドライン、用語集、ユーティ
import Card from '@components/primitives/Card/Card.astro';
import { CardList } from '@components/patterns';
-Express.jsエコシステムを学び、貢献し、接続するためのリソースを見つけましょう。 コミュニティに参加したい場合、ミドルウェアを探索したり、重要な概念を理解したりする場合でも、ここで必要なものが見つかります。
+Express.jsエコシステムを学び、貢献し、接続するためのリソースを見つけましょう。 コミュニティに参加したい場合、ミドルウェアを探索したり、重要な概念を理解したりする場合でも、ここで必要なものが見つかります。 コミュニティに参加したい場合、ミドルウェアを探索したり、重要な概念を理解したりする場合でも、ここで必要なものが見つかります。
@@ -23,7 +23,7 @@ Express.jsエコシステムを学び、貢献し、接続するためのリソ
diff --git a/src/content/pages/ja/resources/middleware/body-parser.mdx b/src/content/pages/ja/resources/middleware/body-parser.mdx
index 56856f2549..e04236df0f 100644
--- a/src/content/pages/ja/resources/middleware/body-parser.mdx
+++ b/src/content/pages/ja/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Node.js body parsing middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ and `toString` may not be a function and instead a string or other user input.
## インストール
-```sh
-$ npm install body-parser
-```
+
## API
@@ -110,8 +109,8 @@ the following keys:
##### reviver
2番目の
-引数として`リバイバー`オプションは直接`JSON.parse`に渡されます。 この引数
-[JSON.parseに関するMDN ドキュメント](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter) に詳しい情報があります。
+引数として`リバイバー`オプションは直接`JSON.parse`に渡されます。 You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### 厳格な
diff --git a/src/content/pages/ja/resources/middleware/compression.mdx b/src/content/pages/ja/resources/middleware/compression.mdx
index 8c2da8fee0..7cca5a25f4 100644
--- a/src/content/pages/ja/resources/middleware/compression.mdx
+++ b/src/content/pages/ja/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js compression ミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/cookie-parser.mdx b/src/content/pages/ja/resources/middleware/cookie-parser.mdx
index e679355a47..b8e48198f1 100644
--- a/src/content/pages/ja/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/ja/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: HTTP リクエストクッキーを解析
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/cookie-session.mdx b/src/content/pages/ja/resources/middleware/cookie-session.mdx
index ea2178e9e0..03fef92888 100644
--- a/src/content/pages/ja/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/ja/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookieセッションミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
@@ -71,16 +72,15 @@ app.use(
### cookieSession(options)
-指定されたオプションで新しいcookieセッションミドルウェアを作成します。 This middleware
+指定されたオプションで新しいcookieセッションミドルウェアを作成します。 指定されたオプションで新しいcookieセッションミドルウェアを作成します。 This middleware
will attach the property `session` to `req`, which provides an object representing
the loaded session. このセッションは、リクエストで有効なセッションが
提供されなかった場合、またはリクエストからロードされたセッションのいずれかである。
-`req.session`の
-内容が変更された場合、ミドルウェアは自動的に`Set-Cookie`ヘッダーをレスポンスに追加します。 _Note_ that no `Set-Cookie` header will be
-in the response (and thus no session created for a specific user) unless there are
-contents in the session, so be sure to add something to `req.session` as soon as
-you have identifying information to store for the session.
+This module does not send a `Set-Cookie` header if the contents of the session
+have not changed. This means that to extend the expiration of a session in the
+user's browser (in response to user activity, for example) some kind of
+modification to the session needs be made.
#### オプション
@@ -96,6 +96,9 @@ Cookie の値の署名と検証に使用するキーのリスト、または設
[`Keygrip`](https://www.npmjs.com/package/keygrip) インスタンス。 Cookieは常に
`keys[0]`で署名されますが、他のキーは検証に有効です。
キーの回転を許可します。 `Keygrip` インスタンスが指定されている場合、
+署名のアルゴリズムのように署名パラメータを変更することができます。 Cookieは常に
+`keys[0]`で署名されますが、他のキーは検証に有効です。
+キーの回転を許可します。 `Keygrip` インスタンスが指定されている場合、
署名のアルゴリズムのように署名パラメータを変更することができます。
##### シークレット
@@ -114,10 +117,10 @@ Cookie の値の署名と検証に使用するキーのリスト、または設
- `expires`: Cookieの有効期限を示す`Date`オブジェクト(デフォルトではセッション終了時に有効期限が切れます)。
- `path`: クッキーのパスを示す文字列(デフォルトでは `/`)。
- `domain`: Cookie のドメインを示す文字列 (デフォルトではありません)。
-- `partitioned`: [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (デフォルトでは `false` )のためにChromeのクッキーを分割するかどうかを示すブール値。 これがtrueの場合、埋め込まれたサイトからのCookieは分割され、作成された同じトップレベルのサイトからのみ読み込み可能になります。
-- `priority`: Cookie の優先度を示す文字列。 これは`'low'`、`'medium'`、または`'high'`に設定できます。
-- `sameSite`: クッキーが「同じサイト」クッキーであるかどうかを示す真偽値または文字列(デフォルトでは`false`)。 これは`'strict'`、`'lax'`、`'none'`、`true`('strict'にマップされます)に設定できます。
-- `secure`: CookieがHTTPSでのみ送信されるかどうかを示すブール値 (HTTPでは`false`、HTTPSではデフォルトでは`true`)。 `true` と Node に設定されている場合。 sはTLS接続上で直接ではありません。 [set Express behind proxies](/guide/behind-proxies)またはクッキーが正しく設定されていない可能性があります。
+- `partitioned`: [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (デフォルトでは `false` )のためにChromeのクッキーを分割するかどうかを示すブール値。 これがtrueの場合、埋め込まれたサイトからのCookieは分割され、作成された同じトップレベルのサイトからのみ読み込み可能になります。 これがtrueの場合、埋め込まれたサイトからのCookieは分割され、作成された同じトップレベルのサイトからのみ読み込み可能になります。
+- `priority`: Cookie の優先度を示す文字列。 これは`'low'`、`'medium'`、または`'high'`に設定できます。 これは`'low'`、`'medium'`、または`'high'`に設定できます。
+- `sameSite`: クッキーが「同じサイト」クッキーであるかどうかを示す真偽値または文字列(デフォルトでは`false`)。 これは`'strict'`、`'lax'`、`'none'`、`true`('strict'にマップされます)に設定できます。 これは`'strict'`、`'lax'`、`'none'`、`true`('strict'にマップされます)に設定できます。
+- `secure`: CookieがHTTPSでのみ送信されるかどうかを示すブール値 (HTTPでは`false`、HTTPSではデフォルトでは`true`)。 `secure`: CookieがHTTPSでのみ送信されるかどうかを示すブール値 (HTTPでは`false`、HTTPSではデフォルトでは`true`)。 `true` と Node に設定されている場合。 sはTLS接続上で直接ではありません。 [set Express behind proxies](/guide/behind-proxies)またはクッキーが正しく設定されていない可能性があります。
- `httpOnly`: CookieがHTTP(S)経由でのみ送信されるかどうかを示すブール値で、クライアントJavaScript(デフォルトでは`true`)では使用できません。
- `signed`: Cookie を署名するかどうかを示す boolean (デフォルトでは `true` )。
- `overwrite`: 以前に同じ名前のクッキーを上書きするかどうかを示す boolean (デフォルトは `true` )。
@@ -140,7 +143,7 @@ Cookie の値の署名と検証に使用するキーのリスト、または設
### req.sessionOptions
-現在のリクエストのセッションオプションを表します。 これらのオプションはミドルウェア構築時に提供されたものの
+現在のリクエストのセッションオプションを表します。 現在のリクエストのセッションオプションを表します。 これらのオプションはミドルウェア構築時に提供されたものの
浅いクローンです。
リクエストごとにクッキー設定の動作を変更するために変更することができます。
@@ -154,6 +157,8 @@ req.session = null;
### セッションを保存中
+セッションの内容全体がクライアント側の Cookie に保持されるため、
+セッションは、`Set-Cookie` レスポンスヘッダーにクッキーを書き出すことによって「保存」されます。
セッションの内容全体がクライアント側の Cookie に保持されるため、
セッションは、`Set-Cookie` レスポンスヘッダーにクッキーを書き出すことによって「保存」されます。
This is done automatically if there has been a change made to the session when
@@ -274,8 +279,7 @@ app.use(
### クッキーの最大サイズ
Because the entire session object is encoded and stored in a cookie, it is
-possible to exceed the maximum cookie size limits on different browsers.
-[RFC6265 仕様](https://tools.ietf.org/html/rfc6265#section-6.1)
+possible to exceed the maximum cookie size limits on different browsers. [RFC6265 仕様](https://tools.ietf.org/html/rfc6265#section-6.1)
ブラウザーが **SHOULD** を許可することをお勧めします
> クッキーあたり少なくとも4096バイト(クッキーの名前、値、属性の
@@ -289,11 +293,15 @@ possible to exceed the maximum cookie size limits on different browsers.
はほとんどの場合、ブラウザはクッキーの保存を拒否します。 これにより、
ブラウザからのリクエストは、a) セッション
情報がない、またはb)
+クッキーの制限を超えないように小さい古いセッション情報を使用します。 これにより、
+ブラウザからのリクエストは、a) セッション
+情報がない、またはb)
クッキーの制限を超えないように小さい古いセッション情報を使用します。
セッションオブジェクトがこれらの制限に達している場合、
セッション内のデータを、リクエストごとにブラウザから送信するのではなく、
サーバー上のデータベースからロードするかどうかを検討することをお勧めします。 または、
+[alternative session strategy](https://github.com/expressjs/session#compatible-session-stores) に移動します。 または、
[alternative session strategy](https://github.com/expressjs/session#compatible-session-stores) に移動します。
## ライセンス
diff --git a/src/content/pages/ja/resources/middleware/cors.mdx b/src/content/pages/ja/resources/middleware/cors.mdx
index 2cee8c73bb..f2ef20296a 100644
--- a/src/content/pages/ja/resources/middleware/cors.mdx
+++ b/src/content/pages/ja/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. これらのヘッダーは、どのオリジンがサーバから応答を読み取れるかをブラウザーに伝えます。
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. これらのヘッダーは、どのオリジンがサーバから応答を読み取れるかをブラウザーに伝えます。
@@ -39,9 +40,7 @@ CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://exp
[npm registry](https://www.npmjs.com/) を介して利用できます。 インストールは
[`npm install` コマンド](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## 使用法
diff --git a/src/content/pages/ja/resources/middleware/errorhandler.mdx b/src/content/pages/ja/resources/middleware/errorhandler.mdx
index 118e4ca371..cc094ec6cc 100644
--- a/src/content/pages/ja/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/ja/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: 開発専用エラーハンドラミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/index.mdx b/src/content/pages/ja/resources/middleware/index.mdx
new file mode 100644
index 0000000000..266c6cdae6
--- /dev/null
+++ b/src/content/pages/ja/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | 説明 |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ この情報は、
+ Expressjsチームがメンテナンスしていないサードパーティのサイト、製品、またはモジュールを指します。
+ ここでの掲載は、 Expressjsプロジェクトチームの推奨または推奨を構成するものではありません。
+
+
+| Middleware module | 説明 |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/ja/resources/middleware/method-override.mdx b/src/content/pages/ja/resources/middleware/method-override.mdx
index 13df67dc25..3e7cf63890 100644
--- a/src/content/pages/ja/resources/middleware/method-override.mdx
+++ b/src/content/pages/ja/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: HTTP 動詞を上書き
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/morgan.mdx b/src/content/pages/ja/resources/middleware/morgan.mdx
index 3325870970..aca731180a 100644
--- a/src/content/pages/ja/resources/middleware/morgan.mdx
+++ b/src/content/pages/ja/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: Node.js 用の HTTP リクエストロガーミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ HTTPリクエストロガーミドルウェア for node.js
[npm registry](https://www.npmjs.com/) を介して利用できます。 インストールは
[`npm install` コマンド](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ UTCの現在の日付と時刻。 利用可能なフォーマットは次のと
リクエストの HTTP バージョン。
-##### :method
+#####
リクエストの HTTP メソッド。
-##### :pid
+#####
Node.js プロセスのプロセス ID がリクエストを処理します。
-##### :referrer
+#####
リクエストの Referrer ヘッダー。 これは、標準のスペルの間違いの Referer ヘッダが存在する場合に使用します。そうでなければ、Referrerです。
@@ -239,7 +238,7 @@ Node.js プロセスのプロセス ID がリクエストを処理します。
引数`digit`は、数字に
を含める桁数を指定する数値で、マイクロ秒の精度を提供する`3`をデフォルト値とします。
-##### :status
+#####
レスポンスのステータスコード。
@@ -255,7 +254,7 @@ the request), then the status will be empty (displayed as `"-"` in the log).
引数`digit`は、数字に
を含める桁数を指定する数値で、マイクロ秒の精度を提供する`3`をデフォルト値とします。
-##### :url
+#####
リクエストの URL `req.originalUrl` が存在する場合は使用します。存在しない場合は、 `req.url` を使用します。
diff --git a/src/content/pages/ja/resources/middleware/multer.mdx b/src/content/pages/ja/resources/middleware/multer.mdx
index fd14a62fec..ad37b68b14 100644
--- a/src/content/pages/ja/resources/middleware/multer.mdx
+++ b/src/content/pages/ja/resources/middleware/multer.mdx
@@ -5,15 +5,17 @@ description: multipart/form-dataを扱うためのミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Multer は `multipart/form-data` を扱うための node.js ミドルウェアで、主にファイルのアップロードに使用されます。
の上に [busboy](https://github.com/mscdex/busboy)と書かれており、最大限の効率を得ることができます。
+の上に [busboy](https://github.com/mscdex/busboy)と書かれており、最大限の効率を得ることができます。
**注意**: Multer はマルチパートでないフォームを処理しません (`multipart/form-data`)。
@@ -36,13 +38,11 @@ Multer は `multipart/form-data` を扱うための node.js ミドルウェア
## インストール
-```sh
-$ npm install multer
-```
+
## 使用法
-Multer は `body` オブジェクトと `file` または `files` オブジェクトを `request` オブジェクトに追加します。 `body` オブジェクトには、フォームのテキストフィールドの値が含まれています。`file` または `files` オブジェクトには、フォームを介してアップロードされたファイルが含まれています。
+Multer は `body` オブジェクトと `file` または `files` オブジェクトを `request` オブジェクトに追加します。 `body` オブジェクトには、フォームのテキストフィールドの値が含まれています。`file` または `files` オブジェクトには、フォームを介してアップロードされたファイルが含まれています。 `body` オブジェクトには、フォームのテキストフィールドの値が含まれています。`file` または `files` オブジェクトには、フォームを介してアップロードされたファイルが含まれています。
基本的な使用例:
@@ -99,7 +99,7 @@ app.post('/profile', upload.none(), function (req, res, next) {
});
```
-multer が HTML 形式でどのように使用されるかについての例を示します。 `enctype="multipart/form-data"と`name="uploaded_file"\`フィールドの特に注意してください。
+multer が HTML 形式でどのように使用されるかについての例を示します。 multer が HTML 形式でどのように使用されるかについての例を示します。 `enctype="multipart/form-data"と`name="uploaded_file"\`フィールドの特に注意してください。
```html
```
-次に、javascriptファイルで、ファイルと本文の両方にアクセスするために、これらの行を追加します。 アップロード関数のフォームから `name` フィールドの値を使用することが重要です。 これは、リクエストのどのフィールドにファイルを探すべきかをmulterに伝えます。 これらのフィールドが HTML フォームとサーバーで同じでない場合、アップロードに失敗します:
+次に、javascriptファイルで、ファイルと本文の両方にアクセスするために、これらの行を追加します。 アップロード関数のフォームから `name` フィールドの値を使用することが重要です。 これは、リクエストのどのフィールドにファイルを探すべきかをmulterに伝えます。 次に、javascriptファイルで、ファイルと本文の両方にアクセスするために、これらの行を追加します。 アップロード関数のフォームから `name` フィールドの値を使用することが重要です。 これは、リクエストのどのフィールドにファイルを探すべきかをmulterに伝えます。 これらのフィールドが HTML フォームとサーバーで同じでない場合、アップロードに失敗します:
```javascript
const multer = require('multer');
@@ -146,19 +146,21 @@ app.post('/stats', upload.single('uploaded_file'), function (req, res) {
Multer は options オブジェクトを受け付けます。最も基本的なオブジェクトは `dest`
プロパティで、Multer はファイルのアップロード先を指定します。
オプションオブジェクトを省略した場合、ファイルはメモリに保存され、ディスクに書き込まれることはありません。
+オプションオブジェクトを省略した場合、ファイルはメモリに保存され、ディスクに書き込まれることはありません。
デフォルトでは、Multer は名前の衝突を避けるためにファイルの名前を変更します。
の名前変更機能は、必要に応じてカスタマイズできます。
+の名前変更機能は、必要に応じてカスタマイズできます。
Multer に渡すことができるオプションは以下のとおりです。
-| キー | 説明 |
-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `dest` または `storage` | ファイルを保存する場所 |
-| `fileFilter` | 受け入れられるファイルを制御する関数 |
-| `limits` | アップロードしたデータの制限 |
-| `preservePath` | ベース名の代わりにファイルの完全なパスを保持します |
-| `defParamCharset` | 拡張パラメータではない (明示的な文字セットを含む) 部品ヘッダーパラメータの値(ファイル名など)に使用するデフォルトの文字セット。 デフォルト: `'latin1'` |
+| キー | 説明 |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `dest` または `storage` | ファイルを保存する場所 |
+| `fileFilter` | 受け入れられるファイルを制御する関数 |
+| `limits` | アップロードしたデータの制限 |
+| `preservePath` | ベース名の代わりにファイルの完全なパスを保持します |
+| `defParamCharset` | 拡張パラメータではない (明示的な文字セットを含む) 部品ヘッダーパラメータの値(ファイル名など)に使用するデフォルトの文字セット。 デフォルト: `'latin1'` デフォルト: `'latin1'` |
In an average web app, only `dest` might be required, and configured as shown in
the following example.
@@ -169,26 +171,29 @@ const upload = multer({ dest: 'uploads/' });
アップロードをもっと制御したい場合は、`dest` の代わりに `storage`
オプションを使用します。 Multer はストレージエンジン `DiskStorage`
+と `MemoryStorage` を搭載しています。より多くのエンジンはサードパーティから入手できます。 Multer はストレージエンジン `DiskStorage`
と `MemoryStorage` を搭載しています。より多くのエンジンはサードパーティから入手できます。
#### `.single(fieldname)`
`fieldname`という名前のファイルを受け入れます。 単一のファイルは
+を `req.file` に格納します。 単一のファイルは
を `req.file` に格納します。
#### `.array(fieldname[, maxCount])`
`fieldname`という名前のファイルの配列を受け入れます。 必要に応じて、
-が `maxCount`ファイルよりも大きい場合にエラーが発生します。 ファイルの配列は
+が `maxCount`ファイルよりも大きい場合にエラーが発生します。 ワイヤ上にあるすべてのファイルを受け入れます。 ファイルの配列は
`req.files` に格納されます。
#### `.fields(fields)`
-`fields`で指定されたファイルのミックスを受け入れます。 ファイル
+`fields`で指定されたファイルのミックスを受け入れます。 `fields`で指定されたファイルのミックスを受け入れます。 ファイル
の配列を持つオブジェクトは`req.files`に保存されます。
`fields`は、`name`とオプションで`maxCount`を持つオブジェクトの配列でなければなりません。
例
+例
```javascript
[
@@ -207,9 +212,11 @@ const upload = multer({ dest: 'uploads/' });
ワイヤ上にあるすべてのファイルを受け入れます。 ファイルの配列は
`req.files` に格納されます。
+**警告:** ユーザーがアップロードするファイルを常に処理していることを確認してください。
**警告:** ユーザーがアップロードするファイルを常に処理していることを確認してください。
悪意のあるユーザーが予想していなかったルートに
ファイルをアップロードできるため、multer をグローバルミドルウェアとして追加しないでください。 アップロードされたファイルを処理しているルート
+でのみこの機能を使用してください。 アップロードされたファイルを処理しているルート
でのみこの機能を使用してください。
### `storage`
@@ -233,6 +240,7 @@ const upload = multer({ storage: storage });
```
`destination` と `filename` の2つのオプションが利用できます。 これらはどちらも、ファイルをどこに保存するかを決める
+関数です。 これらはどちらも、ファイルをどこに保存するかを決める
関数です。
`destination` is used to determine within which folder the uploaded files should
@@ -242,11 +250,14 @@ be stored. これは文字列として与えることもできます(例: `'/tmp
**注意:** 関数として
`destination` を指定するときにディレクトリを作成します。 文字列を渡すとき、multer は
+ディレクトリが作成されていることを確認します。 文字列を渡すとき、multer は
ディレクトリが作成されていることを確認します。
-フォルダ内のファイル名を指定するには、`filename` を使用します。
-If no `filename` is given, each file will be given a random name that doesn't
-include any file extension.
+`destination` is used to determine within which folder the uploaded files should
+be stored.
+これは文字列として与えることもできます(例: `'/tmp/uploads`)。
+`destination` が指定されていない場合は、一時的な
+ファイルのオペレーティングシステムのデフォルトディレクトリが使用されます。
**注意:** Multer はファイル拡張子を追加しません。あなたの関数
はファイル拡張子の完全なファイル名を返します。
@@ -265,6 +276,7 @@ null を渡す必要がある)を理解するには、
メモリストレージエンジンはファイルを `Buffer` オブジェクトとして保存します。
にはオプションはありません。
+にはオプションはありません。
```javascript
const storage = multer.memoryStorage();
@@ -280,26 +292,27 @@ memory storage is used.
### `limits`
-次のオプションプロパティのサイズ制限を指定するオブジェクト。 Multer はこのオブジェクトを busboy に直接渡し、プロパティの詳細は [busboy's page](https://github.com/mscdex/busboy#busboy-methods) にあります。
+次のオプションプロパティのサイズ制限を指定するオブジェクト。 次のオプションプロパティのサイズ制限を指定するオブジェクト。 Multer はこのオブジェクトを busboy に直接渡し、プロパティの詳細は [busboy's page](https://github.com/mscdex/busboy#busboy-methods) にあります。
次の整数値が使用できます。
-| キー | 説明 | デフォルト |
-| --------------- | ------------------------------------------------------------------ | ---------- |
-| `fieldNameSize` | 最大フィールド名のサイズ | 100 バイト |
-| `fieldSize` | 最大フィールド値のサイズ (バイト単位) | 1MB |
-| `fields` | ファイル以外のフィールドの最大数 | Infinity |
-| `fileSize` | マルチパート形式の場合、最大ファイルサイズ(バイト単位) | Infinity |
-| `files` | 複数形の場合、ファイルフィールドの最大数 | Infinity |
-| `parts` | マルチパートフォームの場合、部品の最大数 (フィールド + ファイル) | Infinity |
-| `headerPairs` | マルチパートフォームの場合、解析する最大ヘッダーキー=>値のペアの数 | 2000 |
+| キー | 説明 | デフォルト |
+| ------------------- | -------------------------------------------------------------------------- | ---------- |
+| `fieldNameSize` | 最大フィールド名のサイズ | 100 バイト |
+| `fieldSize` | 最大フィールド値のサイズ (バイト単位) | 1MB |
+| `fields` | ファイル以外のフィールドの最大数 | Infinity |
+| `fileSize` | マルチパート形式の場合、最大ファイルサイズ(バイト単位) | Infinity |
+| `files` | 複数形の場合、ファイルフィールドの最大数 | Infinity |
+| `parts` | マルチパートフォームの場合、部品の最大数 (フィールド + ファイル) | Infinity |
+| `headerPairs` | マルチパートフォームの場合、解析する最大ヘッダーキー=>値のペアの数 | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity |
制限を指定することは、サービス妨害(DoS)攻撃からサイトを保護するのに役立ちます。
### `fileFilter`
どのファイルをアップロードすべきか、どの
-をスキップすべきかを制御する関数に設定します。 関数は次のようになります:
+をスキップすべきかを制御する関数に設定します。 関数は次のようになります: 関数は次のようになります:
```javascript
function fileFilter(req, file, cb) {
@@ -317,12 +330,22 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## エラー処理
-エラーが発生した場合、MulterはエラーをExpressに委任します。 You can
+エラーが発生した場合、MulterはエラーをExpressに委任します。 エラーが発生した場合、MulterはエラーをExpressに委任します。 You can
display a nice error page using [the standard express way](/guide/error-handling).
Multer から特にエラーをキャッチしたい場合は、独自に
+ミドルウェア関数を呼び出すことができます。 Multer から特にエラーをキャッチしたい場合は、独自に
ミドルウェア関数を呼び出すことができます。 Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
```javascript
diff --git a/src/content/pages/ja/resources/middleware/response-time.mdx b/src/content/pages/ja/resources/middleware/response-time.mdx
index 3a42772448..3ce8bc52ca 100644
--- a/src/content/pages/ja/resources/middleware/response-time.mdx
+++ b/src/content/pages/ja/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Node.js サーバーのレスポンスタイム
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/serve-favicon.mdx b/src/content/pages/ja/resources/middleware/serve-favicon.mdx
index 28516ef16f..a332d874ed 100644
--- a/src/content/pages/ja/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/ja/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: キャッシュ機能付きミドルウェアのファビコン
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/serve-index.mdx b/src/content/pages/ja/resources/middleware/serve-index.mdx
index 5ff3ada55d..86cec72406 100644
--- a/src/content/pages/ja/resources/middleware/serve-index.mdx
+++ b/src/content/pages/ja/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: ディレクトリ一覧を提供する
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
@@ -37,6 +36,8 @@ var serveIndex = require('serve-index');
`path`は`req.url`値に基づいています。`/some/dir`
`path`の`req.url`は`public/some/dir'`になります。 If you are using
something like `express`, you can change the URL "base" with `app.use` (see
+the express example). If you are using
+something like `express`, you can change the URL "base" with `app.use` (see
the express example).
#### オプション
@@ -45,7 +46,7 @@ Serve indexはoptionsオブジェクトでこれらのプロパティを受け
##### フィルター
-このフィルタ機能をファイルに適用します。 デフォルトは `false` です。 The `filter` function
+このフィルタ機能をファイルに適用します。 デフォルトは `false` です。 このフィルタ機能をファイルに適用します。 デフォルトは `false` です。 The `filter` function
is called for each file, with the signature `filter(filename, index, files, dir)`
where `filename` is the name of the file, `index` is the array index, `files` is
the array of files and `dir` is the absolute path the file is located (and thus,
@@ -61,12 +62,12 @@ the directory the listing is for).
##### stylesheet
-CSS スタイルシートへのオプションのパス。 デフォルトはビルトインスタイルシートです。
+CSS スタイルシートへのオプションのパス。 デフォルトはビルトインスタイルシートです。 デフォルトはビルトインスタイルシートです。
##### テンプレート
HTMLテンプレートまたはHTML
-文字列をレンダリングする関数への任意のパス。 デフォルトはビルトインテンプレートです。
+文字列をレンダリングする関数への任意のパス。 デフォルトはビルトインテンプレートです。 デフォルトはビルトインテンプレートです。
When given a string, the string is used as a file path to load and then the
following tokens are replaced in templates:
@@ -78,6 +79,7 @@ following tokens are replaced in templates:
関数として与えられた場合、関数は `template(locals, callback)`
と呼ばれ、`callback(error, htmlString)` を呼び出す必要があります。 以下はローカルで提供される
+です。 以下はローカルで提供される
です。
- `directory`は表示されているディレクトリです(`/`がルートです)。
@@ -92,7 +94,7 @@ following tokens are replaced in templates:
##### 表示
-表示モード `tiles`と`details`があります。 デフォルトは `tiles` です。
+表示モード `tiles`と`details`があります。 表示モード `tiles`と`details`があります。 デフォルトは `tiles` です。
## 例
diff --git a/src/content/pages/ja/resources/middleware/serve-static.mdx b/src/content/pages/ja/resources/middleware/serve-static.mdx
index 4d493cdf5a..34c0c291ec 100644
--- a/src/content/pages/ja/resources/middleware/serve-static.mdx
+++ b/src/content/pages/ja/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: 静的ファイルを提供
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/resources/middleware/session.mdx b/src/content/pages/ja/resources/middleware/session.mdx
index 57ce35ba20..3f11e3e370 100644
--- a/src/content/pages/ja/resources/middleware/session.mdx
+++ b/src/content/pages/ja/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Express 用のシンプルなセッションミドルウェア
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## インストール
@@ -18,9 +19,7 @@ import Alert from '@components/primitives/Alert/Alert.astro';
[npm registry](https://www.npmjs.com/) を介して利用できます。 インストールは
[`npm install` コマンド](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -34,15 +33,20 @@ var session = require('express-session');
**注意** セッションデータはクッキー自体に保存されず、セッションIDだけです。
セッションデータはサーバーサイドに保存されます。
+セッションデータはサーバーサイドに保存されます。
**注意** バージョン1.5.0以降、[`cookie-parser` middleware](https://www.npmjs.com/package/cookie-parser)
はこのモジュールを動作させるために使用する必要がなくなりました。 このモジュールは
を直接読み込み、 `req`/`res` に Cookie を書き込みます。 `cookie-parser` を使用すると、このモジュールと `cookie-parser` の間で`secret` が同じでない場合、
+が発生する可能性があります。 このモジュールは
+を直接読み込み、 `req`/`res` に Cookie を書き込みます。 `cookie-parser` を使用すると、このモジュールと `cookie-parser` の間で`secret` が同じでない場合、
が発生する可能性があります。
**警告** デフォルトのサーバーサイドセッションストレージである`MemoryStore`は、_意図的に_
本番環境用に設計されていません。 ほとんどの
条件下でメモリをリークし、単一のプロセスを経過させることはなく、デバッグと
+開発のためのものです。 ほとんどの
+条件下でメモリをリークし、単一のプロセスを経過させることはなく、デバッグと
開発のためのものです。
店舗一覧については、[compatible session store](#compatible-session-stores)を参照してください。
@@ -56,7 +60,7 @@ var session = require('express-session');
Settings object for the session ID cookie. デフォルト値は
`{ path: '/', httpOnly: true, secure: false, maxAge: null }` です。
-静的オブジェクトを提供するだけでなく、各リクエストの Cookie オプションを動的に生成するコールバック関数を渡すこともできます。 コールバックは `req` オブジェクトを引数として受け取り、Cookie の設定を含むオブジェクトを返します。
+静的オブジェクトを提供するだけでなく、各リクエストの Cookie オプションを動的に生成するコールバック関数を渡すこともできます。 コールバックは `req` オブジェクトを引数として受け取り、Cookie の設定を含むオブジェクトを返します。 コールバックは `req` オブジェクトを引数として受け取り、Cookie の設定を含むオブジェクトを返します。
```js
var app = express();
@@ -82,12 +86,13 @@ app.use(
##### cookie.domain
-`Domain` `Set-Cookie` 属性の値を指定します。 デフォルトでは、ドメイン
+`Domain` `Set-Cookie` 属性の値を指定します。 `Domain` `Set-Cookie` 属性の値を指定します。 デフォルトでは、ドメイン
は設定されておらず、ほとんどのクライアントは現在の
ドメインのみに適用するクッキーを考慮します。
##### cookie.expires
+`Expires `Set-Cookie`属性の値にする`Date`オブジェクトを指定します。
`Expires `Set-Cookie`属性の値にする`Date\`オブジェクトを指定します。
デフォルトでは、有効期限は設定されていません そして、ほとんどのクライアントはこれを
"非永続クッキー"と見なし、Webブラウザ
@@ -103,6 +108,8 @@ app.use(
`HttpOnly`Set-Cookie`属性の`boolean`値を指定します。 truthyの場合、
`HttpOnly` 属性が設定されています。そうでなければ、そうではありません。 デフォルトでは、`HttpOnly\`
+属性が設定されています。 truthyの場合、
+`HttpOnly` 属性が設定されています。そうでなければ、そうではありません。 デフォルトでは、`HttpOnly`
属性が設定されています。
**Note** be careful when setting this to `true`, as compliant clients will not allow
@@ -113,6 +120,8 @@ client-side JavaScript to see the cookie in `document.cookie`.
`Expires`
`Set-Cookie` 属性を計算するときに使用する `number` (ミリ秒単位) を指定します。 これは現在のサーバ時間を要し、`Expires`日付を計算するための値に
`maxAge`ミリ秒を追加することによって行われます。 デフォルトでは、
+の最大年齢は設定されていません。 これは現在のサーバ時間を要し、`Expires`日付を計算するための値に
+`maxAge`ミリ秒を追加することによって行われます。 デフォルトでは、
の最大年齢は設定されていません。
**注意** オプションで `expires` と `maxAge` の両方が設定されている場合、オブジェクトで定義された最後の
@@ -122,6 +131,7 @@ client-side JavaScript to see the cookie in `document.cookie`.
[`Partitioned` `Set-Cookie`](https://github.com/expressjs/session/blob/HEAD/rfc-cutler-httpbis-partitioned-cookies)
属性の `boolean` 値を指定します。 truthyの場合、`Partitioned` 属性が設定されています。そうでなければ、そうではありません。
+デフォルトでは、 `Partitioned` 属性は設定されていません。 truthyの場合、`Partitioned` 属性が設定されています。そうでなければ、そうではありません。
デフォルトでは、 `Partitioned` 属性は設定されていません。
**Note** This is an attribute that has not yet been fully standardized, and may
@@ -133,6 +143,7 @@ More information about can be found in [the proposal](https://github.com/privacy
##### cookie.path
`Path` `Set-Cookie` の値を指定します。 デフォルトでは、これは `'/'` に設定されており、ドメインのルートパスは
+になります。 デフォルトでは、これは `'/'` に設定されており、ドメインのルートパスは
になります。
##### cookie.priority
@@ -148,11 +159,13 @@ More information about can be found in [the proposal](https://github.com/privacy
**注意** これは完全に標準化されていない属性であり、将来変更される可能性があります。
これはまた、多くのクライアントがこの属性を理解するまでこの属性を無視することを意味します。
+これはまた、多くのクライアントがこの属性を理解するまでこの属性を無視することを意味します。
##### cookie.sameSite
`Set-Cookie`属性の値にする`boolean`または`string`を指定します。
デフォルトでは `false` です。
+デフォルトでは `false` です。
- `true` は、サイトを厳密に強制するために `SameSite` 属性を `Strict` に設定します。
- `false` は `SameSite` 属性を設定しません。
@@ -174,6 +187,8 @@ set to `'none'`. 一部のウェブブラウザや他のクライアントがこ
The `cookie.sameSite` option can also be set to the special value `'auto'` to have
this setting automatically match the determined security of the connection. 接続
がセキュア(HTTPS)の場合、クロスサイトの使用を可能にするため、`SameSite`属性は`None`に設定されます。
+接続
+がセキュア(HTTPS)の場合、クロスサイトの使用を可能にするため、`SameSite`属性は`None`に設定されます。
When the connection is not secure (HTTP), the `SameSite` attribute will be set to `Lax` for
better security while maintaining functionality. これは、Express `"Trust proxy"`
設定が適切にセットアップされている場合に便利で、開発と本番環境の設定、特に
@@ -183,6 +198,8 @@ SAML認証シナリオを簡素化します。
`Set-Cookie` 属性の `boolean` 値を指定します。 truthyの場合、
`Secure` 属性が設定されています。そうでなければ、そうではありません。 デフォルトでは、`Secure`
+属性は設定されていません。 truthyの場合、
+`Secure` 属性が設定されています。そうでなければ、そうではありません。 デフォルトでは、`Secure`
属性は設定されていません。
**Note** be careful when setting this to `true`, as compliant clients will not send
@@ -235,7 +252,7 @@ as once the cookie is set on HTTPS, it will no longer be visible over HTTP. こ
##### genid
-新しいセッション ID を生成するために呼び出す関数。 Provide a function that returns
+新しいセッション ID を生成するために呼び出す関数。 新しいセッション ID を生成するために呼び出す関数。 Provide a function that returns
a string that will be used as a session ID. The function is given `req` as the
first argument if you want to use some value attached to `req` when generating
the ID.
@@ -281,20 +298,23 @@ each other. 最も簡単な方法は、アプリごとに異なる`name`を設
##### 保存する
-セッション
-がリクエスト中に変更されなかった場合でも、セッションストアに強制的に保存されます。 Depending on your store this may be
-necessary, but it can also create race conditions where a client makes two
-parallel requests to your server and changes made to the session in one
-request may get overwritten when the other request ends, even if it made no
-changes (this behavior also depends on what store you're using).
+ストアに保存される「初期化されていない」セッションを強制します。 A session is
+is uninitialized when it is new but not modified Choosing `false` is useful for
+implementing login sessions, reducing server storage usage, or complying with
+laws that require permission before setting a cookie. Choosing `false` will also
+help with race conditions where a client makes multiple parallel requests
+without a session.
-The default value is `true`, but using the default has been deprecated,
-as the default will change in the future. この設定
+デフォルト値は `true` ですが、
+のデフォルトが将来変更されるため、デフォルトを使用することは推奨されません。 この設定を調べて、
+あなたのユースケースに適したものを選択してください。 この設定
を調べて、使用事例に適したものを選んでください。 通常は、
`false` を使用します。
これが自分の店で必要かどうかどうかを知るにはどうすればいいですか? 最良の方法は、`touch`メソッドを実装しているかどうか、店舗で
確認することです。 もしそうであれば、
+は `resave: false` を安全に設定できます。 最良の方法は、`touch`メソッドを実装しているかどうか、店舗で
+確認することです。 もしそうであれば、
は `resave: false` を安全に設定できます。 If it does not implement the `touch`
method and your store sets an expiration date on stored sessions, then you
likely need `resave: true`.
@@ -303,6 +323,8 @@ likely need `resave: true`.
セッション識別子クッキーをすべてのレスポンスに設定します。 有効期限
は元の[`maxAge`](#cookiemaxage)にリセットされ、有効期限
+カウントダウンをリセットします。 有効期限
+は元の[`maxAge`](#cookiemaxage)にリセットされ、有効期限
カウントダウンをリセットします。
デフォルト値は `false` です。
@@ -329,9 +351,10 @@ laws that require permission before setting a cookie. Choosing `false` will also
help with race conditions where a client makes multiple parallel requests
without a session.
-デフォルト値は `true` ですが、
-のデフォルトが将来変更されるため、デフォルトを使用することは推奨されません。 この設定を調べて、
-あなたのユースケースに適したものを選択してください。
+The default value is `true`, but using the default has been deprecated,
+as the default will change in the future. この設定
+を調べて、使用事例に適したものを選んでください。 通常は、
+`false` を使用します。
**Note** if you are using Session in conjunction with PassportJS, Passport
will add an empty Passport object to the session for use after a user is
@@ -347,6 +370,11 @@ it to be saved. _PassportJS 0.3.0_ で修正されました
型にすることができます。 これは単一のシークレット、または複数のシークレットの配列のいずれかになります。 If
an array of secrets is provided, only the first element will be used to sign the
session ID cookie, while all the elements will be considered when verifying the
+signature in requests. シークレットは、Node.js の `crypto.createHmac` (文字列や
+`Buffer` のように) でサポートされている値の
+型にすることができます。 これは単一のシークレット、または複数のシークレットの配列のいずれかになります。 If
+an array of secrets is provided, only the first element will be used to sign the
+session ID cookie, while all the elements will be considered when verifying the
signature in requests. シークレット自体は人間によって簡単に解析されるべきではなく、
はランダムな文字セットであることが最善です。 ベストプラクティスは以下のとおりです:
@@ -358,12 +386,13 @@ signature in requests. シークレット自体は人間によって簡単に解
推測できないシークレットを使用すると、セッションを
セッションIDを推測するだけのformat@@1にハイジャックすることができなくなります(`genid` オプションで決定されます)。
-シークレットの値を変更すると、既存のすべてのセッションが無効になります。 In order to rotate
+シークレットの値を変更すると、既存のすべてのセッションが無効になります。 シークレットの値を変更すると、既存のすべてのセッションが無効になります。 In order to rotate
the secret without invalidating sessions, provide an array of secrets, with the new
secret as first element of the array, and including previous secrets as the later
elements.
**注意** HMAC-256 はセッションIDに署名するために使用されます。 このため、シークレットは
+に少なくとも 32 バイトのエントロピーを含める必要があります。 このため、シークレットは
に少なくとも 32 バイトのエントロピーを含める必要があります。
##### ストア
@@ -385,7 +414,7 @@ elements.
セッションデータを保存またはアクセスするには、requestプロパティ`reqを使用します。 ession`, (一般的に) ストアによって JSON としてシリアライズされている
ので、入れ子になったオブジェクト
-は通常問題ありません。 例えば、以下はユーザー固有のビューカウンターです。
+は通常問題ありません。 例えば、以下はユーザー固有のビューカウンターです。 例えば、以下はユーザー固有のビューカウンターです。
```js
// Use the session middleware
@@ -408,7 +437,7 @@ app.get('/', function (req, res, next) {
#### Session.regenerate(callback)
-セッションを再生成するには、単にメソッドを呼び出します。 完了すると、
+セッションを再生成するには、単にメソッドを呼び出します。 セッションを再生成するには、単にメソッドを呼び出します。 完了すると、
新しいSIDと`Session` インスタンスが`req.session`
で初期化され、`callback`が呼び出されます。
@@ -422,6 +451,7 @@ req.session.regenerate(function (err) {
セッションを破壊し、`req.session` プロパティを解除します。
完了すると、`callback` が呼び出されます。
+完了すると、`callback` が呼び出されます。
```js
req.session.destroy(function (err) {
@@ -432,7 +462,7 @@ req.session.destroy(function (err) {
#### Session.reload(callback)
ストアからセッションデータをリロードし、
-`req.session` オブジェクトを再入力します。 完了すると、`callback` が呼び出されます。
+`req.session` オブジェクトを再入力します。 完了すると、`callback` が呼び出されます。 完了すると、`callback` が呼び出されます。
```js
req.session.reload(function (err) {
@@ -449,6 +479,7 @@ req.session.reload(function (err) {
このメソッドは、
セッションデータが変更された場合、HTTPレスポンスの最後に自動的に呼び出されます(ミドルウェアコンストラクタの様々な
オプションでこの動作を変更することができます)。 このため、通常、このメソッド
+を呼び出す必要はありません。 このため、通常、このメソッド
を呼び出す必要はありません。
リダイレクト、長寿命リクエスト、WebSocketなど、このメソッドを呼び出すと便利な場合があります。
@@ -466,14 +497,14 @@ req.session.save(function (err) {
### req.session.id
-各セッションには、それに関連付けられた一意のIDがあります。 This property is an
+各セッションには、それに関連付けられた一意のIDがあります。 各セッションには、それに関連付けられた一意のIDがあります。 This property is an
alias of [`req.sessionID`](#reqsessionid-1) and cannot be modified.
`session`
オブジェクトからセッション ID をアクセス可能にするために追加されました。
### req.session.cookie
-各セッションには、それに付随する固有のクッキーオブジェクトがあります。 This allows
+各セッションには、それに付随する固有のクッキーオブジェクトがあります。 各セッションには、それに付随する固有のクッキーオブジェクトがあります。 This allows
you to alter the session cookie per visitor. 例えば、
`req.session.cookie.expires` を `false` に設定すると、ユーザーエージェントの期間のみクッキー
を有効にできます。
@@ -483,6 +514,7 @@ you to alter the session cookie per visitor. 例えば、
別の方法として、`req.session.cookie.maxAge`はミリ秒単位の残り時間
を返し、`.expires`プロパティを適切に調整するために新しい値
を再割り当てることもできます。 以下の
+は本質的に同等です 以下の
は本質的に同等です
```js
@@ -509,12 +541,14 @@ req.session.cookie.maxAge; // => 30000
ロードされたセッションの ID を取得するには、request プロパティ
`req.sessionID` にアクセスします。 これは、セッション
+がロード/作成されたときに読み取り専用の値セットです。 これは、セッション
がロード/作成されたときに読み取り専用の値セットです。
## セッションストアの実装
-すべてのセッションストア*must*は`EventEmitter`で、特定の
+すべてのセッションストア_must_は`EventEmitter`で、特定の
メソッドを実装します。 以下のメソッドは、**required**、**recommended**、
+、**optional**のリストです。 以下のメソッドは、**required**、**recommended**、
、**optional**のリストです。
- 必須メソッドは、このモジュールが常にストアで呼び出すメソッドです。
@@ -529,16 +563,15 @@ req.session.cookie.maxAge; // => 30000
**任意**
-このオプションのメソッドは、ストア内のすべてのセッションを配列として取得するために使用されます。
-`callback` は `callback(error, sessions)` として呼び出されます。
+This required method is used to get a session from the store give a session
+ID (`sid`). `callback` は `callback(error, session)` と呼ばれます。
### store.destroy(sid, callback)
**必須**
This required method is used to destroy a session from the store given
-a session ID (`sid`).
-セッションが破棄されると、`callback(error)`として呼び出されます。
+a session ID (`sid`). セッションが破棄されると、`callback(error)`として呼び出されます。
### store.clear(callback)
@@ -546,6 +579,7 @@ a session ID (`sid`).
このオプションの方法は、ストアからすべてのセッションを削除するために使用されます。
`callback` は店舗がクリアされると`callback(error)`として呼び出されます。
+`callback` は店舗がクリアされると`callback(error)`として呼び出されます。
### store.length(callback)
@@ -553,6 +587,7 @@ a session ID (`sid`).
このオプションのメソッドは、ストア内のすべてのセッション数を取得するために使用されます。
`callback` は `callback(error, len)` と呼ばれます。
+`callback` は `callback(error, len)` と呼ばれます。
### store.get(sid, callback)
@@ -563,6 +598,7 @@ ID (`sid`). `callback` は `callback(error, session)` と呼ばれます。
`session` 引数が見つかった場合はセッションを指定します。それ以外の場合は `null` または
`undefined` セッションが見つからなかった場合は (エラーがなかった場合) 特別な
+の場合は、 `error.code === 'ENOENT'` で `callback(null, null)` のように動作します。 特別な
の場合は、 `error.code === 'ENOENT'` で `callback(null, null)` のように動作します。
### store.set(sid, session, callback)
@@ -571,6 +607,7 @@ ID (`sid`). `callback` は `callback(error, session)` と呼ばれます。
この必須メソッドは、
セッション ID (`sid`) とセッション (`session`) オブジェクトを与えられたストアにセッションをアップサートするために使用されます。 The callback should be
+should be `callback(error)` when the session has been set in the store. The callback should be
should be `callback(error)` when the session has been set in the store.
### store.touch(sid, session, callback)
@@ -579,6 +616,7 @@ should be `callback(error)` when the session has been set in the store.
この推奨メソッドは、
セッション ID (`sid`) とセッション (`session`) オブジェクトを与えられた特定のセッションを「タッチ」するために使用されます。 The `callback` should be
+called as `callback(error)` once the session has been touched. The `callback` should be
called as `callback(error)` once the session has been touched.
This is primarily used when the store will automatically delete idle sessions
@@ -588,7 +626,7 @@ potentially resetting the idle timer.
## 互換性のあるセッションストア
以下のモジュールは、この
-モジュールと互換性のあるセッションストアを実装します。 追加モジュールを追加するために PR を作成してください :)
+モジュールと互換性のあるセッションストアを実装します。 追加モジュールを追加するために PR を作成してください :) 追加モジュールを追加するために PR を作成してください :)
[![★][aerospike-session-store-image] aerospike-session-store][aerospike-session-store-url] A session store using [Aerospike](http://www.aerospike.com/).
@@ -828,7 +866,7 @@ based session store. Fortune (ongoDB、Redis、Postgres、NeDB)でサポート
[session-file-store-url]: https://www.npmjs.com/package/session-file-store
-[![★][session-pouchdb-store-image] session-pouchdb-store][session-pouchdb-store-url] PouchDB / CouchDB用セッションストア 埋め込み、カスタム、またはリモートPouchDBインスタンスとリアルタイム同期を受け入れます。
+[![★][session-pouchdb-store-image] session-pouchdb-store][session-pouchdb-store-url] PouchDB / CouchDB用セッションストア 埋め込み、カスタム、またはリモートPouchDBインスタンスとリアルタイム同期を受け入れます。 埋め込み、カスタム、またはリモートPouchDBインスタンスとリアルタイム同期を受け入れます。
[session-pouchdb-store-url]: https://www.npmjs.com/package/session-pouchdb-store
diff --git a/src/content/pages/ja/resources/middleware/timeout.mdx b/src/content/pages/ja/resources/middleware/timeout.mdx
index 7dec50e891..ceb7da310d 100644
--- a/src/content/pages/ja/resources/middleware/timeout.mdx
+++ b/src/content/pages/ja/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Connect/Expressミドルウェアのリクエスト
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Connect/Expressアプリケーションフレームワークでリクエストをタイムアウトします。
@@ -20,9 +21,7 @@ Connect/Expressアプリケーションフレームワークでリクエスト
[npm registry](https://www.npmjs.com/) を介して利用できます。 インストールは
[`npm install` コマンド](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/ja/resources/middleware/vhost.mdx b/src/content/pages/ja/resources/middleware/vhost.mdx
index a21178b1f3..4547893f00 100644
--- a/src/content/pages/ja/resources/middleware/vhost.mdx
+++ b/src/content/pages/ja/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: バーチャルドメインホスティング
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ja/support.md b/src/content/pages/ja/support.md
index 8a41378fcb..452a83ea01 100644
--- a/src/content/pages/ja/support.md
+++ b/src/content/pages/ja/support.md
@@ -7,14 +7,14 @@ description: 現在メンテナンスされているバージョンや終了ポ
EOL (終了) _may_ のバージョンは、重大なセキュリティ脆弱性の更新を受け取ります。 しかし、Expressチームは保証を提供しておらず、見つかった問題の修正やリリースを計画していません。
-| メジャーバージョン | 最小Node.js バージョン | サポート開始日 | サポート終了日 |
-| ------------------- | ---------------------- | -------------- | -------------- |
-| [**v5.x**](/5x/api) | 18 | 2024年9月 | **進行中** |
-| [**v4.x**](/4x/api) | 0.10.0 | 2014 年 4 月 | **進行中** |
-| [**v3.x**](/3x/api) | 0.8.0 | 2012年10月 | 2015 年 7 月 |
-| [**v2.x**](/2x/) | 0.4.1 | 2011 年 3 月 | 2012 年 7 月 |
-| **v1.x** | 0.2.0 | 2010年12月 | 2011 年 3 月 |
-| **v0.14.x** | 0.1.98 | 2010年12月 | 2010年12月 |
+| メジャーバージョン | 最小Node.js バージョン | サポート開始日 | サポート終了日 |
+| -------------------------------------------------------------- | ---------------------- | -------------- | -------------- |
+| [**v5.x**](/5x/api) | 18 | 2024年9月 | **進行中** |
+| [**v4.x**](/4x/api) | 0.10.0 | 2014 年 4 月 | **進行中** |
+| [**v3.x**](/3x/api) | 0.8.0 | 2012年10月 | 2015 年 7 月 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | 2011 年 3 月 | 2012 年 7 月 |
+| **v1.x** | 0.2.0 | 2010年12月 | 2011 年 3 月 |
+| **v0.14.x** | 0.1.98 | 2010年12月 | 2010年12月 |
## 商用サポートオプション
diff --git a/src/content/pages/ko/advanced/best-practice-performance.md b/src/content/pages/ko/advanced/best-practice-performance.md
index 206df197d2..62980393ca 100644
--- a/src/content/pages/ko/advanced/best-practice-performance.md
+++ b/src/content/pages/ko/advanced/best-practice-performance.md
@@ -33,7 +33,7 @@ Here are some things you can do in your code to improve your application's perfo
Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,6 +41,15 @@ const app = express();
app.use(compression());
```
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
### Don't use synchronous functions
@@ -76,7 +85,7 @@ Before diving into these topics, you should have a basic understanding of Node/E
For more on the fundamentals of error handling, see:
-- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
#### Use try-catch
@@ -159,7 +168,7 @@ Setting NODE_ENV to "production" makes Express:
- Cache CSS files generated from CSS extensions.
- Generate less verbose error messages.
-[Tests indicate](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
@@ -248,7 +257,7 @@ In a multi-core system, you can increase the performance of a Node app by many t

-IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](http://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
@@ -288,7 +297,7 @@ For more information on clustering with PM2, see [Cluster Mode](https://pm2.keym
Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/nginx-caching/)) to greatly improve the speed and performance of your app.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
### Use a load balancer
@@ -302,4 +311,4 @@ With load balancing, you might have to ensure that requests that are associated
A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://www.nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/ko/advanced/best-practice-security.mdx b/src/content/pages/ko/advanced/best-practice-security.mdx
index cb960fcbbf..2b96bbceef 100644
--- a/src/content/pages/ko/advanced/best-practice-security.mdx
+++ b/src/content/pages/ko/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Discover crucial security best practices for Express apps in produc
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
The term _"production"_ refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the _"development"_ stage, you're still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as _production_ and _development_ environments, respectively.
@@ -18,21 +19,19 @@ Policies and Procedures.
Security best practices for Express applications in production include:
-- [Production Best Practices: Security](#production-best-practices-security)
- - [Overview](#overview)
- - [Don't use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Use TLS](#use-tls)
- - [Do not trust user input](#do-not-trust-user-input)
- - [Prevent open redirects](#prevent-open-redirects)
- - [Use Helmet](#use-helmet)
- - [Reduce fingerprinting](#reduce-fingerprinting)
- - [Use cookies securely](#use-cookies-securely)
- - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
- - [Set cookie security options](#set-cookie-security-options)
- - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
- - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
- - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
- - [Additional considerations](#additional-considerations)
+- [Don't use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Use TLS](#use-tls)
+- [Do not trust user input](#do-not-trust-user-input)
+ - [Prevent open redirects](#prevent-open-redirects)
+- [Use Helmet](#use-helmet)
+- [Reduce fingerprinting](#reduce-fingerprinting)
+- [Use cookies securely](#use-cookies-securely)
+ - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
+ - [Set cookie security options](#set-cookie-security-options)
+- [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
+- [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
+ - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
+- [Additional considerations](#additional-considerations)
## Don't use deprecated or vulnerable versions of Express
@@ -44,7 +43,7 @@ Also ensure you are not using any of the vulnerable Express versions listed on t
If your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem "hidden" in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+You may be familiar with Secure Socket Layer (SSL) encryption. In general, we recommend Nginx to handle TLS. In other words, if you were using SSL before, consider upgrading to TLS. In other words, if you were using SSL before, consider upgrading to TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Also, a handy tool to get a free TLS certificate is [Let's Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Each header can be configured or disabled. To read more about it please go to [i
Install Helmet like any other module:
-```bash
-$ npm install helmet
-```
+
Then to use it in your code:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Reduce fingerprinting
It can help to provide an extra layer of security to reduce the ability of attackers to determine
@@ -177,7 +184,7 @@ Using the default session cookie name can open your app to attacks. The security
To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Set cookie security options
Set the following cookie options to enhance security:
@@ -200,7 +219,7 @@ Set the following cookie options to enhance security:
Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Prevent brute-force attacks against authorization
Make sure login endpoints are protected to make private data more secure.
@@ -259,7 +300,7 @@ $ snyk test
### Avoid other known vulnerabilities
-Keep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
Finally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
diff --git a/src/content/pages/ko/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/ko/advanced/healthcheck-graceful-shutdown.md
index c060e58605..5d7b87ac11 100644
--- a/src/content/pages/ko/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/ko/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Health checks
-A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, that determines when to restart a container.
- `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers.
diff --git a/src/content/pages/ko/advanced/security-updates.mdx b/src/content/pages/ko/advanced/security-updates.mdx
index 16d9d7191f..535f0aeb91 100644
--- a/src/content/pages/ko/advanced/security-updates.mdx
+++ b/src/content/pages/ko/advanced/security-updates.mdx
@@ -33,7 +33,7 @@ Policies and Procedures.
- The dependency `serve-static` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-cm22-4g7w-348p).
- The dependency `send` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-m6fv-jmcg-4jfg).
- The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j).
- - The dependency `body-parser` has been updated to addres a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url enconding activated.
+ - The dependency `body-parser` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url encoding activated.
- 4.19.0, 4.19.1
- Fixed open redirect vulnerability in `res.location` and `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc), [CVE-2024-29041](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-29041)).
- 4.17.3
diff --git a/src/content/pages/ko/guide/database-integration.mdx b/src/content/pages/ko/guide/database-integration.mdx
index b0855e4a2a..5c3aeab058 100644
--- a/src/content/pages/ko/guide/database-integration.mdx
+++ b/src/content/pages/ko/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate various databases with Express.js applica
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:
@@ -34,13 +35,11 @@ These database drivers are among many that are available. For other options, sea
### Installation
-```bash
-$ npm install cassandra-driver
-```
+
### Example
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installation
-```bash
-$ npm install couchbase
-```
+
### Example
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
**Module**: [nano](https://github.com/dscape/nano)
### Installation
-```bash
-$ npm install nano
-```
+
### Example
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -129,13 +161,11 @@ books.list((err, body) => {
### Installation
-```bash
-$ npm install level levelup leveldown
-```
+
### Example
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installation
-```bash
-$ npm install mysql
-```
+
### Example
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installation
-```bash
-$ npm install mongodb
-```
+
### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -212,7 +275,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -238,13 +301,11 @@ If you want an object model driver for MongoDB, look at [Mongoose](https://githu
### Installation
-```bash
-$ npm install neo4j-driver
-```
+
### Example
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,6 +323,25 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
**Module**: [oracledb](https://github.com/oracle/node-oracledb)
@@ -270,13 +350,11 @@ session.readTransaction((tx) => {
NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Example
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installation
-```bash
-$ npm install pg-promise
-```
+
### Example
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -337,13 +444,11 @@ db.one('SELECT $1 AS value', 123)
### Installation
-```bash
-$ npm install redis
-```
+
### Example
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
+```mjs title="index.mjs"
+import redis from 'redis';
+
+const client = redis.createClient();
+
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
+
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
+```
+
## SQL Server
**Module**: [tedious](https://github.com/tediousjs/tedious)
### Installation
-```bash
-$ npm install tedious
-```
+
### Example
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -433,13 +560,11 @@ function executeStatement() {
### Installation
-```bash
-$ npm install sqlite3
-```
+
### Example
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -467,13 +592,11 @@ db.close();
### Installation
-```bash
-$ npm install elasticsearch
-```
+
### Example
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/ko/guide/migrating-4.mdx b/src/content/pages/ko/guide/migrating-4.mdx
index c0e246a73c..acd2fb1488 100644
--- a/src/content/pages/ko/guide/migrating-4.mdx
+++ b/src/content/pages/ko/guide/migrating-4.mdx
@@ -4,39 +4,23 @@ description: A guide to migrating your Express.js applications from version 3 to
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 is a breaking change from Express 3. That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies.
This article covers:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Changes in Express 4
There are several significant changes in Express 4:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
See also:
@@ -252,7 +236,7 @@ it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named `birds.js` in the app directory,
with the following content:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to the `/birds` and
`/birds/about` paths, and will call the `timeLog`
middleware that is specific to the route.
@@ -375,7 +389,7 @@ The files of interest are `app.js` and `package.json`.
Consider an Express v.3 application with the following `app.js` file:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -409,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
The accompanying version 3 `package.json` file might look
@@ -435,9 +483,7 @@ Begin the migration process by installing the required middleware for the
Express 4 app and updating Express and Pug to their respective latest
version with the following command:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Make the following changes to `app.js`:
@@ -487,7 +533,7 @@ Running the above `npm` command will update `package.json` as follows:
Then, remove invalid code, load the required middleware, and make other
changes as necessary. The `app.js` file will look like this:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -537,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way:
@@ -572,18 +667,14 @@ the Express 3 app generator and then install the new
If you already have the Express 3 app generator installed on your system,
you must uninstall it:
-```bash
-$ npm uninstall -g express
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
Now install the new generator:
-```bash
-$ npm install -g express-generator
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
diff --git a/src/content/pages/ko/guide/migrating-5.mdx b/src/content/pages/ko/guide/migrating-5.mdx
index 3dfdd8d0ff..ad3a0d9a31 100644
--- a/src/content/pages/ko/guide/migrating-5.mdx
+++ b/src/content/pages/ko/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: A comprehensive guide to migrating your Express.js applications fro
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 5 is not very different from Express 4; although it maintains the same basic API, there are still changes that break compatibility with the previous version. Therefore, an application built with Express 4 might not work if you update it to use Express 5.
@@ -11,9 +12,7 @@ Express 5 is not very different from Express 4; although it maintains the same b
To install this version, you need to have a **Node.js version 18 or higher**. Then, execute the following command in your application directory:
-```sh
-npm install "express@5"
-```
+
You can then run your automated tests to see what fails, and fix problems according to the updates listed below. 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.
@@ -23,15 +22,11 @@ To help you migrate your express server, we have created a set of codemods that
Run the following command for run all the codemods available:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
If you want to run a specific codemod, you can run the following command:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
You can find the list of available codemods [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Initially, `del` was used instead of `delete`, because `delete` is a reserved ke
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Or you can update your code manually:
@@ -80,9 +73,7 @@ The following method names have been pluralized. In Express 4, using the old met
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Or you can update your code manually:
@@ -103,7 +94,7 @@ Or you can update your code manually:
A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
-This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api#app.param), as it makes no mention of the leading colon.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(name)
@@ -113,9 +104,7 @@ This potentially confusing and dangerous method of retrieving form data has been
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Or you can update your code manually:
@@ -140,9 +129,7 @@ Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -161,9 +148,7 @@ Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, se
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -182,16 +167,19 @@ Express 5 no longer supports the signature `res.redirect(url, status)`. Instead,
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Or you can update your code manually:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 no longer supports the magic string `back` in the `res.redirect()` and
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Or you can update your code manually:
@@ -224,9 +210,7 @@ Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -246,9 +230,7 @@ If you need to send a number by using the `res.send()` function, quote the numbe
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -267,9 +249,7 @@ The `res.sendfile()` function has been replaced by a camel-cased version `res.se
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Or you can update your code manually:
@@ -284,6 +264,10 @@ Or you can update your code manually:
The `hidden` and `from` options for `res.sendFile()` are no longer supported. Use `dotfiles` and `root` instead.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### How to update
```diff
@@ -293,12 +277,30 @@ The `hidden` and `from` options for `res.sendFile()` are no longer supported. Us
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### express.static() options
The `hidden` and `from` options for `express.static()` are no longer supported. Use `dotfiles` and `root` instead. Note that `from` was never documented in the API but was accepted as an alias for `root`. The default value of `dotfiles` is now `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### How to update
+You can automatically update your code by running the following command:
+
+
+
+Or you can update your code manually:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ The `hidden` and `from` options for `express.static()` are no longer supported.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### 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.
@@ -449,6 +458,25 @@ Serve specific dot-directories explicitly using the `dotfiles: "allow"` option.
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### How to update
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### 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.
diff --git a/src/content/pages/ko/resources/glossary.mdx b/src/content/pages/ko/resources/glossary.mdx
index 722d87bf44..5f7fff790f 100644
--- a/src/content/pages/ko/resources/glossary.mdx
+++ b/src/content/pages/ko/resources/glossary.mdx
@@ -27,7 +27,7 @@ A function that is invoked by the Express routing layer before the final request
- `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware.
- `app.use(mw)` is called _adding the middleware to the global processing stack_.
-- `app.get('/foo', mw, function (req, res) { ... })` is called _adding the middleware to the "GET /foo" processing stack_.
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/ko/resources/middleware/body-parser.mdx b/src/content/pages/ko/resources/middleware/body-parser.mdx
index 05dd86fc9e..82c968475b 100644
--- a/src/content/pages/ko/resources/middleware/body-parser.mdx
+++ b/src/content/pages/ko/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Node.js body parsing middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Other body parsers you might be interested in:
## Installation
-```sh
-$ npm install body-parser
-```
+
## API
@@ -112,7 +111,7 @@ to `'100kb'`.
The `reviver` option is passed directly to `JSON.parse` as the second
argument. You can find more information on this argument
-[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strict
diff --git a/src/content/pages/ko/resources/middleware/compression.mdx b/src/content/pages/ko/resources/middleware/compression.mdx
index f896116e97..17719320ff 100644
--- a/src/content/pages/ko/resources/middleware/compression.mdx
+++ b/src/content/pages/ko/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js compression middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/cookie-parser.mdx b/src/content/pages/ko/resources/middleware/cookie-parser.mdx
index 15d7e4b104..0ccd0bb0ba 100644
--- a/src/content/pages/ko/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/ko/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Parse HTTP request cookies
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/cookie-session.mdx b/src/content/pages/ko/resources/middleware/cookie-session.mdx
index 96de6ea703..f818929b63 100644
--- a/src/content/pages/ko/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/ko/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie session middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/cors.mdx b/src/content/pages/ko/resources/middleware/cors.mdx
index 3c33a19356..c70429abf1 100644
--- a/src/content/pages/ko/resources/middleware/cors.mdx
+++ b/src/content/pages/ko/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
@@ -39,9 +40,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Usage
diff --git a/src/content/pages/ko/resources/middleware/errorhandler.mdx b/src/content/pages/ko/resources/middleware/errorhandler.mdx
index 16839dc50a..7d784fd534 100644
--- a/src/content/pages/ko/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/ko/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Development-only error handler middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/index.mdx b/src/content/pages/ko/resources/middleware/index.mdx
new file mode 100644
index 0000000000..d335cab822
--- /dev/null
+++ b/src/content/pages/ko/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Description |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ This information refers to third-party sites, products, or modules that are not maintained by the
+ Expressjs team. Listing here does not constitute an endorsement or recommendation from the
+ Expressjs project team.
+
+
+| Middleware module | Description |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/ko/resources/middleware/method-override.mdx b/src/content/pages/ko/resources/middleware/method-override.mdx
index 0595f08d82..ed86353bd4 100644
--- a/src/content/pages/ko/resources/middleware/method-override.mdx
+++ b/src/content/pages/ko/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Override HTTP verbs
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/morgan.mdx b/src/content/pages/ko/resources/middleware/morgan.mdx
index 4568ece4b5..f63f59d98e 100644
--- a/src/content/pages/ko/resources/middleware/morgan.mdx
+++ b/src/content/pages/ko/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: HTTP request logger middleware for Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ If no format is given, then the default is `web`.
The HTTP version of the request.
-##### :method
+#####
The HTTP method of the request.
-##### :pid
+#####
The process ID of the Node.js process handling the request.
-##### :referrer
+#####
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
@@ -239,7 +238,7 @@ headers are written, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :status
+#####
The status code of the response.
@@ -255,7 +254,7 @@ has finished being written out to the connection, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :url
+#####
The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
diff --git a/src/content/pages/ko/resources/middleware/multer.mdx b/src/content/pages/ko/resources/middleware/multer.mdx
index 86f1ecd667..0558a87857 100644
--- a/src/content/pages/ko/resources/middleware/multer.mdx
+++ b/src/content/pages/ko/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware for handling multipart/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ This README is also available in other languages:
## Installation
-```sh
-$ npm install multer
-```
+
## Usage
@@ -284,15 +283,16 @@ An object specifying the size limits of the following optional properties. Multe
The following integer values are available:
-| Key | Description | Default |
-| --------------- | ----------------------------------------------------------------------- | --------- |
-| `fieldNameSize` | Max field name size | 100 bytes |
-| `fieldSize` | Max field value size (in bytes) | 1MB |
-| `fields` | Max number of non-file fields | Infinity |
-| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
-| `files` | For multipart forms, the max number of file fields | Infinity |
-| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
-| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| Key | Description | Default |
+| ------------------- | -------------------------------------------------------------------------- | --------- |
+| `fieldNameSize` | Max field name size | 100 bytes |
+| `fieldSize` | Max field value size (in bytes) | 1MB |
+| `fields` | Max number of non-file fields | Infinity |
+| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
+| `files` | For multipart forms, the max number of file fields | Infinity |
+| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
+| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Error handling
When encountering an error, Multer will delegate the error to Express. You can
diff --git a/src/content/pages/ko/resources/middleware/response-time.mdx b/src/content/pages/ko/resources/middleware/response-time.mdx
index 588ec099d7..4bda25039b 100644
--- a/src/content/pages/ko/resources/middleware/response-time.mdx
+++ b/src/content/pages/ko/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Response time for Node.js servers
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/serve-favicon.mdx b/src/content/pages/ko/resources/middleware/serve-favicon.mdx
index 73a788eb06..887862b21a 100644
--- a/src/content/pages/ko/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/ko/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon serving middleware with caching
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/serve-index.mdx b/src/content/pages/ko/resources/middleware/serve-index.mdx
index 912781757b..b49ab49eb3 100644
--- a/src/content/pages/ko/resources/middleware/serve-index.mdx
+++ b/src/content/pages/ko/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Serve directory listings
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/serve-static.mdx b/src/content/pages/ko/resources/middleware/serve-static.mdx
index 38af6fc42f..d9becdd2f5 100644
--- a/src/content/pages/ko/resources/middleware/serve-static.mdx
+++ b/src/content/pages/ko/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Serve static files
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/resources/middleware/session.mdx b/src/content/pages/ko/resources/middleware/session.mdx
index 17e2353d92..b9b1ba5fe4 100644
--- a/src/content/pages/ko/resources/middleware/session.mdx
+++ b/src/content/pages/ko/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Simple session middleware for Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Installation
@@ -18,9 +19,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -146,7 +145,8 @@ Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribut
More information about the different priority levels can be found in
[the specification][rfc-west-cookie-priority-00-4.1].
-**Note** This is an attribute that has not yet been fully standardized, and may change in the future.
+**Note** This is an attribute that has not yet been fully standardized, and may change in
+the future.
This also means many clients may ignore this attribute until they understand it.
##### cookie.sameSite
@@ -164,8 +164,7 @@ By default, this is `false`.
More information about the different enforcement levels can be found in
[the specification][rfc-6265bis-03-4.1.2.7].
-**Note** This is an attribute that has not yet been fully standardized, and may change in
-the future. This also means many clients may ignore this attribute until they understand it.
+**Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
**Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been
diff --git a/src/content/pages/ko/resources/middleware/timeout.mdx b/src/content/pages/ko/resources/middleware/timeout.mdx
index 4942e10a44..40fa16af93 100644
--- a/src/content/pages/ko/resources/middleware/timeout.mdx
+++ b/src/content/pages/ko/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Request timeout middleware for Connect/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Times out a request in the Connect/Express application framework.
@@ -20,9 +21,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/ko/resources/middleware/vhost.mdx b/src/content/pages/ko/resources/middleware/vhost.mdx
index 7d641e0a70..ecfb9c5daa 100644
--- a/src/content/pages/ko/resources/middleware/vhost.mdx
+++ b/src/content/pages/ko/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Virtual domain hosting
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/ko/support.md b/src/content/pages/ko/support.md
index d083fab364..8a814d9c44 100644
--- a/src/content/pages/ko/support.md
+++ b/src/content/pages/ko/support.md
@@ -7,14 +7,14 @@ Only the latest version of any given major release line is supported.
Versions that are EOL (end-of-life) _may_ receive updates for critical security vulnerabilities, but the Express team offers no guarantee and does not plan to address or release fixes for any issues found.
-| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
-| ------------------- | ----------------------- | ------------------ | ---------------- |
-| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
-| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
-| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | March 2011 | July 2012 |
-| **v1.x** | 0.2.0 | December 2010 | March 2011 |
-| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
+| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
+| -------------------------------------------------------------- | ----------------------- | ------------------ | ---------------- |
+| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
+| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
+| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | March 2011 | July 2012 |
+| **v1.x** | 0.2.0 | December 2010 | March 2011 |
+| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
## Commercial Support Options
diff --git a/src/content/pages/pt-br/advanced/best-practice-performance.md b/src/content/pages/pt-br/advanced/best-practice-performance.md
index 28b19c460a..7d6afa798f 100644
--- a/src/content/pages/pt-br/advanced/best-practice-performance.md
+++ b/src/content/pages/pt-br/advanced/best-practice-performance.md
@@ -33,7 +33,7 @@ Aqui estão algumas coisas que você pode fazer em seu código para melhorar o d
O compactação Gzip pode diminuir significativamente o tamanho do corpo da resposta e, assim, aumentar a velocidade de um aplicativo da web. Use o [compression](https://www.npmjs.com/package/compression) middleware para compressão gzip no seu aplicativo Express. Por exemplo:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-Para um sítio web de alto tráfego, em produção, a melhor maneira de colocar a compressão no lugar é implementá-la a um nível de proxy reverso (veja [usar um proxy reverso](#use-a-reverse-proxy)). Nesse caso, não é necessário utilizar um middleware de compressão. Para detalhes sobre como ativar a compressão gzip no Nginx, consulte [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) na documentação do Nginx.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### Não usar funções síncronas
+### Don't use synchronous functions
-Os métodos e funções síncríveis ligam o processo de execução até que retornam. Uma única chamada para uma função síncrona pode retornar em alguns microsegundos ou milissegundos, No entanto, em sites com alto tráfego, essas chamadas somam e reduzem o desempenho do aplicativo. Evite a sua utilização em produção.
+Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
-Embora o Node e muitos módulos fornecem versões sincronizadas e assíncronas de suas funções, sempre use a versão assíncrona em produção. O único momento em que uma função síncrona pode ser justificada é na inicialização inicial.
+Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
-Você pode usar o sinalizador de linha de comando `--trace-sync-io` para imprimir um aviso e um rastreamento de pilha sempre que seu aplicativo usar uma API síncrona. Claro, você não gostaria de usar isto em produção, mas sim de garantir que seu código esteja pronto para produção. Veja a [documentação de opções de linha de comando do nó](https://nodejs.org/api/cli.html#trace-sync-io) para mais informações.
+You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Faça o login corretamente
+### Do logging correctly
-Em geral, existem duas razões para registrar seu aplicativo: para depuração e para registrar a atividade do aplicativo (essencialmente, tudo o mais). Usar `console.log()` ou `console.error()` para imprimir mensagens de log no terminal é uma prática comum de desenvolvimento. Mas [essas funções são sincronizadas](https://nodejs.org/api/console.html#console) quando o destino é um terminal ou um arquivo, então eles não são adequados para produção, a menos que você canalize a saída para outro programa.
+In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### Para depuração
+#### For debugging
-Se você está logando para fins de depuração, em vez de usar `console.log()`, use um módulo de depuração especial, como [debug](https://www.npmjs.com/package/debug). Esse módulo permite que você use a variável de ambiente DEBUG para controlar quais mensagens de depuração são enviadas para `console.error()`, se houver. Para manter seu aplicativo puramente assíncrono, você ainda pode usar o comando `console.error()` para outro programa. Mas então, você realmente não vai depurar na produção, não é?
+If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
-#### Para atividades do aplicativo
+#### For app activity
-Se você está registrando a atividade do aplicativo (por exemplo, monitorando tráfego ou chamadas de API), em vez de usar o `console. og()`, use uma biblioteca de logs como [Pino](https://www.npmjs.com/package/pino), que é a opção mais rápida e eficiente disponível.
+If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
-### Manipular exceções corretamente
+### Handle exceptions properly
-Aplicativos do nó falham quando encontram uma exceção desmarcada. Não lidar com exceções e tomar as ações adequadas fará com que seu app Express pare de funcionar e fique offline. Se você seguir o conselho em [Verifique se seu aplicativo reinicia automaticamente](#ensure-your-app-automatically-restarts) abaixo, então seu aplicativo se recuperará de uma falha. Felizmente, os aplicativos Express normalmente têm um curto tempo de inicialização. No entanto, o senhor deputado quer evitar a queda, e, para isso, tem de tratar devidamente as excepções.
+Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
-Para garantir que você lida com todas as exceções, use as seguintes técnicas:
+To ensure you handle all exceptions, use the following techniques:
-- [Usar captura final](#use-try-catch)
-- [Usar promessas](#use-promises)
+- [Use try-catch](#use-try-catch)
+- [Use promises](#use-promises)
-Antes de mergulhar nestes tópicos, você deve ter um entendimento básico da manipulação de erro Node/Express: usar callback error first e propagar erros no middleware. O nó utiliza uma convenção "error-first callback" para retornar erros de funções assíncronas, onde o primeiro parâmetro para a função de callback é o objeto de erro, seguido pelos dados de resultado em parâmetros de sucesso. Para indicar nenhum erro, passe nulo como primeiro parâmetro. A função de callback deve seguir correspondentemente a convenção de callback error-first para lidar de forma significativa com o erro. E em Express, a melhor prática é usar a função next() para propagar erros através da cadeia de middleware.
+Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
-Para saber mais sobre os fundamentos da manipulação de erros, veja:
+For more on the fundamentals of error handling, see:
-- [Erro manipulando o Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Usar try-catch
+#### Use try-catch
-Try-catch é uma construção de idioma JavaScript que você pode usar para capturar exceções em código síncrono. Use a tentativa de captura, por exemplo, para lidar com erros de análise JSON, como mostrado abaixo.
+Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
-Aqui está um exemplo de utilização de capturas de tentativa para lidar com uma potencial exceção do crash do processo.
-Esta função middleware aceita um parâmetro de campo de consulta chamado "params" que é um objeto JSON.
+Here is an example of using try-catch to handle a potential process-crashing exception.
+This middleware function accepts a query field parameter named "params" that is a JSON object.
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-No entanto, a tentativa y-catch só funciona para código síncrono. Porque a plataforma Node é principalmente assíncrona (particularmente em ambiente de produção), a tentativa de captura não vai pegar muitas exceções.
+However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
-#### Usar promessas
+#### Use promises
-Quando um erro é lançado em uma função `async` ou uma promessa rejeitada é aguardada dentro de uma função `async`, esses erros serão passados para o manipulador de erros como se chamando `next(err)`
+When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-Além disso, você pode usar funções assíncronas para o seu middleware, e o roteador irá lidar com erros se a promessa falhar, por exemplo:
+Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-A melhor prática é lidar com os erros o mais próximo possível do site. Então enquanto isso é manipulado no roteador, É melhor encontrar o erro no middleware e lidar com ele sem depender de um middleware separado para manipular erros.
+Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
-#### O que não fazer
+#### What not to do
-Uma coisa que você não deveria fazer é ouvir o evento `uncaughtException`, emitido quando uma exceção bolha até o laço de repetição do evento. Adicionando um listener de eventos para `uncaughtException` mudará o comportamento padrão do processo que está encontrando uma exceção; o processo continuará a decorrer apesar da excepção. Isso pode soar como uma boa maneira de impedir que seu aplicativo caia, mas continuar a executar o aplicativo após uma exceção não detectada é uma prática perigosa e não é recomendado, porque o estado do processo se torna pouco fiável e imprevisível.
+One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
-Além disso, usar `uncaughtException` é oficialmente reconhecido como [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Então ouvir por `uncaughtException` é apenas uma má ideia. É por isso que recomendamos coisas como processos múltiplos e supervisores: falhar e reiniciar é muitas vezes a maneira mais confiável de recuperar de um erro.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
-Também não recomendamos o uso de [domains](https://nodejs.org/api/domain.html). Geralmente isso não resolve o problema e é um módulo obsoleto.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
-## Coisas a fazer no seu ambiente / configuração
+## Things to do in your environment / setup
-Aqui estão algumas coisas que você pode fazer em seu ambiente de sistema para melhorar o desempenho do seu aplicativo:
+Here are some things you can do in your system environment to improve your app's performance:
- [Definir NODE_ENV para "produção"](#set-node_env-to-production)
- [Verifique se seu aplicativo reinicia automaticamente](#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Aqui estão algumas coisas que você pode fazer em seu ambiente de sistema para
- [Usar um balanceador de carga](#use-a-load-balancer)
- [Usar um proxy reverso](#use-a-reverse-proxy)
-### Definir NODE_ENV para "produção"
+### Set NODE_ENV to "production"
-A variável de ambiente NODE_ENV especifica o ambiente em que uma aplicação está sendo executada (usualmente, desenvolvimento ou produção). Uma das coisas mais simples que você pode fazer para melhorar o desempenho é configurar NODE_ENV para `produção`.
+The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
-Definir NODE_ENV para "produção" faz Expressão:
+Setting NODE_ENV to "production" makes Express:
-- Modelos de exibição em cache.
-- Arquivos CSS do cache gerados a partir de extensões CSS.
-- Gerar mensagens de erro menos detalhadas.
+- Cache view templates.
+- Cache CSS files generated from CSS extensions.
+- Generate less verbose error messages.
-[Testes indicados](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) que apenas fazer isso pode melhorar o desempenho do aplicativo por um fator de três!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-Se você precisar escrever código de ambiente específico, você pode verificar o valor de NODE_ENV com `process.env.NODE_ENV`. Esteja ciente de que verificar o valor de qualquer variável de ambiente implica uma penalização de desempenho, assim como deve ser feito com moderação.
+If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
-No desenvolvimento, você normalmente define variáveis de ambiente em seu shell interativo, por exemplo, usando `export` ou seu arquivo `.bash_profile`. Mas, em geral, você não deve fazer isso em um servidor de produção; em vez disso, use o sistema init do seu SO (sistema). A próxima seção fornece mais detalhes sobre o uso do seu sistema de init em geral mas a configuração de `NODE_ENV` é tão importante para desempenho (e fácil de fazer), que é destacada aqui.
+In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
-Com o sistema, use a diretiva `Ambiente` no seu arquivo unitário. Por exemplo:
+With systemd, use the `Environment` directive in your unit file. Por exemplo:
```sh
Environment=NODE_ENV=production
```
-Para obter mais informações, consulte [Usando Variáveis de Ambiente em Unidades sistêmicas](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
-### Certifique-se de que seu aplicativo reinicie automaticamente
+### Ensure your app automatically restarts
-Em produção, você não quer que sua aplicação fique offline, nunca. Isto significa que você precisa ter certeza que ele reiniciará tanto se o aplicativo falhar e o próprio servidor falhar. Embora você espere que nenhum desses acontecimentos ocorra, realisticamente você deve ter em conta ambas as eventualidades por:
+In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
-- Usando um gerenciador de processo para reiniciar o aplicativo (e Node) quando ele travar.
-- Usando o sistema de init fornecido pelo seu sistema operacional para reiniciar o gerenciador de processos quando o sistema operacional travar. Também é possível usar o sistema sem um gerente de processo.
+- Using a process manager to restart the app (and Node) when it crashes.
+- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
-Aplicativos do nó falham se encontrarem uma exceção não capturada. A principal coisa que você precisa fazer é garantir que seu aplicativo seja bem testado e tenha todas as exceções (veja [handle exceptions correctly](#handle-exceptions-properly) para detalhes). Mas como falha, coloque um mecanismo em prática para garantir que se e quando o aplicativo parar de funcionar, ele será reiniciado automaticamente.
+Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
-#### Usar um gerenciador de processo
+#### Use a process manager
-Em desenvolvimento, você iniciou seu aplicativo simplesmente pela linha de comando com `node server.js` ou algo parecido. Mas fazer isto em produção é uma receita para o desastre. Se o aplicativo falhar, ele ficará offline até você reiniciá-lo. Para garantir que seu aplicativo seja reiniciado se ele falhar, use um gerenciador de processo. Um gerenciador de processo é um "container" para aplicativos que facilitam a implantação, fornece alta disponibilidade, e permite que você gerencie o aplicativo em tempo de execução.
+In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
-Além de reiniciar seu aplicativo quando ele falhar, um gerente de processo pode habilitá-lo:
+In addition to restarting your app when it crashes, a process manager can enable you to:
-- Receba informações sobre o desempenho da execução e o consumo de recursos.
-- Modifique as configurações dinamicamente para melhorar o desempenho.
-- Controle agrupamento (pm2).
+- Gain insights into runtime performance and resource consumption.
+- Modify settings dynamically to improve performance.
+- Control clustering (pm2).
-Historicamente, foi popular usar um gerente de processo Node.js como [PM2](https://github.com/Unitech/pm2). Veja a documentação deles, se você quiser fazer isso. No entanto, recomendamos a utilização de seu sistema de init para gerenciamento de processos.
+Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
-#### Usar um sistema de entrada
+#### Use an init system
-A próxima camada de confiabilidade é garantir que seu aplicativo seja reiniciado quando o servidor reiniciar. Os sistemas ainda podem descer por diversas razões. Para garantir que seu aplicativo seja reiniciado se o servidor falhar, use o sistema incorporado no seu sistema operacional. O sistema principal de init em uso hoje é [systemd](https://wiki.debian.org/systemd).
+The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
-Existem duas maneiras de usar sistemas de entrada com seu aplicativo Express:
+There are two ways to use init systems with your Express app:
-- Execute seu aplicativo em um gerenciador de processo e instale o gerente de processo como um serviço com o sistema de init. O gerenciador de processos irá reiniciar seu aplicativo quando o aplicativo falhar, e o sistema inicial irá reiniciar o gerenciador de processos quando o sistema operacional for reiniciado. Esta é a abordagem recomendada.
-- Execute seu aplicativo (e Node) diretamente com o sistema init. Isto é um pouco mais simples, mas você não obtém as vantagens adicionais de usar um gerenciador de processo.
+- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
+- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
##### Systemd
-O Systemd é um gerenciador de serviços e sistema Linux. A maioria das principais distribuições de Linux adotaram o sistema como sistema de init padrão.
+Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
-Um arquivo de configuração de serviço systemd é chamado de _unit file_, com um nome de arquivo terminando em `.service`. Aqui está um exemplo de arquivo unitário para gerenciar um aplicativo Node diretamente. Substitua os valores colocados em \`para o seu sistema e aplicativo:
+A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -240,29 +249,29 @@ Restart=always
WantedBy=multi-user.target
```
-Para obter mais informações sobre o sistema, consulte a [referência do sistema (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
+For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Executar seu aplicativo em um cluster
+### Run your app in a cluster
-Em um sistema multi-núcleo, você pode aumentar o desempenho de um aplicativo Node muitas vezes, iniciando um cluster de processos. Um cluster executa várias instâncias do aplicativo, idealmente uma instância em cada núcleo da CPU, distribuindo assim a carga e tarefas entre as instâncias.
+In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
-
+
-IMPORTANTE: Como as instâncias do aplicativo são executadas como processos separados, eles não compartilham o mesmo espaço de memória. Ou seja, objetos são locais para cada instância do aplicativo. Por conseguinte, não pode manter o estado no código de candidatura. No entanto, você pode usar um datastore na memória como [Redis](http://redis.io/) para armazenar dados e estado relacionados à sessão. Esta ressalva se aplica essencialmente a todas as formas de escala horizontal, seja agrupamento com vários processos ou vários servidores físicos.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
-Em apps agrupados, os processos dos trabalhadores podem falhar individualmente sem afetar o resto dos processos. Além das vantagens de desempenho, isolamento de falhas é outra razão para executar um agrupamento de processos de aplicativos. Sempre que um processo do worker parar de funcionar, tenha certeza de registrar o evento e gerar um novo processo usando cluster.fork().
+In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
-#### Usando módulo de cluster do Node
+#### Using Node's cluster module
-É possível agrupar com o [módulo cluster do Node](https://nodejs.org/api/cluster.html). Isto permite a um processo mestre gerar processos de trabalhadores e distribuir conexões de entrada entre os trabalhadores.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
-#### Usando PM2
+#### Using PM2
-Se você publicar sua aplicação com PM2, então você pode aproveitar o clustering _without_ para modificar o código da sua aplicação. Você deve garantir sua [inscrição sem estado](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) primeiro, significando que nenhum dado local é armazenado no processo (como sessões, conexões de websocket e coisas parecidas).
+If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
-Ao executar um aplicativo com PM2, você pode habilitar o **modo de agrupamento** para executá-lo em um cluster com várias instâncias de sua escolha, como o número de CPUs disponíveis na máquina. Você pode alterar manualmente o número de processos no cluster usando a ferramenta de linha de comando `pm2` sem parar o aplicativo.
+When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
-Para ativar o modo de agrupamento, inicie seu aplicativo assim:
+To enable cluster mode, start your application like so:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-Isto também pode ser configurado em um arquivo de processo PM2 (`ecosystem.config. s` ou similar) definindo `exec_mode` para `cluster` e `instâncias` para o número de trabalhadores para começar.
+This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
-Ao executar, o aplicativo pode ser dimensionado assim:
+Once running, the application can be scaled like so:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-Para obter mais informações sobre agrupamento com PM2, consulte [Modo Cluster](https://pm2.keymetrics.io/docs/usage/cluster-mode/) na documentação PM2.
+For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
-### Resultados da requisição em cache
+### Cache request results
-Outra estratégia para melhorar o desempenho em produção é armazenar em cache o resultado das solicitações, para que seu aplicativo não repita a operação para atender o mesmo pedido repetidamente.
+Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Use um servidor de cache como [Varnish](https://www.varnish-cache.org/) ou [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (veja também [Nginx Caching](https://serversforhackers.com/nginx-caching/)) para melhorar muito a velocidade e o desempenho de sua aplicação.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Use um balanceador de carga
+### Use a load balancer
-Não importa o quão otimizado um app seja, uma única instância pode manipular apenas uma quantidade limitada de carga e tráfego. Uma maneira de expandir um aplicativo é rodando várias instâncias dele e distribuindo o tráfego através de um balanceador de carga. Configurar um balanceador de carga pode melhorar o desempenho e a velocidade do seu aplicativo, e habilitá-lo a escalar mais do que é possível com uma única instância.
+No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
-Um balanceador de carga geralmente é um proxy reverso que orqualiza o tráfego de e para a partir de várias instâncias de aplicativos e servidores. Você pode facilmente configurar um balanceador de carga para o seu aplicativo usando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
+A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-Com o balanceamento de carga, você pode ter que garantir que os pedidos que estão associados a um determinado ID de sessão estejam conectados ao processo que os originou. Isto é conhecido como afinidade de sessão, ou _sessões fixas_, e pode ser abordado pela sugestão acima para usar um armazenamento de dados, como Redis para dados de sessão (dependendo do seu aplicativo). Para uma discussão, consulte [Usando múltiplos nós](https://socket.io/docs/v4/using-multiple-nodes/).
+With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
-### Usar um proxy reverso
+### Use a reverse proxy
-Um proxy reverso está na frente de um aplicativo web e executa operações de suporte sobre as solicitações, além de direcionar solicitações para o aplicativo. Ele pode lidar com páginas de erro, compressão, cache, arquivos de servidor, e o equilíbrio de carga entre outras coisas.
+A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Atingir tarefas que não exigem conhecimento do estado do aplicativo para um proxy reverso libera o Express para executar tarefas de aplicativo especializado. Por este motivo, é recomendado executar Expresso atrás de um proxy reverso como [Nginx](https://www.nginx.org/) ou [HAProxy](https://www.haproxy.org/) em produção.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/pt-br/advanced/best-practice-security.mdx b/src/content/pages/pt-br/advanced/best-practice-security.mdx
index bad8f24730..b821796093 100644
--- a/src/content/pages/pt-br/advanced/best-practice-security.mdx
+++ b/src/content/pages/pt-br/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Descubra as melhores práticas de segurança cruciais para aplicati
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
O termo _"produção"_ se refere ao estágio no ciclo de vida do software quando uma aplicação ou API está geralmente disponível para seus usuários finais ou consumidores. Em contraste, na etapa "development"\__ , você ainda está escrevendo e testando o código, e o aplicativo não está aberto para acesso externo. Os ambientes de sistema correspondentes são conhecidos como ambientes de \_produção_ e _desenvolvimento_, respectivamente.
@@ -18,21 +19,19 @@ Políticas e Procedimentos.
As melhores práticas de segurança para aplicações Expressas na produção incluem:
-- [Práticas de Melhor Produção: Segurança](#production-best-practices-security)
- - [Overview](#overview)
- - [Não usar versões descontinuadas ou vulneráveis do Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Usar TLS](#use-tls)
- - [Não confie na entrada do usuário](#do-not-trust-user-input)
- - [Impedir redirecionamentos abertos](#prevent-open-redirects)
- - [Usar capacete](#use-helmet)
- - [Reduzir impressão digital](#reduce-fingerprinting)
- - [Usar cookies de forma segura](#use-cookies-securely)
- - [Não usar o nome padrão de cookie da sessão](#dont-use-the-default-session-cookie-name)
- - [Definir opções de segurança de cookies](#set-cookie-security-options)
- - [Impedir ataques brute-force contra a autorização](#prevent-brute-force-attacks-against-authorization)
- - [Garanta que suas dependências sejam seguras](#ensure-your-dependencies-are-secure)
- - [Evitar outras vulnerabilidades conhecidas](#avoid-other-known-vulnerabilities)
- - [Considerações adicionais](#additional-considerations)
+- [Não usar versões descontinuadas ou vulneráveis do Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Usar TLS](#use-tls)
+- [Não confie na entrada do usuário](#do-not-trust-user-input)
+ - [Impedir redirecionamentos abertos](#prevent-open-redirects)
+- [Usar capacete](#use-helmet)
+- [Reduzir impressão digital](#reduce-fingerprinting)
+- [Usar cookies de forma segura](#use-cookies-securely)
+ - [Não usar o nome padrão de cookie da sessão](#dont-use-the-default-session-cookie-name)
+ - [Definir opções de segurança de cookies](#set-cookie-security-options)
+- [Impedir ataques brute-force contra a autorização](#prevent-brute-force-attacks-against-authorization)
+- [Garanta que suas dependências sejam seguras](#ensure-your-dependencies-are-secure)
+ - [Evitar outras vulnerabilidades conhecidas](#avoid-other-known-vulnerabilities)
+- [Considerações adicionais](#additional-considerations)
## Não usar versões obsoletas ou vulneráveis do Express
@@ -44,7 +43,7 @@ Certifique-se também de que você não está usando nenhuma das versões vulner
Se seu aplicativo lida com ou transmite dados confidenciais, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) para proteger a conexão e os dados. Esta tecnologia criptografa dados antes de ser enviada do cliente para o servidor, impedindo assim alguns hackers comuns (e fáceis). Embora solicitações do Ajax e POST não sejam óbvias e pareçam "ocultas" nos navegadores, seu tráfego de rede está vulnerável ao [sniffing de pacotes](https://en.wikipedia.org/wiki/Packet_analyzer) e [ataques do meio](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-Você deve estar familiarizado com a criptografia Secure Socket Layer (SSL). [TLS é simplesmente a próxima progressão do SSL](). Em outras palavras, se você estava usando SSL antes, considere atualizar para o TLS. Em geral, recomendamos o Nginx para lidar com TLS. Para uma boa referência para configurar TLS no Nginx (e outros servidores), consulte [Configurações de servidores recomendadas (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+Você deve estar familiarizado com a criptografia Secure Socket Layer (SSL). Em geral, recomendamos o Nginx para lidar com TLS. Em outras palavras, se você estava usando SSL antes, considere atualizar para o TLS. Em outras palavras, se você estava usando SSL antes, considere atualizar para o TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Além disso, uma ferramenta prática para obter um certificado TLS gratuito é [Let's Encrypt](https://letsencrypt.org/about/), uma ferramenta gratuita, automatizada, e abrir autoridade certificadora (CA) fornecida pelo [Grupo de Investigação de Segurança da Internet (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Cada cabeçalho pode ser configurado ou desativado. Para ler mais sobre isso, po
Instalar o Capacete como qualquer outro módulo:
-```bash
-$ npm install helmet
-```
+
Então para usá-lo em seu código:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Reduzir impressão digital
Ele pode ajudar a fornecer uma camada extra de segurança para reduzir a capacidade dos invasores de determinar
@@ -177,7 +184,7 @@ Usar o nome padrão de cookie de sessão pode abrir seu aplicativo para ataques.
Para evitar este problema, use nomes genéricos de cookie, por exemplo, usando [express-session](https://www.npmjs.com/package/express-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Definir opções de segurança do cookie
Defina as seguintes opções de cookies para aumentar a segurança:
@@ -200,7 +219,7 @@ Defina as seguintes opções de cookies para aumentar a segurança:
Aqui está um exemplo usando [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Evite ataques brutos contra autorização
Certifique-se de que os endpoints de login estejam protegidos para tornar os dados privados mais seguros.
@@ -259,7 +300,7 @@ $ snyk test
### Evitar outras vulnerabilidades conhecidas
-Fique de olho nos conselhos [Node Security Project](https://npmjs.com/advisories) ou [Snyk](https://snyk.io/vuln/) que possam afetar os módulos Express ou outros que seu aplicativo usa. Em geral, estas bases de dados são excelentes recursos para o conhecimento e ferramentas sobre a segurança dos Nós.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. Em geral, estas bases de dados são excelentes recursos para o conhecimento e ferramentas sobre a segurança dos Nós.
Finalmente, Aplicativos Expressos—como qualquer outro aplicativo da web—podem ser vulneráveis a uma variedade de ataques baseados na web. Familiarize-se com as conhecidas [vulnerabilidades da web](https://www.owasp.org/www-project-top-ten/) e tome precauções para evitá-las.
diff --git a/src/content/pages/pt-br/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/pt-br/advanced/healthcheck-graceful-shutdown.md
index 392c97191a..8899ffc113 100644
--- a/src/content/pages/pt-br/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/pt-br/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Exercícios de saúde
-Um balanceador de carga usa verificações de saúde para determinar se uma instância do aplicativo é saudável e pode aceitar pedidos. Por exemplo, [Kubernetes tem dois exames de saúde](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+Um balanceador de carga usa verificações de saúde para determinar se uma instância do aplicativo é saudável e pode aceitar pedidos. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, isso determina quando reiniciar um contêiner.
- `pronto`, que determina quando um recipiente está pronto para começar a aceitar tráfego. Quando um pod não está pronto, é removido dos balanceadores de carga de serviço.
diff --git a/src/content/pages/pt-br/advanced/security-updates.mdx b/src/content/pages/pt-br/advanced/security-updates.mdx
index 0d7c132178..37c489398c 100644
--- a/src/content/pages/pt-br/advanced/security-updates.mdx
+++ b/src/content/pages/pt-br/advanced/security-updates.mdx
@@ -39,7 +39,7 @@ Políticas e Procedimentos.
- 4.17.3
- A dependência `qs` foi atualizada para o endereço [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp). Isso pode afetar sua aplicação se as seguintes APIs forem usadas: `req.query`, `req.body`, `req.param`.
- 4.16.0
- - A dependência `encaminhado` foi atualizada para o endereço [vulnerability](https://npmjs.com/advisories/527). Isso pode afetar sua aplicação se as seguintes APIs forem usadas: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
+ - The dependency `forwarded` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-mpcf-4gmh-23w8). Isso pode afetar sua aplicação se as seguintes APIs forem usadas: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
- A dependência `mime` foi atualizada para endereçar um [vulnerability](https://npmjs.com/advisories/535), mas esta issue não afeta o Express.
- A dependência `send` foi atualizada para fornecer uma proteção contra uma [Node.js 8.5.0 vulnerabilidade](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Isso só afeta a execução do Express na versão 8.5.0 específica do Node.js.
- 4.15.5
diff --git a/src/content/pages/pt-br/guide/database-integration.mdx b/src/content/pages/pt-br/guide/database-integration.mdx
index b1e7637db2..f2e1510e6e 100644
--- a/src/content/pages/pt-br/guide/database-integration.mdx
+++ b/src/content/pages/pt-br/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Descubra como integrar vários bancos de dados com aplicações do
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Adicionar a capacidade de conectar bancos de dados aos aplicativos Express é apenas uma questão de carregar um driver Node.js apropriado para o banco de dados em seu aplicativo. Este documento explica brevemente como adicionar e usar alguns dos mais populares módulos Node.js para os sistemas de banco de dados no seu aplicativo Express:
@@ -34,13 +35,11 @@ Estes motoristas da base de dados estão entre muitos que estão disponíveis. P
### Instalação
-```bash
-$ npm install cassandra-driver
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
-**Módulo**: [couchnode](https://github.com/couchbase/couchnode)
+**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Instalação
-```bash
-$ npm install couchbase
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
-**Módulo**: [nano](https://github.com/dscape/nano)
+**Module**: [nano](https://github.com/dscape/nano)
### Instalação
-```bash
-$ npm install nano
-```
+
### Exemplo
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -125,17 +157,15 @@ books.list((err, body) => {
## LevelDB
-**Módulo**: [levelup](https://github.com/rvagg/node-levelup)
+**Module**: [levelup](https://github.com/rvagg/node-levelup)
### Instalação
-```bash
-$ npm install level levelup leveldown
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
-**Módulo**: [mysql](https://github.com/felixge/node-mysql/)
+**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Instalação
-```bash
-$ npm install mysql
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
-**Módulo**: [mongodb](https://github.com/mongodb/node-mongodb-native)
+**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Instalação
-```bash
-$ npm install mongodb
-```
+
-### Exemplo (v2.\*)
+### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -210,9 +273,9 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
});
```
-### Exemplo (v3.\*)
+### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -230,21 +293,19 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
});
```
-Se você quer um driver de objeto para MongoDB, olhe para [Mongoose](https://github.com/LearnBoost/mongoose).
+If you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).
## Neo4j
-**Módulo**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
+**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
### Instalação
-```bash
-$ npm install neo4j-driver
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +323,38 @@ session.readTransaction((tx) => {
});
```
-## Orátopo
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
-**Módulo**: [oracledb](https://github.com/oracle/node-oracledb)
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
+## Oracle
+
+**Module**: [oracledb](https://github.com/oracle/node-oracledb)
### Instalação
-NOTA: [Ver pré-requisitos de instalação](https://github.com/oracle/node-oracledb#-installation).
+NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
-**Módulo**: [pg-promise](https://github.com/vitaly-t/pg-promise)
+**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Instalação
-```bash
-$ npm install pg-promise
-```
+
### Exemplo
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -333,17 +440,15 @@ db.one('SELECT $1 AS value', 123)
## Redis
-**Módulo**: [redis](https://github.com/mranney/node_redis)
+**Module**: [redis](https://github.com/mranney/node_redis)
### Instalação
-```bash
-$ npm install redis
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
-## Servidor SQL
+```mjs title="index.mjs"
+import redis from 'redis';
-**Módulo**: [tedious](https://github.com/tediousjs/tedious)
+const client = redis.createClient();
-### Instalação
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
-```bash
-$ npm install tedious
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
```
+## SQL Server
+
+**Module**: [tedious](https://github.com/tediousjs/tedious)
+
+### Instalação
+
+
+
### Exemplo
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -429,17 +556,15 @@ function executeStatement() {
## SQLite
-**Módulo**: [sqlite3](https://github.com/mapbox/node-sqlite3)
+**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
### Instalação
-```bash
-$ npm install sqlite3
-```
+
### Exemplo
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -463,17 +588,15 @@ db.close();
## Elasticsearch
-**Módulo**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
+**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
### Instalação
-```bash
-$ npm install elasticsearch
-```
+
### Exemplo
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/pt-br/guide/migrating-4.mdx b/src/content/pages/pt-br/guide/migrating-4.mdx
index 6a8e2d47ef..203ac74cd2 100644
--- a/src/content/pages/pt-br/guide/migrating-4.mdx
+++ b/src/content/pages/pt-br/guide/migrating-4.mdx
@@ -4,39 +4,23 @@ description: Um guia para migrar seus aplicativos Express.js da versão 3 para 4
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Expresso 4 é uma mudança quebrada do Express 3. Isso significa que um aplicativo Expresso 3 não funcionará se você atualizar a versão Expresso em suas dependências.
Cobertos deste artigo:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Mudanças no Express 4
Há várias mudanças significativas na Expresso 4:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
Ver também:
@@ -59,7 +43,7 @@ que é necessário para executar seu aplicativo. Basta seguir estes passos:
A seguinte tabela lista Express 3 middleware e seus homólogos no Express 4.
-
+
| Expressar 3 |
Express 4 |
@@ -252,7 +236,7 @@ ele, define algumas rotas e o conecta em um caminho no aplicativo principal.
Por exemplo, crie um arquivo de roteador chamado `birds.js` no diretório de aplicativos,
com o seguinte conteúdo:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Em seguida, carregue o módulo do roteador no aplicativo:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
Agora o aplicativo será capaz de lidar com pedidos para os caminhos `/birds` e
`/birds/about`, e irá chamar o middleware `timeLog`
que é específico da rota.
@@ -291,16 +305,14 @@ que é específico da rota.
A tabela a seguir lista outras pequenas mas importantes mudanças no Express 4:
-
+
| Object |
Descrição |
| Node.js |
-
- Express 4 requer Node.js 0.10.x ou posterior e tem abandonado o suporte para Node.js 0.8.
- |
+ Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
| `http.createServer()` |
@@ -377,7 +389,7 @@ Os arquivos de interesse são `app.js` e `package.json`.
Considere um aplicativo Express v.3 com o seguinte arquivo `app.js`:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -411,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
O arquivo de acompanhamento da versão 3 `package.json` pode parecer
@@ -437,9 +483,7 @@ Inicie o processo de migração instalando o middleware necessário para o aplic
Express 4 e atualize o Express e o Pug para sua respectiva versão
mais recente com o seguinte comando:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Faça as seguintes alterações no `app.js`:
@@ -489,7 +533,7 @@ Executar o comando `npm` acima atualizará o `package.json` da seguinte forma:
Then, remove invalid code, load the required middleware, and make other
changes as necessary. O arquivo `app.js` será parecido com este:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -539,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
A menos que você precise trabalhar diretamente com o módulo 'http' (socket.io/SPDY/HTTPS), carregá-lo não é necessário, e o aplicativo pode ser simplesmente iniciado dessa forma:
@@ -574,18 +667,14 @@ o gerador de aplicativo Express 3 e então instalar o novo gerador
Se você já tiver o gerador de aplicativo Express 3 instalado em seu sistema,
você deve desinstalá-lo:
-```bash
-$ npm uninstall -g express
-```
+
Dependendo de como seus privilégios de arquivo e diretório são configurados,
talvez você precise executar este comando com `sudo`.
Agora instale o novo gerador:
-```bash
-$ npm install -g express-generator
-```
+
Dependendo de como seus privilégios de arquivo e diretório são configurados,
talvez você precise executar este comando com `sudo`.
diff --git a/src/content/pages/pt-br/guide/migrating-5.mdx b/src/content/pages/pt-br/guide/migrating-5.mdx
index fa67b7a187..3e78160c27 100644
--- a/src/content/pages/pt-br/guide/migrating-5.mdx
+++ b/src/content/pages/pt-br/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: Um guia completo para migrar seus aplicativos Express.js da versão
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Expresso 5 não é muito diferente do Express 4; embora ele mantenha a mesma API básica, ainda há mudanças que quebram a compatibilidade com a versão anterior. Portanto, um aplicativo construído com Express 4 pode não funcionar se você atualizá-lo para usar o Express 5.
@@ -11,9 +12,7 @@ Expresso 5 não é muito diferente do Express 4; embora ele mantenha a mesma API
Para instalar esta versão, você precisa ter uma \*\*versão 18 ou superior do Node.js. Em seguida, execute o seguinte comando em seu diretório de aplicativos:
-```sh
-npm install "express@5"
-```
+
Você pode então executar seus testes automatizados para ver o que falhou e corrigir problemas de acordo com as atualizações listadas abaixo. Após falhas no teste, execute seu aplicativo para ver quais erros ocorrem. Você vai descobrir imediatamente se o aplicativo usa quaisquer métodos ou propriedades que não são suportadas.
@@ -23,15 +22,11 @@ Para ajudá-lo a migrar seu servidor expresso, nós criamos um conjunto de codem
Execute o seguinte comando para executar todos os codemods disponíveis:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
Se você quiser executar um código específico, você pode executar o seguinte comando:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
Você pode encontrar a lista de codemods disponíveis [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Inicialmente, `del` foi usado em vez de `delete`, porque `delete` é uma palavra
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Ou você pode atualizar seu código manualmente:
@@ -80,9 +73,7 @@ Os nomes dos seguintes métodos foram pluralizados. No Express 4, a utilização
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Ou você pode atualizar seu código manualmente:
@@ -101,9 +92,9 @@ Ou você pode atualizar seu código manualmente:
### Posicionando dois pontos (:) no nome do app.param(name, fn)
-Um personagem com dois pontos principais (:) no nome do `app. aram(name, fn)` é um remanescente do Express 3, e por uma questão de compatibilidade retrógrada, Express 4 apoiou-o com um aviso de depreciação. Expresso 5 irá ignorá-lo silenciosamente e usar o parâmetro de nome sem prefixá-lo com dois-pontos.
+No Expresso 4, os caracteres curinga eram strings vazias (`''`) e parâmetros opcionais `:` (usando `?`) tinham uma chave com valor `undefined`. No Expresso 5, parâmetros não correspondentes são completamente omitidos de `req.params`.
-Isso não deve afetar o seu código se você seguir a documentação Express 4 do [app.param](/4x/api#app.param), uma vez que não faz qualquer menção ao casal principal.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(nome)
@@ -113,9 +104,7 @@ Este método potencialmente confuso e perigoso de recuperação de dados de form
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Ou você pode atualizar seu código manualmente:
@@ -140,9 +129,7 @@ Expresso 5 não suporta mais a assinatura `res.json(obj, status)`. Ao invés dis
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou você pode atualizar seu código manualmente:
@@ -161,9 +148,7 @@ Expresso 5 não suporta mais a assinatura `res.jsonp(obj, status)`. Ao invés di
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou você pode atualizar seu código manualmente:
@@ -182,16 +167,19 @@ Expresso 5 não suporta mais a assinatura `res.redirect(url, status)`. Ao invés
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Ou você pode atualizar seu código manualmente:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Expresse 5 não suporta mais a string mágica `back` nos métodos `res.redirect(
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Ou você pode atualizar seu código manualmente:
@@ -224,9 +210,7 @@ Expresso 5 não suporta mais a assinatura `res.send(obj, status)`. Em vez disso,
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou você pode atualizar seu código manualmente:
@@ -246,9 +230,7 @@ Se você precisar enviar um número usando os `res. função end()`, cita o núm
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Ou você pode atualizar seu código manualmente:
@@ -267,9 +249,7 @@ A função `res.sendfile()` foi substituída por uma versão caída por camelo `
Você pode atualizar seu código automaticamente executando o seguinte comando:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Ou você pode atualizar seu código manualmente:
@@ -284,6 +264,10 @@ Ou você pode atualizar seu código manualmente:
As opções `hidden` e` from` para `res.sendFile()` não são mais suportadas. Use `dotfiles` e `root` em vez disso.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### Como atualizar
```diff
@@ -293,12 +277,30 @@ As opções `hidden` e` from` para `res.sendFile()` não são mais suportadas. U
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### Opções de express.static()
As opções `hidden` e` from` para `express.static()` não são mais suportadas. Use `dotfiles` e `root` em vez disso. Note que 'de' nunca foi documentado na API mas foi aceito como um alias para 'root'. O valor padrão de `dotfiles` agora é `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### Como atualizar
+Você pode atualizar seu código automaticamente executando o seguinte comando:
+
+
+
+Ou você pode atualizar seu código manualmente:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ As opções `hidden` e` from` para `express.static()` não são mais suportadas.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### router.param(fn)
A assinatura `router.param(fn)` foi usada para modificar o comportamento da função `router.param(name, fn)`. Está obsoleto desde a versão 4.11.0, e Express 5 não apoia mais nada.
@@ -449,6 +458,25 @@ Serve diretórios de pontos específicos usando explicitamente os `dotfiles: op
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### Como atualizar
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### Ouvir
No Express 5, o método `app.listen` invocará a função de callback fornecido pelo usuário (se fornecido) quando o servidor receber um evento de erro. Na Expressa 4, esses erros seriam lançados. Essa mudança desloca a responsabilidade da manipulação de erros para a função de retorno de chamada no Express 5. Se houver um erro, ele será passado para o callback como argumento.
diff --git a/src/content/pages/pt-br/resources/contributing.mdx b/src/content/pages/pt-br/resources/contributing.mdx
index 220d1f7a3c..3ab166d957 100644
--- a/src/content/pages/pt-br/resources/contributing.mdx
+++ b/src/content/pages/pt-br/resources/contributing.mdx
@@ -90,8 +90,7 @@ se você tiver dúvidas ou precisar de orientação.
### Tornando-se um Compromissor
-Todos os colaboradores que pouparam contribuições significativas e valiosas devem ser integrados em tempo hábil.
-e adicionado como um commit, e ser dado acesso de gravação ao repositório.
+Todos os colaboradores que pouparam contribuições significativas e valiosas devem ser integrados em tempo hábil. e adicionado como um commit, e ser dado acesso de gravação ao repositório.
Espera-se que os compromissos sigam esta política e continuem enviando pull requests, passe por
uma revisão adequada e tenha outros committers que juntem seus pull requests.
diff --git a/src/content/pages/pt-br/resources/glossary.mdx b/src/content/pages/pt-br/resources/glossary.mdx
index 91600b4d05..8a5360cdad 100644
--- a/src/content/pages/pt-br/resources/glossary.mdx
+++ b/src/content/pages/pt-br/resources/glossary.mdx
@@ -27,7 +27,7 @@ Uma função que é invocada pela camada de roteamento Express antes do manipula
- `var foo = require('middleware')` é chamado de _requiring_ ou _usando_ um módulo Node.js. Então, a instrução `var mw = foo()` normalmente retorna o middleware.
- `app.use(mw)` é chamado de _adicionando o middleware à pilha de processamento global_.
-- `app.get('/foo', mw, função (req, res) { ... })` é chamado de _adicionando o middleware para a pilha de processamento "GET /foo"_.
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/pt-br/resources/index.mdx b/src/content/pages/pt-br/resources/index.mdx
index 4ff9e5c512..e0fd539333 100644
--- a/src/content/pages/pt-br/resources/index.mdx
+++ b/src/content/pages/pt-br/resources/index.mdx
@@ -17,13 +17,13 @@ Encontre recursos para ajudar você a aprender, contribuir e se conectar com o e
@@ -35,7 +35,7 @@ Encontre recursos para ajudar você a aprender, contribuir e se conectar com o e
diff --git a/src/content/pages/pt-br/resources/middleware/body-parser.mdx b/src/content/pages/pt-br/resources/middleware/body-parser.mdx
index f60f2fb68b..3ec05e5d90 100644
--- a/src/content/pages/pt-br/resources/middleware/body-parser.mdx
+++ b/src/content/pages/pt-br/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Analisando o Node.js corpo do middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Outros analisadores de corpo que você pode interessar:
## Instalação
-```sh
-$ npm install body-parser
-```
+
## API
@@ -111,8 +110,8 @@ para `'100kb'`.
##### reviver
A opção `reviver` é passada diretamente para `JSON.parse` como o segundo argumento
-. Você pode encontrar mais informações sobre este argumento
-[na documentação MDN sobre JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### estrito
diff --git a/src/content/pages/pt-br/resources/middleware/compression.mdx b/src/content/pages/pt-br/resources/middleware/compression.mdx
index 3b7107c19f..5e56cd8ca7 100644
--- a/src/content/pages/pt-br/resources/middleware/compression.mdx
+++ b/src/content/pages/pt-br/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Compressão de Node.js middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/cookie-parser.mdx b/src/content/pages/pt-br/resources/middleware/cookie-parser.mdx
index 64f544ffd9..53af80943e 100644
--- a/src/content/pages/pt-br/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/pt-br/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Analisar cookies de solicitação HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/cookie-session.mdx b/src/content/pages/pt-br/resources/middleware/cookie-session.mdx
index 508a165a0d..a20cd3795f 100644
--- a/src/content/pages/pt-br/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/pt-br/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Meio de sessão de cookies
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/cors.mdx b/src/content/pages/pt-br/resources/middleware/cors.mdx
index 3f9d6b2eb7..e3ec44246c 100644
--- a/src/content/pages/pt-br/resources/middleware/cors.mdx
+++ b/src/content/pages/pt-br/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS é um [Node.js](https://nodejs.org/en/) middleware para [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) que define os cabeçalhos de resposta [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS). Estes cabeçalhos indicam aos navegadores que originam as respostas do seu servidor.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. Estes cabeçalhos indicam aos navegadores que originam as respostas do seu servidor.
@@ -39,9 +40,7 @@ Este é um módulo [Node.js](https://nodejs.org/en/) disponível através do
[registro do npm](https://www.npmjs.com/). A instalação é feita usando o comando
[`npm install`](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Utilização
@@ -232,7 +231,7 @@ app.listen(80, function () {
- `origin`: Configura o cabeçalho CORS **Access-Control-Allow-Origin**. Valores possíveis:
- `Boolean` - defina `origin` como `true` para refletir a [origem da solicitação](https://datatracker.ietf.org/doc/html/draft-abarth-origin-09), conforme definido por `req.header('Origin')`, ou defina-o como `false` para desabilitar CORS.
- `String` - defina `origin` para uma origem específica. Por exemplo, se você definir isso para
- - `"http://example.com"` somente requisições de "http://example.com" serão permitidas.
+ - Será permitido "http://example.com"\` somente requisições de "http://example.com" .
- `"*"` para todos os domínios serem permitidos.
- `RegExp` - define `origin` para um padrão de expressão regular que será usado para testar a origem da solicitação. Se for uma correspondência, a origem do pedido será refletida. Por exemplo, o padrão `/example\.com$/` irá refletir qualquer solicitação que esteja vindo de uma origem que termina com "example.com".
- `Array` - defina `origin` para uma matriz de origens válidas. Cada origem pode ser uma `String` ou um `RegExp`. Por exemplo, `["http://example1.com", /\.example2\.com$/]` aceitará qualquer solicitação de "http://example1.com" ou de um subdomínio de "example2.com".
diff --git a/src/content/pages/pt-br/resources/middleware/errorhandler.mdx b/src/content/pages/pt-br/resources/middleware/errorhandler.mdx
index 8dda1e4dfe..56efb4517a 100644
--- a/src/content/pages/pt-br/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/pt-br/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Erro no manipulador de middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/index.mdx b/src/content/pages/pt-br/resources/middleware/index.mdx
new file mode 100644
index 0000000000..b06926a33c
--- /dev/null
+++ b/src/content/pages/pt-br/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Descrição: |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ Esta informação refere-se a sites de terceiros, produtos ou módulos que não são mantidos pela
+ equipe Expressjs. Listar aqui não constitui um endosso ou recomendação da equipe de projeto
+ Expressjs.
+
+
+| Middleware module | Descrição: |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/pt-br/resources/middleware/method-override.mdx b/src/content/pages/pt-br/resources/middleware/method-override.mdx
index 0d53167151..fc628d881a 100644
--- a/src/content/pages/pt-br/resources/middleware/method-override.mdx
+++ b/src/content/pages/pt-br/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Substituir verbos HTTP
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/morgan.mdx b/src/content/pages/pt-br/resources/middleware/morgan.mdx
index 1b45229f48..94a0229546 100644
--- a/src/content/pages/pt-br/resources/middleware/morgan.mdx
+++ b/src/content/pages/pt-br/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: Requisição de logger middleware HTTP para Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ Este é um módulo [Node.js](https://nodejs.org/en/) disponível através do
[registro do npm](https://www.npmjs.com/). A instalação é feita usando o comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ Se nenhum formato é dado, então o padrão é `web`.
A versão HTTP da solicitação.
-##### :method
+#####
O método HTTP do pedido.
-##### :pid
+#####
O ID do processo do Node.js lidando com a solicitação.
-##### :referrer
+#####
O cabeçalho do Referrer da solicitação. Isto usará o cabeçalho Referer de ortografia incorreta se existir, caso contrário será Referente.
@@ -239,7 +238,7 @@ de resposta são escritos, em milissegundos.
O argumento `dígitos` é um número que especifica o número de dígitos a
incluir no número, por padrão até `3`, que fornece precisão de microsegundos.
-##### :status
+#####
O código de status da resposta.
@@ -255,7 +254,7 @@ terminou de ser escrita para a conexão, em milissegundos.
O argumento `dígitos` é um número que especifica o número de dígitos a
incluir no número, por padrão até `3`, que fornece precisão de microsegundos.
-##### :url
+#####
A URL da solicitação. Isto usará `req.originalUrl` se existir, caso contrário `req.url`.
diff --git a/src/content/pages/pt-br/resources/middleware/multer.mdx b/src/content/pages/pt-br/resources/middleware/multer.mdx
index b628da3cef..4ed7b8dba3 100644
--- a/src/content/pages/pt-br/resources/middleware/multer.mdx
+++ b/src/content/pages/pt-br/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware para manipular dados multipartes/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -21,24 +22,22 @@ sobre [busboy](https://github.com/mscdex/busboy) para uma eficiência máxima.
Este README também está disponível em outros idiomas:
-| | |
-| ------------------------------------------------------------------------------------- | -------------- |
-| [العربية](https://github.com/expressjs/multer/blob/main/doc/README-ar.md) | Arábico |
-| [简体中文](https://github.com/expressjs/multer/blob/main/doc/README-zh-cn.md) | chinês |
-| [Français](https://github.com/expressjs/multer/blob/main/doc/README-fr.md) | francês |
-| [한국어](https://github.com/expressjs/multer/blob/main/doc/README-ko.md) | coreano |
-| [Português](https://github.com/expressjs/multer/blob/main/doc/README-pt-br.md) | Português (BR) |
-| [Русский язык](https://github.com/expressjs/multer/blob/main/doc/README-ru.md) | Russo |
-| [Español](https://github.com/expressjs/multer/blob/main/doc/README-es.md) | espanhol |
-| [O'zbek tili](https://github.com/expressjs/multer/blob/main/doc/README-uz.md) | Uzbek |
-| [Visualizar... t Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese |
-| [Türkçe](https://github.com/expressjs/multer/blob/main/doc/README-tr.md) | Turco |
+| | |
+| ------------------------------------------------------------------------------ | -------------- |
+| [العربية](https://github.com/expressjs/multer/blob/main/doc/README-ar.md) | Arábico |
+| [简体中文](https://github.com/expressjs/multer/blob/main/doc/README-zh-cn.md) | chinês |
+| [Français](https://github.com/expressjs/multer/blob/main/doc/README-fr.md) | francês |
+| [한국어](https://github.com/expressjs/multer/blob/main/doc/README-ko.md) | coreano |
+| [Português](https://github.com/expressjs/multer/blob/main/doc/README-pt-br.md) | Português (BR) |
+| [Русский язык](https://github.com/expressjs/multer/blob/main/doc/README-ru.md) | Russo |
+| [Español](https://github.com/expressjs/multer/blob/main/doc/README-es.md) | espanhol |
+| [O'zbek tili](https://github.com/expressjs/multer/blob/main/doc/README-uz.md) | Uzbek |
+| t Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese |
+| [Türkçe](https://github.com/expressjs/multer/blob/main/doc/README-tr.md) | Turco |
## Instalação
-```sh
-$ npm install multer
-```
+
## Utilização
@@ -284,15 +283,16 @@ Um objeto especificando os limites de tamanho das seguintes propriedades opciona
Os seguintes valores de números inteiros estão disponíveis:
-| Chave | Descrição: | Padrão |
-| ---------------- | --------------------------------------------------------------------------------------------------- | --------- |
-| `fieldNameSize` | Tamanho máximo do nome do campo | 100 bytes |
-| `tamanhoDoCampo` | Tamanho máximo do campo (em bytes) | 1MB |
-| 'campos' | Número máximo de campos não-arquivo | Infinito |
-| `tamanhoArquivo` | Para formas multipartes, o tamanho máximo do arquivo (em bytes) | Infinito |
-| `arquivos` | Para formulários multipartes, o número máximo de campos de arquivo | Infinito |
-| peças\` | Para formulários multipartes, o número máximo de peças (campos + arquivos) | Infinito |
-| `headerPairs` | Para formas de múltiplas partes, o número máximo de pares chave de cabeçalho=>valores para analisar | 2000 |
+| Chave | Descrição: | Padrão |
+| ------------------- | --------------------------------------------------------------------------------------------------- | --------- |
+| `fieldNameSize` | Tamanho máximo do nome do campo | 100 bytes |
+| `tamanhoDoCampo` | Tamanho máximo do campo (em bytes) | 1MB |
+| 'campos' | Número máximo de campos não-arquivo | Infinito |
+| `tamanhoArquivo` | Para formas multipartes, o tamanho máximo do arquivo (em bytes) | Infinito |
+| `arquivos` | Para formulários multipartes, o número máximo de campos de arquivo | Infinito |
+| peças\` | Para formulários multipartes, o número máximo de peças (campos + arquivos) | Infinito |
+| `headerPairs` | Para formas de múltiplas partes, o número máximo de pares chave de cabeçalho=>valores para analisar | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinito |
Especificar os limites pode ajudar a proteger seu site contra ataques de negação de serviço (DoS).
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Manipulação de erros
Quando encontrar um erro, Multer irá delegar o erro ao Express. Você pode
diff --git a/src/content/pages/pt-br/resources/middleware/response-time.mdx b/src/content/pages/pt-br/resources/middleware/response-time.mdx
index 270515e4d5..29b3d4a2b0 100644
--- a/src/content/pages/pt-br/resources/middleware/response-time.mdx
+++ b/src/content/pages/pt-br/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Tempo de resposta para servidores Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/serve-favicon.mdx b/src/content/pages/pt-br/resources/middleware/serve-favicon.mdx
index 4e28a2e6de..4319022171 100644
--- a/src/content/pages/pt-br/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/pt-br/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon servindo middleware com cache
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/serve-index.mdx b/src/content/pages/pt-br/resources/middleware/serve-index.mdx
index a89c71a908..e2de995bbf 100644
--- a/src/content/pages/pt-br/resources/middleware/serve-index.mdx
+++ b/src/content/pages/pt-br/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Listagens de diretórios do Serve
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/serve-static.mdx b/src/content/pages/pt-br/resources/middleware/serve-static.mdx
index 468dc858ae..334243a92d 100644
--- a/src/content/pages/pt-br/resources/middleware/serve-static.mdx
+++ b/src/content/pages/pt-br/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Servir arquivos estáticos
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/resources/middleware/session.mdx b/src/content/pages/pt-br/resources/middleware/session.mdx
index ecc473535e..587fb315e6 100644
--- a/src/content/pages/pt-br/resources/middleware/session.mdx
+++ b/src/content/pages/pt-br/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Sessão simples de middleware para Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Instalação
@@ -18,9 +19,7 @@ Este é um módulo [Node.js](https://nodejs.org/en/) disponível através do
[registro do npm](https://www.npmjs.com/). A instalação é feita usando o comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -146,7 +145,8 @@ Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribut
Mais informações sobre os diferentes níveis de prioridade podem ser encontradas em
[a especificação][rfc-west-cookie-priority-00-4.1].
-**Nota** Esse é um atributo que ainda não foi totalmente padronizado, e pode mudar no futuro.
+**Nota** Esse é um atributo que ainda não foi totalmente padronizado, e pode mudar em
+futuro.
Isso também significa que muitos clientes podem ignorar esse atributo até que eles o entendam
##### cookie.sameSite
@@ -164,8 +164,7 @@ Por padrão, isso é 'falso'.
Mais informações sobre os diferentes níveis de execução podem ser encontradas em
[a especificação][rfc-6265bis-03-4.1.2.7].
-**Nota** Esse é um atributo que ainda não foi totalmente padronizado, e pode mudar em
-futuro. Isso também significa que muitos clientes podem ignorar esse atributo até que eles o entendam
+**Nota** Esse é um atributo que ainda não foi totalmente padronizado, e pode mudar no futuro. Isso também significa que muitos clientes podem ignorar esse atributo até que eles o entendam
**Nota** Há um [rascunho da especificação](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
que requer que o atributo `Secure` seja definido como `true` quando o atributo `SameSite` tiver sido
diff --git a/src/content/pages/pt-br/resources/middleware/timeout.mdx b/src/content/pages/pt-br/resources/middleware/timeout.mdx
index 1d6350666c..d5fe1c1609 100644
--- a/src/content/pages/pt-br/resources/middleware/timeout.mdx
+++ b/src/content/pages/pt-br/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Solicitar tempo limite de middleware para conectar/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Tempo limite para uma solicitação no framework de aplicação Connect/Express.
@@ -20,9 +21,7 @@ Este é um módulo [Node.js](https://nodejs.org/en/) disponível através do
[registro do npm](https://www.npmjs.com/). A instalação é feita usando o comando
[`npm install`](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/pt-br/resources/middleware/vhost.mdx b/src/content/pages/pt-br/resources/middleware/vhost.mdx
index ae599a2aa1..05cb9f00b8 100644
--- a/src/content/pages/pt-br/resources/middleware/vhost.mdx
+++ b/src/content/pages/pt-br/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Hospedagem de domínio virtual
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/pt-br/support.md b/src/content/pages/pt-br/support.md
index 2634de3fe8..ee00a7325e 100644
--- a/src/content/pages/pt-br/support.md
+++ b/src/content/pages/pt-br/support.md
@@ -7,14 +7,14 @@ Somente a versão mais recente de qualquer linha de lançamento principal é sup
Versões que são EOL (fim de vida) _pode_ receber atualizações de vulnerabilidades de segurança críticas, mas a equipe Express não oferece garantia e não planeja endereçar ou liberar correções para quaisquer problemas encontrados.
-| Versão maior | Versão mínima do Node.js | Início Suporte | Término Suporte |
-| ------------------- | ------------------------ | ---------------- | ---------------- |
-| [**v5.x**](/5x/api) | 18 | Setembro de 2024 | **em andamento** |
-| [**v4.x**](/4x/api) | 0.10.0 | Abril de 2014 | **em andamento** |
-| [**v3.x**](/3x/api) | 0.8.0 | Outubro de 2012 | Julho de 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | Março de 2011 | Julho de 2012 |
-| **v1.x** | 0.2.0 | Dezembro de 2010 | Março de 2011 |
-| **v0.14.x** | 0.1.98 | Dezembro de 2010 | Dezembro de 2010 |
+| Versão maior | Versão mínima do Node.js | Início Suporte | Término Suporte |
+| -------------------------------------------------------------- | ------------------------ | ---------------- | ---------------- |
+| [**v5.x**](/5x/api) | 18 | Setembro de 2024 | **em andamento** |
+| [**v4.x**](/4x/api) | 0.10.0 | Abril de 2014 | **em andamento** |
+| [**v3.x**](/3x/api) | 0.8.0 | Outubro de 2012 | Julho de 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | Março de 2011 | Julho de 2012 |
+| **v1.x** | 0.2.0 | Dezembro de 2010 | Março de 2011 |
+| **v0.14.x** | 0.1.98 | Dezembro de 2010 | Dezembro de 2010 |
## Opções de Suporte Comercial
diff --git a/src/content/pages/zh-cn/advanced/best-practice-performance.md b/src/content/pages/zh-cn/advanced/best-practice-performance.md
index 206df197d2..42221810cd 100644
--- a/src/content/pages/zh-cn/advanced/best-practice-performance.md
+++ b/src/content/pages/zh-cn/advanced/best-practice-performance.md
@@ -1,18 +1,18 @@
---
-title: 'Production best practices: performance and reliability'
-description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance.
+title: '生产环境最佳实践:性能与可靠性'
+description: 探寻生产环境下Express应用在性能与可靠性方面的最佳实践,涵盖实现最优性能所需的代码优化与环境配置。
---
-This article discusses performance and reliability best practices for Express applications deployed to production.
+本文介绍部署至生产环境的Express应用在性能和可靠性方面的最佳实践。
-This topic clearly falls into the "devops" world, spanning both traditional development and operations. Accordingly, the information is divided into two parts:
+该主题明显属于“开发运维(DevOps)”范畴,兼顾传统开发与运维两大领域。 因此,相关内容分为两部分:
-- Things to do in your code (the dev part):
+- 代码层面需要执行的操作(开发部分):
- [Use gzip compression](#use-gzip-compression)
- [Don't use synchronous functions](#dont-use-synchronous-functions)
- [Do logging correctly](#do-logging-correctly)
- [Handle exceptions properly](#handle-exceptions-properly)
-- Things to do in your environment / setup (the ops part):
+- 环境/部署配置层面需要完成的事项(运维部分):
- [Set NODE_ENV to "production"](#set-node_env-to-production)
- [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
- [Run your app in a cluster](#run-your-app-in-a-cluster)
@@ -20,20 +20,20 @@ This topic clearly falls into the "devops" world, spanning both traditional deve
- [Use a load balancer](#use-a-load-balancer)
- [Use a reverse proxy](#use-a-reverse-proxy)
-## Things to do in your code
+## 代码层面的优化事项
-Here are some things you can do in your code to improve your application's performance:
+你可以在代码中执行以下操作来提升应用性能:
- [Use gzip compression](#use-gzip-compression)
- [Don't use synchronous functions](#dont-use-synchronous-functions)
- [Do logging correctly](#do-logging-correctly)
- [Handle exceptions properly](#handle-exceptions-properly)
-### Use gzip compression
+### 使用gzip压缩
-Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:
+Gzip压缩可大幅减小响应体大小,从而提升Web应用的运行速度。 在Express应用中使用 [compression](https://www.npmjs.com/package/compression) 中间件实现gzip压缩。 举个例子:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,49 +41,58 @@ const app = express();
app.use(compression());
```
-For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
+对于生产环境中的高流量网站,实施压缩的最佳方式是在反向代理层实现(参见[使用反向代理](#use-a-reverse-proxy))。 这种情况下,你无需使用压缩中间件。 For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
-### Don't use synchronous functions
+### 不要使用同步函数
-Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.
+同步函数和方法会阻塞执行进程,直至其执行完毕并返回结果。 单次调用同步函数可能仅需几微秒或几毫秒即可返回,但在高流量网站中,这些调用会累积起来,降低应用性能。 在生产环境中应避免使用同步函数。
-Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.
+尽管Node.js及许多模块都提供了函数的同步和异步版本,但在生产环境中务必使用异步版本。 唯一可以合理使用同步函数的场景是应用初始启动阶段。
-You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
+你可以使用 `--trace-sync-io` 命令行标志,在应用每次调用同步API时输出警告信息与堆栈跟踪。 当然,你不应该在生产环境中使用该标志,而应在代码准备部署到生产环境前使用它来排查问题。 See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information.
-### Do logging correctly
+### 正确进行日志记录
-In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
+通常,应用程序记录日志有两个目的:调试,以及记录应用运行活动(除此之外的所有场景基本都归为此类)。 在开发过程中,使用 `console.log()` 或 `console.error()` 将日志信息打印到终端是常见做法。 But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.
-#### For debugging
+#### 用于调试
-If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you?
+如果你的日志记录目的是调试,那么请使用专门的调试模块(例如 [debug](https://www.npmjs.com/package/debug)),而非使用 `console.log()`。 该模块允许你使用 DEBUG 环境变量来控制将哪些调试信息发送到 `console.error()`(如果存在的话)。 若要保持应用程序完全异步,你仍然需要将 `console.error()` 的输出通过管道传输到另一个程序。 但话说回来,你并不会真的在生产环境中进行调试,对吧?
-#### For app activity
+#### 用于应用运行活动记录
-If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available.
+如果你的目的是记录应用运行活动(例如追踪流量或API调用),请不要使用 `console.log()`,而是使用如 [Pino](https://www.npmjs.com/package/pino) 这样的日志库,它是目前速度最快、效率最高的选择。
-### Handle exceptions properly
+### 正确处理异常
-Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.
+Node 应用在遇到未捕获异常时会崩溃。 不处理异常并采取相应措施会导致你的 Express 应用崩溃并下线。 如果你遵循下文 [确保应用自动重启](#ensure-your-app-automatically-restarts) 中的建议,那么你的应用将能从崩溃中恢复。 幸运的是,Express 应用的启动耗时通常很短。 尽管如此,你首先需要避免应用崩溃,而要做到这一点,就必须正确处理异常。
-To ensure you handle all exceptions, use the following techniques:
+为确保处理所有异常,请使用以下方法:
- [Use try-catch](#use-try-catch)
- [Use promises](#use-promises)
-Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.
+在深入探讨这些主题之前,你应该对 Node/Express 错误处理有基本的了解:使用错误优先回调函数,以及在中间件中传递错误。 Node 使用**错误优先回调**约定从异步函数中返回错误,回调函数的第一个参数是错误对象,后续参数为结果数据。 若不存在错误,请将 `null` 作为第一个参数传递。 回调函数必须相应地遵循错误优先回调约定,才能有效处理错误。 而在 Express 中,最佳实践是使用 `next()` 函数沿着中间件链传递错误。
-For more on the fundamentals of error handling, see:
+如需了解错误处理基础的更多内容,请参阅:
-- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
-#### Use try-catch
+#### 使用 try-catch
-Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.
+`try-catch` 是一种 JavaScript 语言结构,可用于捕获同步代码中的异常。 例如,可使用 `try-catch` 处理 JSON 解析错误,如下所示。
-Here is an example of using try-catch to handle a potential process-crashing exception.
-This middleware function accepts a query field parameter named "params" that is a JSON object.
+以下是一个使用 `try-catch` 处理可能导致进程崩溃的异常的示例。
+该中间件函数接收一个名为 `params` 的查询字段参数,该参数是一个 JSON 对象。
```js
app.get('/search', (req, res) => {
@@ -100,11 +109,11 @@ app.get('/search', (req, res) => {
});
```
-However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions.
+但是,`try-catch` 仅适用于同步代码。 由于 Node 平台主要是异步的(尤其是在生产环境中),`try-catch` 无法捕获大量异常。
-#### Use promises
+#### 使用 Promise
-When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)`
+当在 `async` 函数中抛出错误,或在 `async` 函数内等待(await)一个已被拒绝的 Promise 时,这些错误会被传递给错误处理程序,效果等同于调用 `next(err)`。
```js
app.get('/', async (req, res, next) => {
@@ -118,7 +127,7 @@ app.use((err, req, res, next) => {
});
```
-Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example:
+此外,你可以将异步函数用于中间件,若 Promise 失败,路由器会自动处理错误,例如:
```js
app.use(async (req, res, next) => {
@@ -128,19 +137,19 @@ app.use(async (req, res, next) => {
});
```
-Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware.
+最佳实践是尽可能在错误发生的就近位置处理错误。 因此,虽然这类错误现在可由路由器处理,但最佳做法是在中间件中捕获并处理错误,而不依赖独立的错误处理中间件。
-#### What not to do
+#### 不要执行的操作
-One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.
+你**不应**执行的操作之一是监听 `uncaughtException` 事件,该事件会在异常一直冒泡回到事件循环时触发。 为 `uncaughtException` 添加事件监听器会改变进程遇到异常时的默认行为;即便发生异常,进程仍会继续运行。 这听起来似乎是防止应用崩溃的好方法,但在发生未捕获异常后继续运行应用是一种危险的做法,**不推荐使用**,因为此时进程的状态会变得不可靠且不可预测。
-Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.
+Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). 因此,监听 `uncaughtException` 是一种不可取的做法。 这也是我们推荐使用多进程和进程管理工具的原因:崩溃后重启通常是从错误中恢复的最可靠方式。
-We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module.
+We also don't recommend using [domains](https://nodejs.org/api/domain.html). 该模块通常无法解决问题,且已被废弃。
-## Things to do in your environment / setup
+## 环境/安装设置注意事项
-Here are some things you can do in your system environment to improve your app's performance:
+你可以在系统环境中进行以下操作来提升应用性能:
- [Set NODE_ENV to "production"](#set-node_env-to-production)
- [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts)
@@ -149,66 +158,66 @@ Here are some things you can do in your system environment to improve your app's
- [Use a load balancer](#use-a-load-balancer)
- [Use a reverse proxy](#use-a-reverse-proxy)
-### Set NODE_ENV to "production"
+### 将 `NODE_ENV` 设置为 `"production"`
-The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`.
+`NODE_ENV` 环境变量用于指定应用的运行环境(通常为开发环境或生产环境)。 提升性能最简单的操作之一就是将 `NODE_ENV` 设为 `production`。
-Setting NODE_ENV to "production" makes Express:
+将 `NODE_ENV` 设置为 `"production"` 会使 Express:
-- Cache view templates.
-- Cache CSS files generated from CSS extensions.
-- Generate less verbose error messages.
+- 缓存视图模板。
+- 缓存由 CSS 扩展生成的 CSS 文件。
+- 生成更简洁的错误提示信息。
-[Tests indicate](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
-If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
+若需要编写针对特定环境的代码,可通过 `process.env.NODE_ENV` 检查 `NODE_ENV` 的值。 请注意,检查任何环境变量的值都会产生性能损耗,因此应谨慎使用。
-In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here.
+在开发环境中,你通常在交互式 shell 中设置环境变量,例如使用 `export` 命令或 `.bash_profile` 文件。 但通常情况下,你不应该在生产服务器上这样做;相反,应使用操作系统的初始化系统(systemd)。 下一节将详细介绍如何使用初始化系统,但由于设置 `NODE_ENV` 对性能至关重要(且操作简便),因此在此单独强调。
-With systemd, use the `Environment` directive in your unit file. For example:
+使用 systemd 时,在单元文件中使用 `Environment` 指令。 举个例子:
```sh
Environment=NODE_ENV=production
```
-For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/).
+如需了解更多信息,参阅[在 systemd 单元中使用环境变量](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/)。
-### Ensure your app automatically restarts
+### 确保应用自动重启
-In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:
+在生产环境中,你绝不希望应用程序出现离线状态。 这意味着你需要确保**无论应用崩溃还是服务器本身崩溃,应用都能自动重启**。 尽管你希望这两种情况都不会发生,但在实际场景中,你必须通过以下方式应对这两种情况:
-- Using a process manager to restart the app (and Node) when it crashes.
-- Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.
+- 使用进程管理器在应用(及 Node)崩溃时将其重启。
+- 借助操作系统自带的初始化系统,在操作系统异常后重启进程管理器。 你也可以不使用进程管理器,直接使用初始化系统。
-Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.
+Node 应用在遇到未捕获异常时会崩溃。 首要任务是保证应用经过充分测试、妥善处理所有异常(详情参见[合理处理异常](#handle-exceptions-properly))。 但作为故障安全保障,需部署一套机制,确保应用一旦崩溃便能**自动重启**。
-#### Use a process manager
+#### 使用进程管理器
-In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.
+在开发环境中,你通常只需通过命令行(例如执行 `node server.js`)来启动应用。 但在生产环境中采用这种启动方式极易引发故障。 倘若应用崩溃,服务就会中断,需要手动重启才能恢复。 如需应用程序意外崩溃后自动重启,请使用进程管理器。 进程管理器是应用的“容器”,可简化部署流程、保障高可用,并支持在运行阶段管理应用。
-In addition to restarting your app when it crashes, a process manager can enable you to:
+除了在应用崩溃时重启应用外,进程管理器还可实现以下功能:
-- Gain insights into runtime performance and resource consumption.
-- Modify settings dynamically to improve performance.
-- Control clustering (pm2).
+- 查看运行时性能与资源占用情况。
+- 动态修改配置以优化性能。
+- 控制集群(pm2)。
-Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management.
+以往,使用 [PM2](https://github.com/Unitech/pm2) 这类 Node.js 进程管理器十分普遍。 如需使用,请查阅其官方文档。 不过我们建议采用系统初始化程序进行进程管理。
-#### Use an init system
+#### ### 使用系统初始化服务
-The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd).
+保障可靠性的下一步是确保服务器重启时应用也能自动重启。 服务器仍可能因各类故障宕机。 如需在服务器崩溃后重启应用,请使用操作系统内置的初始化系统。 如今主流的初始化系统为 [systemd](https://wiki.debian.org/systemd)。
-There are two ways to use init systems with your Express app:
+在 Express 应用中使用初始化系统有两种方式:
-- Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.
-- Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager.
+- 在进程管理器中运行应用,并通过初始化系统将该进程管理器安装为系统服务。 应用崩溃时进程管理器会重启应用,操作系统重启时初始化系统会重启进程管理器。 该方案为推荐方案。
+- 直接通过初始化系统运行你的应用(以及 Node)。 该方式相对简便,但无法获得使用进程管理器带来的额外优势。
##### Systemd
-Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.
+systemd 是一款 Linux 系统与服务管理器。 多数主流 Linux 发行版已将 systemd 设为默认初始化系统。
-A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app:
+systemd 服务配置文件被称为**单元文件**,文件名以 `.service` 结尾。 以下是一个直接管理 Node 应用的单元文件示例。 Replace the values enclosed in `` for your system and app:
```sh
[Unit]
@@ -242,27 +251,27 @@ WantedBy=multi-user.target
For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).
-### Run your app in a cluster
+### 以集群模式运行应用
-In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.
+在多核系统中,通过启动进程集群可以将 Node 应用的性能提升数倍。 集群会运行应用的多个实例,理想情况下每个 CPU 核心运行一个实例,从而在各实例之间分配负载与任务。

-IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](http://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
+重要提示:由于应用实例以独立进程运行,它们不共享相同的内存空间。 也就是说,对象仅作用于应用的每个独立实例。 因此,你无法在应用代码中维护状态。 不过你可以使用 [Redis](http://redis.io/) 这类内存型数据存储来存储会话相关数据与状态。 该注意事项基本适用于所有形式的水平扩展,无论是多进程集群还是多物理服务器部署。
-In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
+在集群化应用中,工作进程可单独崩溃而不会影响其余进程。 除性能优势外,故障隔离是采用应用进程集群部署的另一原因。 每当工作进程崩溃时,务必记录该事件,并使用 cluster.fork() 生成新进程。
#### Using Node's cluster module
-Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers.
+Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). 该模块可让主进程创建多个工作进程,并将接入的连接分发至各个工作进程。
-#### Using PM2
+#### 使用 PM2
-If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).
+如果使用 PM2 部署应用,**无需**修改应用代码即可使用集群功能。 你应当首先确保[应用为无状态应用](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps),即不在进程内存储本地数据(例如会话、WebSocket 连接等数据)。
-When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.
+使用 PM2 运行应用程序时,你可以启用**集群模式**,以指定数量的实例(例如与机器上可用 CPU 数量匹配)集群化运行应用。 你可以使用 `pm2` 命令行工具,**无需停止应用**,手动调整集群中的进程数量。
-To enable cluster mode, start your application like so:
+要启用集群模式,请按如下方式启动应用程序:
```bash
@@ -271,9 +280,9 @@ $ pm2 start npm --name my-app -i 4 -- start
$ pm2 start npm --name my-app -i max -- start
```
-This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.
+这也可以在 PM2 进程文件(`ecosystem.config.js` 或类似文件)中进行配置,将 `exec_mode` 设置为 `cluster`,并将 `instances` 设置为要启动的工作进程数量。
-Once running, the application can be scaled like so:
+应用启动后,可按如下方式进行扩容:
```bash
@@ -282,24 +291,24 @@ $ pm2 scale my-app +3
$ pm2 scale my-app 2
```
-For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.
+如需了解更多关于使用 PM2 实现集群部署的相关信息,请参阅 PM2 文档中的[集群模式](https://pm2.keymetrics.io/docs/usage/cluster-mode/)。
-### Cache request results
+### 缓存请求结果
-Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
+优化生产环境性能的另一方案是缓存请求返回结果,避免应用重复处理相同请求。
-Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/nginx-caching/)) to greatly improve the speed and performance of your app.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
-### Use a load balancer
+### 使用负载均衡器
-No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance.
+无论应用优化程度多高,单个实例所能承载的负载与流量都存在上限。 应用扩容的一种方案:部署多实例,并通过负载均衡分发流量。 配置负载均衡能够提升应用性能与访问速度,同时让应用实现单实例无法达成的扩容能力。
-A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
+负载均衡器通常是一种反向代理,用于调度多应用实例与多服务器之间的往来流量。 You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).
-With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).
+使用负载均衡时,你可能需要确保与特定会话 ID 关联的请求能连接到创建该会话的进程。 这被称为**会话亲和性**(_session affinity_),即**粘性会话**(_sticky sessions_),可通过上述建议解决(根据你的应用场景,可采用 Redis 等数据存储来存放会话数据)。 相关说明请参阅[多节点部署](https://socket.io/docs/v4/using-multiple-nodes/)。
-### Use a reverse proxy
+### # 使用反向代理
-A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
+反向代理部署在 Web 应用前端,除了将请求转发至应用外,还会对请求执行各类辅助操作。 它可处理错误页面、压缩、缓存、静态资源托管以及负载均衡等多项工作。
-Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://www.nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
+将无需感知应用状态的任务交由反向代理处理,可释放 Express 专注处理各类应用专属任务。 For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/zh-cn/advanced/best-practice-security.mdx b/src/content/pages/zh-cn/advanced/best-practice-security.mdx
index cb960fcbbf..8fa5c472a9 100644
--- a/src/content/pages/zh-cn/advanced/best-practice-security.mdx
+++ b/src/content/pages/zh-cn/advanced/best-practice-security.mdx
@@ -1,13 +1,14 @@
---
-title: 'Production Best Practices: Security'
-description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities.
+title: 生产环境最佳实践:安全防护
+description: 了解Express应用部署至生产环境需遵循的关键安全最佳实践,包含启用TLS、入参校验、安全Cookie配置及漏洞防护相关内容。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-The term _"production"_ refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the _"development"_ stage, you're still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as _production_ and _development_ environments, respectively.
+术语\*\*「生产环境」**指软件生命周期中应用或API面向终端用户、调用方正式对外开放的阶段。 与之相对,**「开发环境」**阶段中,开发者仍在编写与测试代码,应用暂不对外开放访问。 对应的系统环境分别称作**生产环境**与**开发环境\*\*。
-Development and production environments are usually set up differently and have vastly different requirements. What's fine in development may not be acceptable in production. For example, in a development environment you may want verbose logging of errors for debugging, while the same behavior can become a security concern in a production environment. And in development, you don't need to worry about scalability, reliability, and performance, while those concerns become critical in production.
+开发环境与生产环境通常配置不同,需求差异悬殊。 在开发环境中可行的配置,放到生产环境未必适用。 例如:开发环境下可开启详细错误日志用于调试,但相同配置在生产环境中会带来安全隐患。 开发阶段无需考量扩展性、可靠性与性能,而在生产环境中这些指标至关重要。
@@ -16,51 +17,48 @@ Policies and Procedures.
-Security best practices for Express applications in production include:
+Express 应用生产环境安全最佳实践包含:
-- [Production Best Practices: Security](#production-best-practices-security)
- - [Overview](#overview)
- - [Don't use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Use TLS](#use-tls)
- - [Do not trust user input](#do-not-trust-user-input)
- - [Prevent open redirects](#prevent-open-redirects)
- - [Use Helmet](#use-helmet)
- - [Reduce fingerprinting](#reduce-fingerprinting)
- - [Use cookies securely](#use-cookies-securely)
- - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
- - [Set cookie security options](#set-cookie-security-options)
- - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
- - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
- - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
- - [Additional considerations](#additional-considerations)
+- [请勿使用已弃用或存在漏洞的 Express 版本](#请勿使用已弃用或存在漏洞的-express-版本)
+- [启用TLS](#use-tls)
+- [切勿信任用户输入](#切勿信任用户输入)
+ - [防止开放重定向](#防止开放重定向)
+- [使用 Helmet](#use-helmet)
+- [减少指纹信息泄露](#reduce-fingerprinting)
+- [安全使用 Cookie](#use-cookies-securely)
+ - [不使用默认会话 cookie 名称](#dont-use-the-default-session-cookie-name)
+ - [设置 cookie 安全选项](#set-cookie-security-options)
+- [防止使用暴力攻击授权](#prevent-brute-force-attacks-against-authorization)
+- [确保您的依赖是安全的](#ensure-your-dependencies-are-secure)
+ - [避免其他已知漏洞](#avoid-other-known-vulnerabilities)
+- [其他考虑](#additional-considerations)
-## Don't use deprecated or vulnerable versions of Express
+## 请勿使用已弃用或存在漏洞的 Express 版本
-Express 2.x and 3.x are no longer maintained. Security and performance issues in these versions won't be fixed. Do not use them! If you haven't moved to version 4, follow the [migration guide](/guide/migrating-4) or consider [Commercial Support Options](/support#commercial-support-options).
+Express 2.x 与 3.x 版本已不再维护。 这些版本中的安全与性能问题将不再进行修复。 不要使用它们! If you haven't moved to version 4, follow the [migration guide](/guide/migrating-4) or consider [Commercial Support Options](/support#commercial-support-options).
-Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](/advanced/security-updates). If you are, update to one of the stable releases, preferably the latest.
+Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](/advanced/security-updates). 如若正在使用,请升级至任一稳定版本,优先选择最新版。
-## Use TLS
+## 使用 TLS
-If your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem "hidden" in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
+如果您的应用处理或传输敏感数据,请使用 [传输图层安全](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) 来保护连接和数据。 该技术会在客户端向服务器发送数据前对数据进行加密,从而防范部分常见且易实施的攻击。 尽管 AJAX 和 POST 请求在浏览器中不会直观展现、看似处于 “隐藏” 状态,但它们的网络流量容易遭到[抓包分析](https://en.wikipedia.org/wiki/Packet_analyzer)与[中间人攻击](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+你或许熟悉安全套接字层(SSL)加密。 In general, we recommend Nginx to handle TLS. 换言之,若此前使用SSL,建议升级至TLS。 In other words, if you were using SSL before, consider upgrading to TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
-Also, a handy tool to get a free TLS certificate is [Let's Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
+另外,获取免费TLS证书的实用工具是[Let's Encrypt](https://letsencrypt.org/about/),它是由[互联网安全研究集团(ISRG)](https://www.abetterinternet.org/)提供的免费、自动化的开放证书颁发机构(CA)。
-## Do not trust user input
+## 切勿信任用户输入
-For web applications, one of the most critical security requirements is proper user input validation and handling. This comes in many forms and we will not cover all of them here.
-Ultimately, the responsibility for validating and correctly handling the types of user input your application accepts is yours.
+对 Web 应用而言,最关键的安全要求之一是对用户输入进行合理的验证与处理。 这类风险形式多样,本文不逐一列举。
+最终,你需要全权负责验证并正确处理应用接收的各类用户输入。
-### Prevent open redirects
+### 防止开放重定向
-An example of potentially dangerous user input is an _open redirect_, where an application accepts a URL as user input (often in the URL query, for example `?url=https://example.com`) and uses `res.redirect` to set the `location` header and
-return a 3xx status.
+开放重定向是一类存在潜在风险的用户输入:应用接收 URL 格式的用户输入(通常位于 URL 查询参数中,例如 `?url=https://example.com`),并通过 `res.redirect` 设置 `location` 响应头,返回 3xx 状态码实现重定向。
-An application must validate that it supports redirecting to the incoming URL to avoid sending users to malicious links such as phishing websites, among other risks.
+应用必须验证自身支持重定向至传入的 URL,避免将用户导向钓鱼网站等恶意链接,防范相关风险。
-Here is an example of checking URLs before using `res.redirect` or `res.location`:
+以下是在使用 `res.redirect` 或 `res.location` 之前检查 URL 的示例:
```js
app.use((req, res) => {
@@ -77,35 +75,33 @@ app.use((req, res) => {
## Use Helmet
-[Helmet][helmet] can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately.
+[Helmet][helmet] 可通过合理设置 HTTP 请求头,帮助你的应用抵御部分常见的 Web 安全漏洞。
-Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default:
+Helmet 是用于设置安全相关 HTTP 响应头的中间件函数。 Helmet 默认设置如下请求头:
-- `Content-Security-Policy`: A powerful allow-list of what can happen on your page which mitigates many attacks
-- `Cross-Origin-Opener-Policy`: Helps process-isolate your page
-- `Cross-Origin-Resource-Policy`: Blocks others from loading your resources cross-origin
-- `Origin-Agent-Cluster`: Changes process isolation to be origin-based
+- `Content-Security-Policy`:一套管控页面资源访问的强力白名单,可防范多种攻击
+- `Cross-Origin-Opener-Policy`:协助对页面进行进程隔离
+- `Cross-Origin-Resource-Policy`:阻止其他站点跨域加载你的资源
+- `Origin-Agent-Cluster`:基于源修改进程隔离策略
- `Referrer-Policy`: Controls the [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header
-- `Strict-Transport-Security`: Tells browsers to prefer HTTPS
+- `Strict-Transport-Security`:告知浏览器优先使用 HTTPS
- `X-Content-Type-Options`: Avoids [MIME sniffing](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#mime_sniffing)
-- `X-DNS-Prefetch-Control`: Controls DNS prefetching
-- `X-Download-Options`: Forces downloads to be saved (Internet Explorer only)
-- `X-Frame-Options`: Legacy header that mitigates [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) attacks
-- `X-Permitted-Cross-Domain-Policies`: Controls cross-domain behavior for Adobe products, like Acrobat
-- `X-Powered-By`: Info about the web server. Removed because it could be used in simple attacks
-- `X-XSS-Protection`: Legacy header that tries to mitigate [XSS attacks](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting), but makes things worse, so Helmet disables it
+- `X-DNS-Prefetch-Control`:控制 DNS 预取
+- `X-Download-Options`:强制文件以下载形式保存(仅适用于 IE 浏览器)
+- `X-Frameworks`: 减少 [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) 攻击的遗留标题
+- `X-Permitted-Cross-Domain-Policies`:控制Adobe系列产品(如Acrobat)的跨域行为
+- `X-Powered-By`:有关Web服务器的信息。 因易被用于简易攻击而移除
+- `X-XSS-Protection`:用于缓解[XSS攻击](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)的旧式请求头,但会带来安全隐患,因此Helmet将其禁用
-Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet].
+每个请求头均可配置或禁用。 如需了解更多详情,请访问[其官方文档网站][helmet]。
-Install Helmet like any other module:
+像安装其他模块一样安装 Helmet:
-```bash
-$ npm install helmet
-```
+
-Then to use it in your code:
+然后在代码中使用:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,16 +110,23 @@ app.use(helmet());
// ...
```
-## Reduce fingerprinting
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
+## 减少指纹识别
-It can help to provide an extra layer of security to reduce the ability of attackers to determine
-the software that a server uses, known as "fingerprinting." Though not a security issue itself,
-reducing the ability to fingerprint an application improves its overall security posture.
-Server software can be fingerprinted by quirks in how it responds to specific requests, for example in
-the HTTP response headers.
+它有助于提供额外的安全层,降低攻击者识别服务器所使用软件的能力,这种行为被称为“指纹识别”。 尽管其本身并非安全漏洞,
+但降低应用程序的指纹识别能力可提升其整体安全状况。
+服务器软件可通过其响应特定请求的特征进行指纹识别,例如通过HTTP响应头中的特征。
-By default, Express sends the `X-Powered-By` response header that you can
-disable using the `app.disable()` method:
+默认情况下,Express 会发送 `X-Powered-By` 响应头,你可以使用 `app.disable()` 方法将其禁用:
```js
app.disable('x-powered-by');
@@ -131,14 +134,11 @@ app.disable('x-powered-by');
-Disabling the `X-Powered-By header` does not prevent a sophisticated attacker from determining
-that an app is running Express. It may discourage a casual exploit, but there are other ways to
-determine an app is running Express.
+禁用 `X-Powered-By` 响应头并不能阻止老练的攻击者识别出应用正在运行 Express。 这或许能防范随意的漏洞利用,但仍有其他方法可以识别应用正在运行 Express。
-Express also sends its own formatted "404 Not Found" messages and formatter error
-response messages. These can be changed by
+Express 还会发送自身格式化的“404 Not Found”信息和错误响应格式化信息。 These can be changed by
[adding your own not found handler](/starter/faq#how-do-i-handle-404-responses)
and
[writing your own error handler](/guide/error-handling#writing-error-handlers):
@@ -158,26 +158,26 @@ app.use((err, req, res, next) => {
});
```
-## Use cookies securely
+## 安全使用 cookie
-To ensure cookies don't open your app to exploits, don't use the default session cookie name and set cookie security options appropriately.
+为确保Cookie不会让你的应用程序面临攻击风险,请勿使用默认的会话Cookie名称,并合理设置Cookie安全选项。
-There are two main middleware cookie session modules:
+主要有两个会话Cookie中间件模块:
-- [express-session](https://www.npmjs.com/package/express-session) that replaces `express.session` middleware built-in to Express 3.x.
-- [cookie-session](https://www.npmjs.com/package/cookie-session) that replaces `express.cookieSession` middleware built-in to Express 3.x.
+- [express-session](https://www.npmjs.com/package/express-session):替代了 Express 3.x 内置的 `express.session` 中间件。
+- [cookie-session](https://www.npmjs.com/package/cookie-session):替代了 Express 3.x 内置的 `express.cookieSession` 中间件。
-The main difference between these two modules is how they save cookie session data. The [express-session](https://www.npmjs.com/package/express-session) middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you'll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores).
+这两个模块的主要区别在于它们存储 Cookie 会话数据的方式。 [express-session](https://www.npmjs.com/package/express-session) 中间件将会话数据存储在服务器端;它仅将会话ID保存到Cookie本身,不存储会话数据。 默认情况下,它使用内存存储,并非为生产环境设计。 In production, you'll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores).
-In contrast, [cookie-session](https://www.npmjs.com/package/cookie-session) middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don't exceed the limit, don't exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then `express-session` may be a better choice.
+相比之下,[cookie-session](https://www.npmjs.com/package/cookie-session) 中间件实现基于Cookie的存储:它将整个会话序列化后存储到Cookie中,而非仅存储会话密钥。 仅当会话数据相对较小且易于编码为基本类型值(而非对象)时,才使用它。 尽管浏览器应支持每个Cookie至少4096字节,但为确保不超出限制,每个域的Cookie大小请勿超过4093字节。 此外,请注意**Cookie数据对客户端是可见的**,因此如果有任何需要保证数据安全或隐藏的需求,那么 `express-session` 会是更合适的选择。
-### Don't use the default session cookie name
+### 不要使用默认的会话Cookie名称
-Using the default session cookie name can open your app to attacks. The security issue posed is similar to `X-Powered-By`: a potential attacker can use it to fingerprint the server and target attacks accordingly.
+使用默认会话Cookie名称会使你的应用易遭受攻击。 由此带来的安全隐患与`X-Powered-By`类似:潜在攻击者可借此识别服务器指纹,并针对性发起攻击。
-To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
+若要避免此问题,请使用通用的Cookie名称;例如使用 [express-session](https://www.npmjs.com/package/express-session) 中间件:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,19 +188,31 @@ app.use(
);
```
-### Set cookie security options
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
+### 设置 cookie 安全选项
-Set the following cookie options to enhance security:
+设置下面的 cookie 选项以增强安全性:
-- `secure` - Ensures the browser only sends the cookie over HTTPS.
-- `httpOnly` - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.
-- `domain` - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.
-- `path` - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.
+- `secure` - 确保浏览器只通过 HTTPS 发送 cookie 。
+- `httpOnly` - 确保 Cookie 仅通过 HTTP(S) 发送,不会被客户端 JavaScript 访问,有助于防范跨站脚本攻击。
+- `domain` - 表示 Cookie 的所属域名;用于将其与请求 URL 所在的服务器域名进行比对。 若匹配,则下一步检查路径属性。
+- `path` - 表示 Cookie 的路径;用于将其与请求路径进行比对。 若域名与路径均匹配,则在请求中发送该 Cookie。
- `expires` - use to set expiration date for persistent cookies.
-Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
+以下是使用 [cookie-session](https://www.npmjs.com/package/cookie-session) 中间件的示例:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,56 +233,78 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Prevent brute-force attacks against authorization
-Make sure login endpoints are protected to make private data more secure.
+确保登录接口受到保护,以提升私有数据的安全性。
-A simple and powerful technique is to block authorization attempts using two metrics:
+一种简单且有效的技巧是使用两个指标来阻止授权尝试:
-1. The number of consecutive failed attempts by the same user name and IP address.
-2. The number of failed attempts from an IP address over some long period of time. For example, block an IP address if it makes 100 failed attempts in one day.
+1. 同一用户名和IP地址连续失败的尝试次数。
+2. 某一IP地址在较长时间段内的失败尝试次数。 例如,如果一个IP地址在一天内失败尝试100次,则阻止该IP地址。
-[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) package provides tools to make this technique easy and fast. You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)
+[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) 包提供了可简便快捷实现该技巧的工具。 你可以在文档中找到[暴力破解防护示例](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)
-## Ensure your dependencies are secure
+## 确保你的依赖项安全
-Using npm to manage your application's dependencies is powerful and convenient. But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the "weakest link" in your dependencies.
+使用 npm 管理应用依赖项功能强大且便捷。 但你使用的软件包可能包含严重的安全漏洞,这些漏洞同样会影响你的应用。 应用的安全性仅取决于依赖项中**最薄弱的环节**。
-Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree.
+从 npm@6 版本开始,npm 会自动审查每一次安装请求。 此外,你可以使用 `npm audit` 分析你的依赖树。
```bash
$ npm audit
```
-If you want to stay more secure, consider [Snyk](https://snyk.io/).
+如需进一步提升安全性,可选用 [Snyk](https://snyk.io/)。
-Snyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [Github integration](https://snyk.io/docs/github) that checks your application against [Snyk's open source vulnerability database](https://snyk.io/vuln/) for any known vulnerabilities in your dependencies. Install the CLI as follows:
+Snyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [Github integration](https://snyk.io/docs/github) that checks your application against [Snyk's open source vulnerability database](https://snyk.io/vuln/) for any known vulnerabilities in your dependencies. 安装如下CLI:
```bash
$ npm install -g snyk
$ cd your-app
```
-Use this command to test your application for vulnerabilities:
+使用此命令检测你的应用是否存在漏洞:
```bash
$ snyk test
```
-### Avoid other known vulnerabilities
+### 规避其他已知安全漏洞
-Keep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. 总体而言,这些数据库是获取 Node 安全相关知识与工具的优质资源。
-Finally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
+最后,Express 应用—和所有 Web 应用一样—可能遭受各类基于网页的攻击。 Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
-## Additional considerations
+## 其他注意事项
-Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:
+以下是源自优质文档 [Node.js 安全检查清单](https://blog.risingstack.com/node-js-security-checklist/) 的补充建议。 关于这些建议的所有详细信息,请参阅该博客帖子:
-- Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.
-- Defend against SQL injection attacks by using parameterized queries or prepared statements.
+- 始终过滤并净化用户输入,防范跨站脚本(XSS)与命令注入攻击。
+- 使用参数化查询或预处理语句防范 SQL 注入攻击。
- Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.
-- Use the [nmap](https://nmap.org/) and [sslyze](https://github.com/nabla-c0d3/sslyze) tools to test the configuration of your SSL ciphers, keys, and renegotiation as well as the validity of your certificate.
+- 使用 [nmap](https://nmap.org/) 和 [sslyze](https://github.com/nabla-c0d3/sslyze) 工具测试 SSL 加密套件、密钥、重协商配置以及证书有效性。
- Use [safe-regex](https://www.npmjs.com/package/safe-regex) to ensure your regular expressions are not susceptible to [regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) attacks.
[helmet]: https://helmetjs.github.io/
diff --git a/src/content/pages/zh-cn/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/zh-cn/advanced/healthcheck-graceful-shutdown.md
index c060e58605..d7fd3206bd 100644
--- a/src/content/pages/zh-cn/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/zh-cn/advanced/healthcheck-graceful-shutdown.md
@@ -1,13 +1,13 @@
---
-title: Health Checks and Graceful Shutdown
-description: Learn how to implement health checks and graceful shutdown in Express apps to enhance reliability, manage deployments, and integrate with load balancers like Kubernetes.
+title: 健康检查与优雅关闭
+description: 学习如何在 Express 应用中实现健康检查和优雅关闭,以提升可靠性、管理部署并与 Kubernetes 等负载均衡器集成。
---
-## Graceful shutdown
+## 优雅关闭
-When you deploy a new version of your application, you must replace the previous version. The process manager you're using will first send a SIGTERM signal to the application to notify it that it will be killed. Once the application gets this signal, it should stop accepting new requests, finish all the ongoing requests, clean up the resources it used, including database connections and file locks then exit.
+部署应用新版本时,必须替换旧版本。 你使用的进程管理器会首先向应用发送 SIGTERM 信号,通知应用即将被终止。 应用收到该信号后,应停止接收新请求、完成所有正在处理的请求,释放已使用的资源(包括数据库连接和文件锁),然后退出。
-### Example
+### 示例
```js
const server = app.listen(port);
@@ -20,9 +20,9 @@ process.on('SIGTERM', () => {
});
```
-## Health checks
+## 健康检查
-A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+负载均衡器通过健康检查判定应用实例状态是否正常、能否接收请求。 For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
-- `liveness`, that determines when to restart a container.
-- `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers.
+- `liveness`(存活检查):用于判断何时重启容器。
+- `readiness`(就绪检查):用于判断容器何时准备就绪并开始接收流量。 Pod 未就绪时,会从服务负载均衡器中被剔除。
diff --git a/src/content/pages/zh-cn/advanced/security-updates.mdx b/src/content/pages/zh-cn/advanced/security-updates.mdx
index 16d9d7191f..9b480e5edf 100644
--- a/src/content/pages/zh-cn/advanced/security-updates.mdx
+++ b/src/content/pages/zh-cn/advanced/security-updates.mdx
@@ -1,19 +1,19 @@
---
-title: Security updates
-description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application.
+title: 安全更新
+description: 查看 Express.js 最新安全更新与补丁,包含各版本详细漏洞清单,助力维护应用安全。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-Node.js vulnerabilities directly affect Express. Therefore, keep a watch on Node.js
+Node.js 漏洞会直接影响 Express。 Therefore, keep a watch on Node.js
vulnerabilities and make sure you are using the latest
stable version of Node.js.
-The list below enumerates the Express vulnerabilities that were fixed in the specified version update.
+下方清单列举了在对应版本更新中已修复的 Express 漏洞。
@@ -25,63 +25,63 @@ Policies and Procedures.
## 4.x
- 4.21.2
- - The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-rhx6-c78j-4q9w).
+ - 依赖包 `path-to-regexp` 已完成升级,用于修复一处[安全漏洞](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-rhx6-c78j-4q9w)。
- 4.21.1
- - The dependency `cookie` has been updated to address a [vulnerability](https://github.com/jshttp/cookie/security/advisories/GHSA-pxg6-pf52-xh8x), This may affect your application if you use `res.cookie`.
+ - 依赖包 `cookie` 已升级以修复一处[漏洞](https://github.com/jshttp/cookie/security/advisories/GHSA-pxg6-pf52-xh8x),若项目使用 `res.cookie`,你的应用可能受此漏洞影响。
- 4.20.0
- Fixed XSS vulnerability in `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-qw6h-vgh9-j6wx), [CVE-2024-43796](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-43796)).
- - The dependency `serve-static` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-cm22-4g7w-348p).
- - The dependency `send` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-m6fv-jmcg-4jfg).
- - The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j).
- - The dependency `body-parser` has been updated to addres a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url enconding activated.
+ - 依赖包 `serve-static` 已升级以修复一处[安全漏洞](https://github.com/advisories/GHSA-cm22-4g7w-348p)。
+ - 依赖包 `send` 已升级以修复一处[安全漏洞](https://github.com/advisories/GHSA-m6fv-jmcg-4jfg)。
+ - 依赖包 `path-to-regexp` 已升级以修复一处[安全漏洞](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j)。
+ - 依赖包 `body-parser` 已升级以修复一处[安全漏洞](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7),若你启用了 URL 编码,你的应用可能会受此影响。
- 4.19.0, 4.19.1
- Fixed open redirect vulnerability in `res.location` and `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc), [CVE-2024-29041](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-29041)).
- 4.17.3
- - The dependency `qs` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp). This may affect your application if the following APIs are used: `req.query`, `req.body`, `req.param`.
+ - 依赖`qs`已更新以修复一处[安全漏洞](https://github.com/advisories/GHSA-hrpp-h998-j3pp)。 若使用了下述 API:`req.query`、`req.body`、`req.param`,该问题可能对你的应用造成影响。
- 4.16.0
- - The dependency `forwarded` has been updated to address a [vulnerability](https://npmjs.com/advisories/527). This may affect your application if the following APIs are used: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`.
+ - The dependency `forwarded` has been updated to address a [vulnerability](https://npmjs.com/advisories/527). 如果使用了下列API,这可能会影响您的应用程序:`req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`。
- The dependency `mime` has been updated to address a [vulnerability](https://npmjs.com/advisories/535), but this issue does not impact Express.
- - The dependency `send` has been updated to provide a protection against a [Node.js 8.5.0 vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). This only impacts running Express on the specific Node.js version 8.5.0.
+ - 依赖`send`已完成更新,用于防范[Node.js 8.5.0相关漏洞](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/)。 该问题仅会在 Node.js 8.5.0 特定版本中运行 Express 时产生影响。
- 4.15.5
- The dependency `debug` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express.
- - The dependency `fresh` has been updated to address a [vulnerability](https://npmjs.com/advisories/526). This will affect your application if the following APIs are used: `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`.
+ - The dependency `fresh` has been updated to address a [vulnerability](https://npmjs.com/advisories/526). 若你的应用使用了以下 API,则会受到影响:`express.static`、`req.fresh`、`res.json`、`res.jsonp`、`res.send`、`res.sendfile`、`res.sendFile`、`res.sendStatus`。
- 4.15.3
- - The dependency `ms` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:ms:20170412). This may affect your application if untrusted string input is passed to the `maxAge` option in the following APIs: `express.static`, `res.sendfile`, and `res.sendFile`.
+ - The dependency `ms` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:ms:20170412). 如果将不可信的字符串输入传递给以下 API 中的 `maxAge` 选项,你的应用可能会受到影响:`express.static`、`res.sendfile` 和 `res.sendFile`。
- 4.15.2
- - The dependency `qs` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:qs:20170213), but this issue does not impact Express. Updating to 4.15.2 is a good practice, but not required to address the vulnerability.
+ - The dependency `qs` has been updated to address a [vulnerability](https://snyk.io/vuln/npm:qs:20170213), but this issue does not impact Express. 更新至 4.15.2 是良好实践,但修复该漏洞并非必须执行此操作。
- 4.11.1
- - Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
+ - 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径泄露漏洞。
- 4.10.7
- Fixed open redirect vulnerability in `express.static` ([advisory](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
- 4.8.8
- Fixed directory traversal vulnerabilities in `express.static` ([advisory](http://npmjs.com/advisories/32) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)).
- 4.8.4
- - Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
+ - Node.js 0.10 在特定情况下可能会发生文件描述符(`fd`)泄漏,从而影响 `express.static` 和 `res.sendfile`。 恶意请求可能导致文件描述符(`fd`)泄漏,最终引发`EMFILE`错误并造成服务器无响应。
- 4.8.0
- - Sparse arrays that have extremely high indexes in the query string could cause the process to run out of memory and crash the server.
- - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
+ - 查询字符串中包含极高索引的稀疏数组,可能导致进程内存耗尽并使服务器崩溃。
+ - 深度嵌套的查询字符串对象会导致进程阻塞,使服务器暂时无法响应。
## 3.x
-
-**Express 3.x IS END-OF-LIFE AND NO LONGER MAINTAINED**
+
+**Express 3.x 已终止生命周期,不再提供维护支持**
-Known and unknown security and performance issues in 3.x have not been addressed since the last update (1 August, 2015). It is highly recommended to use the latest version of Express.
+3.x 版本自2015年8月1日最后一次更新后,已知及潜在的安全、性能漏洞均不再修复。 强烈建议使用最新版本的 Express。
If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/support#commercial-support-options).
- 3.19.1
- - Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile`
+ - 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径泄露漏洞。
- 3.19.0
- Fixed open redirect vulnerability in `express.static` ([advisory](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)).
- 3.16.10
- - Fixed directory traversal vulnerabilities in `express.static`.
+ - 在 `expres.static` 中固定的目录遍历脆弱性。
- 3.16.6
- - Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness.
+ - Node.js 0.10 在特定情况下可能会发生文件描述符(`fd`)泄漏,从而影响 `express.static` 和 `res.sendfile`。 恶意请求可能导致文件描述符(`fd`)泄漏,最终引发`EMFILE`错误并造成服务器无响应。
- 3.16.0
- - Sparse arrays that have extremely high indexes in query string could cause the process to run out of memory and crash the server.
- - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily.
+ - 查询字符串中包含极高索引的稀疏数组,会导致进程内存耗尽并使服务器崩溃。
+ - 深度嵌套的查询字符串对象会导致进程阻塞,使服务器暂时无法响应。
- 3.3.0
- - The 404 response of an unsupported method override attempt was susceptible to cross-site scripting attacks.
+ - 尝试使用不支持的方法重写时返回的 404 响应,曾存在跨站脚本攻击漏洞。
diff --git a/src/content/pages/zh-cn/guide/database-integration.mdx b/src/content/pages/zh-cn/guide/database-integration.mdx
index b0855e4a2a..16ca618551 100644
--- a/src/content/pages/zh-cn/guide/database-integration.mdx
+++ b/src/content/pages/zh-cn/guide/database-integration.mdx
@@ -1,11 +1,12 @@
---
-title: Database integration
-description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more.
+title: 数据库集成
+description: 了解如何将各种数据库与 Express.js 应用程序集成,包括 MongoDB、MySQL、PostgreSQL 等的配置示例。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:
+为 Express 应用添加连接数据库的功能,只需在应用中加载对应数据库的合适 Node.js 驱动程序即可。 本文简要说明如何在 Express 应用中添加并使用一些最流行的数据库系统 Node.js 模块:
- [Cassandra](#cassandra)
- [Couchbase](#couchbase)
@@ -23,8 +24,7 @@ Adding the capability to connect databases to Express apps is just a matter of l
-These database drivers are among many that are available. For other options, search on the
-[npm](https://www.npmjs.com/) site.
+这些数据库驱动只是众多可选驱动中的一部分。 如需其他方案,可前往[npm](https://www.npmjs.com/)官网检索。
@@ -32,15 +32,13 @@ These database drivers are among many that are available. For other options, sea
**Module**: [cassandra-driver](https://github.com/datastax/nodejs-driver)
-### Installation
+### 安装
-```bash
-$ npm install cassandra-driver
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +48,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
**Module**: [couchnode](https://github.com/couchbase/couchnode)
-### Installation
+### 安装
-```bash
-$ npm install couchbase
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +94,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
**Module**: [nano](https://github.com/dscape/nano)
-### Installation
+### 安装
-```bash
-$ npm install nano
-```
+
-### Example
+### 示例
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -127,15 +158,13 @@ books.list((err, body) => {
**Module**: [levelup](https://github.com/rvagg/node-levelup)
-### Installation
+### 安装
-```bash
-$ npm install level levelup leveldown
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +179,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
**Module**: [mysql](https://github.com/felixge/node-mysql/)
-### Installation
+### 安装
-```bash
-$ npm install mysql
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +225,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
-### Installation
+### 安装
-```bash
-$ npm install mongodb
-```
+
### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -212,7 +274,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -236,15 +298,13 @@ If you want an object model driver for MongoDB, look at [Mongoose](https://githu
**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)
-### Installation
+### 安装
-```bash
-$ npm install neo4j-driver
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,21 +322,38 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
**Module**: [oracledb](https://github.com/oracle/node-oracledb)
-### Installation
+### 安装
NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +383,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
-### Installation
+### 安装
-```bash
-$ npm install pg-promise
-```
+
-### Example
+### 示例
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -335,15 +441,13 @@ db.one('SELECT $1 AS value', 123)
**Module**: [redis](https://github.com/mranney/node_redis)
-### Installation
+### 安装
-```bash
-$ npm install redis
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +470,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
+```mjs title="index.mjs"
+import redis from 'redis';
+
+const client = redis.createClient();
+
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
+
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
+```
+
## SQL Server
**Module**: [tedious](https://github.com/tediousjs/tedious)
-### Installation
+### 安装
-```bash
-$ npm install tedious
-```
+
-### Example
+### 示例
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -431,15 +557,13 @@ function executeStatement() {
**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)
-### Installation
+### 安装
-```bash
-$ npm install sqlite3
-```
+
-### Example
+### 示例
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -465,15 +589,13 @@ db.close();
**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)
-### Installation
+### 安装
-```bash
-$ npm install elasticsearch
-```
+
-### Example
+### 示例
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +623,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/zh-cn/guide/migrating-4.mdx b/src/content/pages/zh-cn/guide/migrating-4.mdx
index c0e246a73c..2a68db6179 100644
--- a/src/content/pages/zh-cn/guide/migrating-4.mdx
+++ b/src/content/pages/zh-cn/guide/migrating-4.mdx
@@ -1,63 +1,43 @@
---
-title: Moving to Express 4
-description: A guide to migrating your Express.js applications from version 3 to 4, covering changes in middleware, routing, and how to update your codebase effectively.
+title: 迁移至 Express 4
+description: 一份将 Express.js 应用从 3 版迁移至 4 版的指南,涵盖中间件与路由的变更,以及高效更新代码库的方法。
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Express 4 is a breaking change from Express 3. That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies.
+Express 4 相对于 Express 3 是一个破坏性变更版本。 这意味着如果在依赖项中更新 Express 版本,现有的 Express 3 应用将**无法**正常运行。
-This article covers:
+本文包括:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
-## Changes in Express 4
+## Express 4 的变更
-There are several significant changes in Express 4:
+Express 4 中有几项重大变更:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
-See also:
+参阅:
-- [New features in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x)
-- [Migrating from 3.x to 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
+- [新功能在 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x)
+- [从 3.x 迁移到 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
-### Changes to Express core and middleware system
+### Express 核心和中间件系统的变更
-Express 4 no longer depends on Connect, and removes all built-in
-middleware from its core, except for the `express.static` function. This means that
-Express is now an independent routing and middleware web framework, and
-Express versioning and releases are not affected by middleware updates.
+Express 4 不再依赖 Connect,并从核心中移除了所有内置中间件,`express.static` 函数除外。 这意味着 Express 现在是一个独立的路由与中间件 Web 框架,其版本和发布不再受中间件更新的影响。
-Without built-in middleware, you must explicitly add all the
-middleware that is required to run your app. Simply follow these steps:
+由于不再包含内置中间件,你必须显式添加应用运行所需的全部中间件。 只需按照以下步骤操作:
1. Install the module: `npm install --save \`
-2. In your app, require the module: `require('module-name')`
-3. Use the module according to its documentation: `app.use( ... )`
+2. 在你的应用中,引入该模块:`require('module-name')`
+3. 按照其文档说明使用该模块:`app.use( ...` )\`
-The following table lists Express 3 middleware and their counterparts in Express 4.
+下表列出了 Express 3 中间件及其在 Express 4 中的对应模块。
@@ -187,16 +167,14 @@ The following table lists Express 3 middleware and their counterparts in Express
-Here is the [complete list](https://github.com/senchalabs/connect#middleware) of Express 4 middleware.
+此处为 Express 4 中间件的[完整清单](https://github.com/senchalabs/connect#middleware)。
-In most cases, you can simply replace the old version 3 middleware with
-its Express 4 counterpart. For details, see the module documentation in
-GitHub.
+大多数情况下,你只需将旧版3中间件替换为对应的Express 4版本即可。 详情请参阅 GitHub 上的模块文档。
-#### `app.use` accepts parameters
+#### `app.use` 接受参数
-In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler.
-For example:
+在版本4中,你可以使用可变参数来定义加载中间件函数的路径,然后从路由处理程序中读取该参数的值。
+举个例子:
```js
app.use('/book/:id', (req, res, next) => {
@@ -205,25 +183,21 @@ app.use('/book/:id', (req, res, next) => {
});
```
-### The routing system
+### 路由系统
-Apps now implicitly load routing middleware, so you no longer have to
-worry about the order in which middleware is loaded with respect to
-the `router` middleware.
+应用现在会隐式加载路由中间件,因此你无需再担心中间件相对于 `router` 中间件的加载顺序。
-The way you define routes is unchanged, but the routing system has two
-new features to help organize your routes:
+定义路由的方式未发生改变,但路由系统新增了两项功能,可帮助你更好地组织路由:
-- A new method, `app.route()`, to create chainable route handlers for a route path.
-- A new class, `express.Router`, to create modular mountable route handlers.
+- 新增方法 `app.route()`,用于为路由路径创建可链式调用的路由处理程序。
+- 新增类 `express.Router`,用于创建模块化的、可挂载的路由处理程序。
-#### `app.route()` method
+#### `app.route()` 方法
-The new `app.route()` method enables you to create chainable route handlers
-for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more
+新增的 `app.route()` 方法支持你为路由路径创建可链式调用的路由处理程序。 由于路径在单一位置指定,因此创建模块化路由十分实用,同时还能减少冗余代码和拼写错误。 For more
information about routes, see [`Router()` documentation](/4x/api#router).
-Here is an example of chained route handlers that are defined by using the `app.route()` function.
+以下是使用 `app.route()` 函数定义的链式路由处理程序示例。
```js
app
@@ -239,20 +213,15 @@ app
});
```
-#### `express.Router` class
+#### `express.Router` 类
-The other feature that helps to organize routes is a new class,
-`express.Router`, that you can use to create modular mountable
-route handlers. A `Router` instance is a complete middleware and
-routing system; for this reason it is often referred to as a "mini-app".
+另一项有助于组织路由的功能是新增的 `express.Router` 类,你可以使用它创建模块化的、可挂载的路由处理程序。 `Router` 实例是完整的中间件和路由系统;因此它通常被称为“迷你应用”。
-The following example creates a router as a module, loads middleware in
-it, defines some routes, and mounts it on a path on the main app.
+以下示例创建一个路由作为模块,在其中加载中间件、定义若干路由,并将其挂载到主应用的路径上。
-For example, create a router file named `birds.js` in the app directory,
-with the following content:
+例如,在应用目录中创建一个名为 `birds.js` 的路由文件,内容如下:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +242,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
-Then, load the router module in the app:
+```mjs title="birds.mjs"
+import express from 'express';
-```js
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
+然后,在应用程序中加载路由模块:
+
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,13 +274,19 @@ var birds = require('./birds');
app.use('/birds', birds);
```
-The app will now be able to handle requests to the `/birds` and
-`/birds/about` paths, and will call the `timeLog`
-middleware that is specific to the route.
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
+应用现在能够处理 `/birds` 和 `/birds/about` 路径的请求,并会调用专用于该路由的 `timeLog` 中间件。
-### Other changes
+### 其他改变:
-The following table lists other small but important changes in Express 4:
+下表列出了 Express 4 中其他细微但重要的变更:
@@ -298,84 +295,81 @@ The following table lists other small but important changes in Express 4:
| Node.js |
- Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. |
+ Express 4 requires Node.js 0.10.x 或更高版本,并且已经放弃了对 Node.js 0.8.x的支持。 |
| `http.createServer()` |
- The `http` module is no longer needed, unless you need to directly work with it
- (socket.io/SPDY/HTTPS). The app can be started by using the `app.listen()` function.
+ 不再需要`http`模块,除非你需要直接使用 (socket.io/SPDY/HTTPS). 可通过 `app.listen()`
+ 函数启动应用。
|
| `app.configure()` |
- The `app.configure()` function has been removed. Use the `process.env.NODE_ENV` or
- `app.get('env')` function to detect the environment and configure the app accordingly.
+ `app.configure()` 函数已被删除。 使用 `process.env.NODE_ENV` 或 `app.get('env)`
+ 函数检测环境并相应配置应用程序。
|
| `json spaces` |
-
- The `json spaces` application property is disabled by default in Express 4.
- |
+ Express 4默认禁用了 "json spaces" 应用程序属性。 |
| `req.accepted()` |
- Use `req.accepts()`, `req.acceptsEncodings()`, `req.acceptsCharsets()`, and
+ 使用`req.accepts()`, `req.acceptsEncodings()`, `req.acceptsCharsets()`, 和
`req.acceptsLanguages()`.
|
| `res.location()` |
- No longer resolves relative URLs. |
+ 不再解析相对 URL。 |
| `req.params` |
- Was an array; now an object. |
+ 原为数组;现为对象。 |
| `res.locals` |
- Was a function; now an object. |
+ 原为函数;现为对象。 |
- | `res.headerSent` |
- Changed to `res.headersSent`. |
+ "res.headerSent" |
+ 更改为 "res.headersSent"。 |
- | `app.route` |
- Now available as `app.mountpath`. |
+ "app.route" |
+ 现在可用于“app.mountpath"。 |
| `res.on('header')` |
- Removed. |
+ 删除。 |
| `res.charset` |
- Removed. |
+ 删除。 |
| `res.setHeader('Set-Cookie', val)` |
- Functionality is now limited to setting the basic cookie value. Use `res.cookie()` for added
- functionality.
+ 功能现已受限,仅用于设置基础的 Cookie 值。 如需使用更多功能,请使用 `res.cookie()`。
|
-## Example app migration
+## 应用迁移示例
-Here is an example of migrating an Express 3 application to Express 4.
-The files of interest are `app.js` and `package.json`.
+以下是将 Express 3 应用迁移至 Express 4 的示例。
+需要关注的文件是 `app.js` 和 `package.json`。
-### Version 3 app
+### 版本 3 应用
#### `app.js`
-Consider an Express v.3 application with the following `app.js` file:
+假设一个 Express 3 版本的应用拥有如下 `app.js` 文件:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -409,10 +403,43 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
-The accompanying version 3 `package.json` file might look
-something like this:
+对应的 Express 3 版 `package.json` 文件大致如下:
```json
{
@@ -429,36 +456,26 @@ something like this:
}
```
-### Process
+### 流程
-Begin the migration process by installing the required middleware for the
-Express 4 app and updating Express and Pug to their respective latest
-version with the following command:
+开始迁移流程:执行以下命令,安装 Express 4 应用所需的中间件,并将 Express 和 Pug 更新至各自的最新版本。
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
-Make the following changes to `app.js`:
+对 `app.js` 进行如下修改:
-1. The built-in Express middleware functions `express.favicon`,
- `express.logger`, `express.methodOverride`,
- `express.session`, `express.bodyParser` and
- `express.errorHandler` are no longer available on the
- `express` object. You must install their alternatives
- manually and load them in the app.
+1. Express 内置中间件函数 `express.favicon`、`express.logger`、`express.methodOverride`、`express.session`、`express.bodyParser` 和 `express.errorHandler` 已从 `express` 对象中移除。 你必须手动安装它们的替代模块,并在应用中引入加载。
-2. You no longer need to load the `app.router` function.
- It is not a valid Express 4 app object, so remove the
- `app.use(app.router);` code.
+2. 你不再需要加载 `app.router` 函数。
+ 它并非有效的 Express 4 应用对象,因此请删除 `app.use(app.router); `代码。
-3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes.
+3. 确保中间件函数按正确顺序加载——在应用路由加载完毕后再加载`errorHandler`。
-### Version 4 app
+### 版本 4 应用
#### `package.json`
-Running the above `npm` command will update `package.json` as follows:
+运行上述 `npm` 命令将会按如下方式更新 `package.json` 文件:
```json
{
@@ -484,10 +501,9 @@ Running the above `npm` command will update `package.json` as follows:
#### `app.js`
-Then, remove invalid code, load the required middleware, and make other
-changes as necessary. The `app.js` file will look like this:
+然后,移除无效代码,加载所需的中间件,并根据需要进行其他更改。 `app.js`文件看起来像这样:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -537,8 +553,57 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
-Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way:
+除非你需要直接操作 `http` 模块(socket.io/SPDY/HTTPS),否则无需加载该模块,应用可通过以下方式直接启动:
```js
app.listen(app.get('port'), () => {
@@ -548,97 +613,69 @@ app.listen(app.get('port'), () => {
-### Run the app
+### 运行应用
-The migration process is complete, and the app is now an
-Express 4 app. To confirm, start the app by using the following command:
+迁移流程已完成,当前应用已升级为 Express 4 应用。 若要确认,请使用以下命令启动应用:
```bash
$ node .
```
-Load [http://localhost:3000](http://localhost:3000)
-and see the home page being rendered by Express 4.
+访问 [http://localhost:3000](http://localhost:3000),查看由 Express 4 渲染的首页。
-## Upgrading to the Express 4 app generator
+## 升级至 Express 4 应用生成器
-The command-line tool to generate an Express app is still
-`express`, but to upgrade to the new version, you must uninstall
-the Express 3 app generator and then install the new
-`express-generator`.
+用于生成 Express 应用的命令行工具仍为 `express`,但要升级至新版本,你必须先卸载 Express 3 应用生成器,然后安装全新的 `express-generator`。
-### Installing
+### 安装
-If you already have the Express 3 app generator installed on your system,
-you must uninstall it:
+如果你的系统中已安装 Express 3 应用生成器,必须先将其卸载:
-```bash
-$ npm uninstall -g express
-```
+
-Depending on how your file and directory privileges are configured,
-you might need to run this command with `sudo`.
+根据你的文件和目录权限配置,你可能需要使用 `sudo` 运行该命令。
-Now install the new generator:
+现在安装新版生成器:
-```bash
-$ npm install -g express-generator
-```
+
-Depending on how your file and directory privileges are configured,
-you might need to run this command with `sudo`.
+根据你的文件和目录权限配置,你可能需要使用 `sudo` 运行该命令。
-Now the `express` command on your system is updated to the
-Express 4 generator.
+现在,你系统中的 `express` 命令已更新为 Express 4 生成器。
-### Changes to the app generator
+### 更改应用生成器
-Command options and use largely remain the same, with the following exceptions:
+命令选项和用法基本保持不变,仅存在以下例外:
-- Removed the `--sessions` option.
-- Removed the `--jshtml` option.
+- 已移除`--sessions`选项。
+- 移除了 "--jshtml" 选项。
- Added the `--hogan` option to support [Hogan.js](http://twitter.github.io/hogan.js/).
-### Example
+### 示例
-Execute the following command to create an Express 4 app:
+执行以下命令来创建一个Express 4应用:
```bash
$ express app4
```
-If you look at the contents of the `app4/app.js` file, you will notice
-that all the middleware functions (except `express.static`) that are required for
-the app are loaded as independent modules, and the `router` middleware
-is no longer explicitly loaded in the app.
+查看 `app4/app.js` 文件的内容,你会发现应用所需的所有中间件函数(`express.static` 除外)均作为独立模块加载,且应用中不再显式加载 `router` 中间件。
-You will also notice that the `app.js` file is now a Node.js module, in contrast to the standalone app that was generated by the old generator.
+你还会注意到,`app.js` 文件现在是一个 Node.js 模块,这与旧版生成器生成的独立应用不同。
-After installing the dependencies, start the app by using the following command:
+安装依赖项后,使用以下命令启动应用:
```bash
$ npm start
```
-If you look at the `npm start` script in the `package.json` file,
-you will notice that the actual command that starts the app is
-`node ./bin/www`, which used to be `node app.js`
-in Express 3.
+查看 `package.json` 文件中的 `npm start` 脚本,你会发现启动应用的实际命令是 `node ./bin/www`,而在 Express 3 中该命令为 `node app.js`。
-Because the `app.js` file that was generated by the Express 4 generator
-is now a Node.js module, it can no longer be started independently as an app
-(unless you modify the code). The module must be loaded in a Node.js file
-and started via the Node.js file. The Node.js file is `./bin/www`
-in this case.
+由于 Express 4 生成器生成的 `app.js` 文件现已成为一个 Node.js 模块,因此无法再作为应用独立启动(除非你修改代码)。 必须将该模块加载到 Node.js 文件中,并通过该文件启动应用。 在本例中,这个 Node.js 文件就是 `./bin/www`。
-Neither the `bin` directory nor the extensionless `www`
-file is mandatory for creating an Express app or starting the app. They are
-just suggestions made by the generator, so feel free to modify them to suit your
-needs.
+创建或启动 Express 应用时,`bin` 目录和无后缀的 `www` 文件都不是必需的。 这些仅为生成器给出的建议,你可按需自行修改。
-To get rid of the `www` directory and keep things the "Express 3 way",
-delete the line that says `module.exports = app;` at the end of the
-`app.js` file, then paste the following code in its place:
+若要移除 `www` 目录并沿用“Express 3 风格”,请删除 `app.js` 文件末尾的 `module.exports = app;` 这一行,然后将以下代码粘贴到该位置:
```js
app.set('port', process.env.PORT || 3000);
@@ -648,15 +685,12 @@ var server = app.listen(app.get('port'), () => {
});
```
-Ensure that you load the `debug` module at the top of the `app.js` file by using the following code:
+确保你通过以下代码在 `app.js` 文件顶部加载 `debug` 模块:
```js
var debug = require('debug')('app4');
```
-Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`.
+接下来,将 `package.json` 文件中的 `"start": "node ./bin/www"` 改为 `"start": "node app.js"`。
-You have now moved the functionality of `./bin/www` back to
-`app.js`. This change is not recommended, but the exercise helps you
-to understand how the `./bin/www` file works, and why the `app.js` file
-no longer starts on its own.
+你现已将 `./bin/www` 的功能移回至 `app.js`。 不推荐进行此项修改,但该实操能帮你理解 `./bin/www` 文件的工作原理,以及 `app.js` 无法独立启动的原因。
diff --git a/src/content/pages/zh-cn/guide/migrating-5.mdx b/src/content/pages/zh-cn/guide/migrating-5.mdx
index 3dfdd8d0ff..866c7cc59c 100644
--- a/src/content/pages/zh-cn/guide/migrating-5.mdx
+++ b/src/content/pages/zh-cn/guide/migrating-5.mdx
@@ -1,59 +1,52 @@
---
-title: Upgrade to Express v5
-description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements.
+title: 升级到 Express v5
+description: Express.js 应用从 4 版升级至 5 版完整迁移指南,详述破坏性变更、废弃方法与新增优化项
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Express 5 is not very different from Express 4; although it maintains the same basic API, there are still changes that break compatibility with the previous version. Therefore, an application built with Express 4 might not work if you update it to use Express 5.
+Express 5 与 Express 4 差异不大;尽管基础 API 保持一致,但仍存在部分导致无法向下兼容的改动。 因此,基于 Express 4 构建的应用在升级至 Express 5 后可能无法正常运行。
-## Installation
+## 安装
-To install this version, you need to have a **Node.js version 18 or higher**. Then, execute the following command in your application directory:
+安装该版本需要 **Node.js 18 及以上版本**。 随后在应用目录中执行以下命令:
-```sh
-npm install "express@5"
-```
+
-You can then run your automated tests to see what fails, and fix problems according to the updates listed below. 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.
+为帮助你迁移 Express 服务器,我们提供了一套代码转换工具,可自动将代码更新至最新版 Express。
-Run the following command for run all the codemods available:
+运行以下命令以执行所有可用的代码转换:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
-If you want to run a specific codemod, you can run the following command:
+若要运行特定的代码转换,可执行以下命令:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
-You can find the list of available codemods [here](https://codemod.link/express).
+可在[此处](https://codemod.link/express)查看可用的代码转换列表。
-## Removed methods and properties
+## 移除方法和属性
-If you use any of these methods or properties in your app, it will crash. So, you'll need to change your app after you update to version 5.
+如果你的应用中使用了上述任意方法或属性,应用将会崩溃。 因此,更新到 5 版本后,你需要修改你的应用。
### app.del()
-Express 5 no longer supports the `app.del()` function. If you use this function, an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead.
+Express 5 不再支持 `app.del()` 函数。 如果您使用此函数,将会出现错误。 要注册 HTTP DELETE 路由,请使用 `app.delete()` 函数。
-Initially, `del` was used instead of `delete`, because `delete` is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names.
+起初,使用 `del` 而非 `delete`,因为 `delete` 是 JavaScript 中的保留关键字。 但从 ECMAScript 6 开始,`delete` 及其他保留关键字可以合法用作属性名。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
-app.del('/user/:id', (req, res) => {
@@ -64,27 +57,25 @@ Or you can update your code manually:
### app.param(fn)
-The `app.param(fn)` signature was used for modifying the behavior of the `app.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.
+`app.param(fn)` 签名用于修改 `app.param(name, fn)` 函数的行为。 该方法自 v4.11.0 起已被弃用,Express 5 完全不再支持它。
-### Pluralized method names
+### 复数形式的方法名
-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:
+以下方法名已改为复数形式。 在 Express 4 中,使用旧方法会触发弃用警告。 Express 5 已完全不再支持这些方法:
-`req.acceptsCharset()` is replaced by `req.acceptsCharsets()`.
+`req.acceptsCharset()`替换为`req.acceptsets()`。
-`req.acceptsEncoding()` is replaced by `req.acceptsEncodings()`.
+`req.acceptsEncoding()` 替换为 `req.acceptsEncodings()` 。
-`req.acceptsLanguage()` is replaced by `req.acceptsLanguages()`.
+`req.acceptsLanguage()` 替换为 `req.acceptsLanguages()` 。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.all('/', (req, res) => {
@@ -99,25 +90,23 @@ Or you can update your code manually:
});
```
-### Leading colon (:) in the name for app.param(name, fn)
+### `app.param(name, fn)` 中名称前的冒号(:)
-A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
+`app.param(name, fn)` 函数中名称开头的冒号(:)是 Express 3 的遗留用法,为了向后兼容,Express 4 虽支持该用法但会抛出弃用提示。 Express 5 会静默忽略该冒号,并直接使用不带冒号前缀的名称参数。
-This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api#app.param), as it makes no mention of the leading colon.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(name)
-This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in the `req.params`, `req.body`, or `req.query` object.
+这种可能造成混淆且存在风险的表单数据获取方法已被移除。 现在你需要在 `req.params`、`req.body` 或 `req.query` 对象中显式查找提交的参数名称。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.post('/user', (req, res) => {
@@ -134,17 +123,15 @@ Or you can update your code manually:
### res.json(obj, status)
-Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`.
+Express 5 不再支持 `res.json(obj, status)` 签名。 取而代之的是,先设置状态码,再链式调用 `res.json()` 方法,写法如下:`res.status(status).json(obj)`。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.post('/user', (req, res) => {
@@ -155,17 +142,15 @@ Or you can update your code manually:
### res.jsonp(obj, status)
-Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`.
+Express 5 不再支持 `res.jsonp(obj, status)` 签名。 取而代之的是,先设置状态码,再链式调用 `res.jsonp()` 方法,写法如下:`res.status(status).jsonp(obj)`。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.post('/user', (req, res) => {
@@ -176,38 +161,39 @@ Or you can update your code manually:
### res.redirect(url, status)
-Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`.
+Express 5 不再支持 `res.redirect(url, status)` 签名。 相反,使用下列签名:`res.redirect(status, url)`。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
-### res.redirect('back') and res.location('back')
+### res.redirect('back') 与 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.
+Express 5 不再支持 `res.redirect()` 和 `res.location()` 方法中的魔法字符串 `back`。 取而代之,请使用 `req.get('Referrer') || '/'` 来重定向回上一页。 在 Express 4 中,`res.redirect('back')` 和 `res.location('back')` 方法已被弃用。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.get('/user', (req, res) => {
@@ -218,17 +204,15 @@ Or you can update your code manually:
### 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)`.
+Express 5 不再支持 `res.send(obj, status)` 这种签名。 取而代之的是,先设置状态码,再链式调用 `res.send()` 方法,写法如下:`res.status(status).send(obj)`。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.get('/user', (req, res) => {
@@ -239,18 +223,16 @@ Or you can update your code manually:
### 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.
+Express 5 不再支持签名 `res.send(status)` 是一个数字。 取而代之,请使用 `res.sendStatus(statusCode)` 函数,该函数会设置 HTTP 响应头状态码并发送该状态码的文本版本:“未找到”、“服务器内部错误”等。
+如果需要通过 `res.send()` 函数发送数字,请将数字用引号包裹转换为字符串,避免 Express 将其误判为尝试使用已不支持的旧签名。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.get('/user', (req, res) => {
@@ -261,17 +243,15 @@ Or you can update your code manually:
### res.sendfile()
-The `res.sendfile()` function has been replaced by a camel-cased version `res.sendFile()` in Express 5.
+在 Express 5 中,`res.sendfile()` 函数已替换为驼峰命名的版本 `res.sendFile()`。
-#### How to update
+#### 如何更新
-You can automatically update your code by running the following command:
+你可以通过运行以下命令自动更新你的代码:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
-Or you can update your code manually:
+或者您可以手动更新您的代码:
```diff
app.get('/user', (req, res) => {
@@ -282,9 +262,13 @@ Or you can update your code manually:
### res.sendFile() options
-The `hidden` and `from` options for `res.sendFile()` are no longer supported. Use `dotfiles` and `root` instead.
+`res.sendFile()` 的 `hidden` 和 `from` 选项已不再支持。 使用 `dotfiles` 和 `root` 代替。
-#### How to update
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
+#### 如何更新
```diff
app.get('/files/:name', (req, res) => {
@@ -293,11 +277,29 @@ The `hidden` and `from` options for `res.sendFile()` are no longer supported. Us
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### express.static() options
-The `hidden` and `from` options for `express.static()` are no longer supported. Use `dotfiles` and `root` instead. Note that `from` was never documented in the API but was accepted as an alias for `root`. The default value of `dotfiles` is now `"ignore"`.
+不再支持 `expres.static()` 的 `hidden` 和 `from` 两个选项。 使用 `dotfiles` 和 `root` 代替。 注意,`from` 从未在 API 文档中记载,但曾被接受作为 `root` 的别名。 `dotfiles`的默认值现在是 \`"ignore"。
+
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
+#### 如何更新
+
+你可以通过运行以下命令自动更新你的代码:
-#### How to update
+
+
+或者您可以手动更新您的代码:
```diff
const express = require('express');
@@ -307,16 +309,23 @@ The `hidden` and `from` options for `express.static()` are no longer supported.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### 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.
+`router.param(fn)` 签名曾用于修改 `router.param(name, fn)` 函数的行为。 该方法自 v4.11.0 起已被弃用,Express 5 完全不再支持它。
### express.static.mime
-In Express 5, `mime` is no longer an exported property of the `static` field.
-Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values.
+在 Express 5 中,`mime` 不再是 `static` 字段的导出属性。
+请使用 [`mime-types` 包](https://github.com/jshttp/mime-types) 处理 MIME 类型值。
-#### How to update
+#### 如何更新
```diff
-express.static.mime.lookup('json');
@@ -324,17 +333,17 @@ Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work wit
+mime.lookup('json');
```
-### MIME type changes
+### MIME 类型更改
-Several MIME types have changed due to updates in [`mime-db`](https://github.com/jshttp/mime-db). These changes only affect `express.static()` and `res.sendFile()`. For a full list of changes, see the [`mime-db` changelog](https://github.com/jshttp/mime-db/blob/HEAD/HISTORY.md).
+由于[`mime-db`](https://github.com/jshttp/mime-db) 的更新,几种MIME类型已经更改。 这些更改只会影响 `expres.static()` 和 `res.sendFile()` 。 完整的更改列表见[`mime-db`更新日志](https://github.com/jshttp/mime-db/blob/HEAD/HISTORY.md)。
-Express 4 uses `mime-db` version **1.52.0**, while Express 5 uses newer versions that reflect updates to IANA and other MIME type specifications. The most notable change is that JavaScript files (`.js`) are now served as `text/javascript` instead of `application/javascript`.
+Express 4 使用 **1.52.0** 版本的 `mime-db`,而 Express 5 使用了更新的版本,以反映 IANA 及其他 MIME 类型规范的更新。 最显著的变化是,JavaScript 文件(`.js`)现在以 `text/javascript` 提供服务,而非 `application/javascript`。
-In Express 5, changes to MIME types from `mime-db` updates are not considered breaking changes, so be careful when updating your dependencies as MIME types may change between minor or patch versions.
+在 Express 5 中,由 `mime-db` 更新带来的 MIME 类型变更**不被视为破坏性变更**,因此在更新依赖项时请务必谨慎,因为 MIME 类型可能在次要版本或补丁版本之间发生变化。
-### express:router debug logs
+### express:router 调试日志
-Router handling logic is now performed by a separate dependency ([`router`](https://github.com/pillarjs/router)) maintained by the Express team, so debug logs have moved to a different namespace. Before Express 5.1, these debug logs did not exist. To get them, update to a recent Express 5 version or update the `router` package in your `package-lock.json`:
+路由器处理逻辑现在由 Express 团队维护的独立依赖项([`router`](https://github.com/pillarjs/router))执行,因此调试日志已迁移至其他命名空间。 在Express 5.1之前,这些调试日志不存在。 若要获取这些日志,请更新至最新的 Express 5 版本,或更新 `package-lock.json` 中的 `router` 包:
| v4 | v5 |
| -------------------------- | ----------------------------------- |
@@ -343,22 +352,22 @@ Router handling logic is now performed by a separate dependency ([`router`](http
| `express:router:route` | `router:route` |
| `express:*` (includes all) | `express:*` + `router` + `router:*` |
-#### How to update
+#### 如何更新
```diff
-DEBUG=express:* node index.js
+DEBUG=express:*,router,router:* node index.js
```
-## Changed
+## 更改
-These APIs still exist but their behavior has changed. Review these changes to make sure your app works as expected.
+这些 API 仍然保留,但行为已发生变更。 请检查这些变更,确保你的应用正常运行。
-### 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:
+路径路由匹配语法是指将字符串作为第一个参数传递给 `app.all()`、`app.use()`、`app.METHOD()`、`router.all()`、`router.METHOD()` 和 `router.use()` 这些 API。 已对路径字符串与传入请求的匹配规则做出如下修改:
-- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*`
+- 通配符 `*` 必须指定名称,和参数标记 `:` 的使用规则保持一致,请使用 `/*splat` 而非 `/*`
```diff
-app.get('/*', async (req, res) => {
@@ -369,7 +378,7 @@ Path route matching syntax is when a string is supplied as the first parameter t
- `*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.
+ `*splat` 匹配没有根路径的任何路径。 如果你需要同时匹配根路径,你可以使用 `/{*splat}` 来包装括号中的通配符。
```js
app.get('/{*splat}', async (req, res) => {
@@ -379,7 +388,7 @@ Path route matching syntax is when a string is supplied as the first parameter t
-- The optional character `?` is no longer supported, use braces instead.
+- 可选标识 `?` 不再受支持,请改用大括号写法。
```diff
-app.get('/:file.:ext?', async (req, res) => {
@@ -388,7 +397,7 @@ Path route matching syntax is when a string is supplied as the first parameter t
});
```
-- Regexp characters are not supported. For example:
+- 路由路径中不支持正则表达式字符。 举个例子:
```diff
-app.get('/[discussion|page]/:slug', async (req, res) => {
@@ -397,19 +406,19 @@ Path route matching syntax is when a string is supplied as the first parameter t
});
```
-- 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"`.
+- 参数名称现支持合法的 JavaScript 标识符,或使用 `:"this"` 形式进行引号包裹。
-### Rejected promises handled from middleware and handlers
+### 处理来自中间件和处理器的被拒绝 Promise
-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)`.
+返回被拒绝 Promise 的请求中间件和处理程序,现会将被拒绝的值作为 `Error` 转发给错误处理中间件进行处理。 这意味着使用 `async` 函数编写中间件和处理程序变得前所未有的简便。 当在 `async` 函数中抛出错误,或在异步函数内 `await` 了一个被拒绝的 Promise 时,这些错误将被传递给错误处理程序,效果等同于调用 `next(err)`。
Details of how Express handles errors is covered in the [error handling documentation](/guide/error-handling).
-#### How to update
+#### 如何更新
-You can now use `async/await` directly without manually catching errors. If `getUserById` throws an error or rejects, `next` will be called automatically with the rejected value.
+你现在可以直接使用 `async/await`,无需手动捕获错误。 若 `getUserById` 抛出错误或被拒绝,`next` 会自动以被拒绝的值作为参数被调用。
```diff
-app.get('/user/:id', (req, res, next) => {
@@ -425,11 +434,11 @@ You can now use `async/await` directly without manually catching errors. If `get
### express.urlencoded
-The `express.urlencoded` method makes the `extended` option `false` by default.
+`express.urlencoded` 方法的 `extended` 选项默认值为 `false`。
-#### How to update
+#### 如何更新
-If your application relies on the `extended` behavior, explicitly set it to `true`:
+如果你的应用依赖 `extended` 特性,请将其显式设置为 `true`:
```diff
-app.use(express.urlencoded());
@@ -438,21 +447,40 @@ If your application relies on the `extended` behavior, explicitly set it to `tru
### express.static dotfiles
-The `express.static` middleware's `dotfiles` option now defaults to `"ignore"`. In Express 4, dotfiles were served by default. As a result, files inside a directory that starts with a dot (`.`), such as `.well-known`, will no longer be accessible and will return a **404 Not Found** error. This can break functionality that depends on serving dot-directories, such as Android App Links and Apple Universal Links.
+`express.static` 中间件的 `dotfiles` 选项现在默认值为 `"ignore"`。 在 Express 4 中,点文件默认提供服务。 因此,以点(`.`)开头的目录(如 `.well-known`)内的文件将不再可访问,并会返回**404 未找到**错误。 这可能会破坏依赖于提供点目录服务的功能,例如 Android 应用链接和 Apple 通用链接。
-#### How to update
+#### 如何更新
-Serve specific dot-directories explicitly using the `dotfiles: "allow"` option. This allows you to safely serve only the intended dot-directories while keeping the default secure behavior for other dotfiles.
+使用 `dotfiles: "allow"` 选项显式提供特定的点目录服务。 这使你可以安全地仅提供预期的点目录,同时对其他点文件保持默认的安全行为。
```diff
+app.use('/.well-known', express.static('public/.well-known', { dotfiles: 'allow' }));
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### 如何更新
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### 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:
+在 Express 5 中,当服务器接收到错误事件时,`app.listen` 方法会调用用户提供的回调函数(若已指定)。 在 Express 4 中,这类错误会被直接抛出。 在 Express 5 中,此项变更将错误处理的职责转移给了回调函数。 如果发生错误,错误将作为参数传递给回调函数。
+举个例子:
```js ins={2-4}
const server = app.listen(8080, '0.0.0.0', (error) => {
@@ -465,11 +493,11 @@ const server = app.listen(8080, '0.0.0.0', (error) => {
### app.router
-The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. 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.
+在 Express 4 中被移除的 `app.router` 对象,在 Express 5 中重新回归。 在新版本中,该对象只是对基础 Express 路由的引用,这与 Express 3 不同,在 Express 3 中应用必须显式加载它。
### req.body
-The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default.
+当请求体尚未被解析时,`req.body` 属性会返回 `undefined`。 在Express 4中,默认情况下返回 `{}` 。
```js del={4} ins={6}
app.post('/user', (req, res) => {
@@ -483,15 +511,15 @@ app.post('/user', (req, res) => {
### req.host
-In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5, the port number is maintained.
+在Express 4中,如果存在`req.host`函数,它会不正确地删除端口号。 Express 5中保留端口号。
### req.params
-The `req.params` object now has a **null prototype** when using string paths. However, if the path is defined with a regular expression, `req.params` remains a standard object with a normal prototype. Additionally, there are two important behavioral changes:
+当使用字符串路径时,`req.params`对象现在有一个 **null 原型** 。 但是,如果路径使用正则表达式定义,`req.params` 仍为带有标准原型的普通对象。 此外,还有两项重要的行为变更:
-**Wildcard parameters are now arrays:**
+**WildCard 参数现在是数组:**
-Wildcards (e.g., `/*splat`) capture path segments as an array instead of a single string.
+Wildcards(例如 `/*splat`)会将路径片段捕获为数组,而非单个字符串。
```js
app.get('/*splat', (req, res) => {
@@ -501,9 +529,9 @@ app.get('/*splat', (req, res) => {
});
```
-**Unmatched parameters are omitted:**
+**未匹配参数:**
-In Express 4, unmatched wildcards were empty strings (`''`) and optional `:` parameters (using `?`) had a key with value `undefined`. In Express 5, unmatched parameters are completely omitted from `req.params`.
+在 Express 4 中,不匹配的通配符为空字符串(`''`),可选 `:` 参数(使用 `?`)会存在键且值为 `undefined`。 在 Express 5 中,不匹配的参数会从 `req.params` 中完全省略。
```diff
-// v4: unmatched wildcard is empty string
@@ -530,7 +558,7 @@ In Express 4, unmatched wildcards were empty strings (`''`) and optional `:` par
### 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".
+`req.query` 属性不再是可写属性,而是一个 getter。 默认查询解析器已从 "extended" 更改为 "simple"。
```js del={3}
app.get('/search', (req, res) => {
@@ -541,7 +569,7 @@ app.get('/search', (req, res) => {
### res.clearCookie
-The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user.
+`res.clearCookie` 方法会忽略用户提供的 `maxAge` 和 `expires` 选项。
```diff
app.get('/logout', (req, res) => {
@@ -552,7 +580,7 @@ The `res.clearCookie` method ignores the `maxAge` and `expires` options provided
### 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.status` 方法仅接受 `100` 至 `999` 范围内的整数,遵循 Node.js 定义的行为,当状态码不是整数时会返回错误。
```js del={2}
app.get('/user', (req, res) => {
@@ -563,7 +591,7 @@ app.get('/user', (req, res) => {
### 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.
+当缺少`field`参数时,`res.vary`会抛出错误。 在 Express 4 中,如果省略该参数,控制台会输出一条警告信息。
```js del={2}
app.get('/user', (req, res) => {
@@ -572,14 +600,14 @@ app.get('/user', (req, res) => {
});
```
-## Improvements
+## 改进
-These changes don't require any migration steps, but are worth knowing about when upgrading.
+这些变更无需执行任何迁移操作,但在升级时了解这些内容会很有帮助。
### res.render()
-This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines that had a synchronous implementation and that violated the recommended interface.
+该方法现在强制所有模板引擎遵循异步行为,避免了因部分模板引擎采用同步实现、违反推荐接口而导致的错误。
-### Brotli encoding support
+### Brotli编码支持
-Middleware like `express.json()`, `express.urlencoded()`, `express.text()`, and `express.raw()` now support Brotli (`Content-Encoding: br`) decompression for incoming request bodies, in addition to `gzip` and `deflate`.
+除 `gzip` 和 `deflate` 外,`express.json()`、`express.urlencoded()`、`express.text()` 和 `express.raw()` 等中间件现在还支持对传入请求体进行 Brotli(`Content-Encoding: br`)解压。
diff --git a/src/content/pages/zh-cn/resources/community.mdx b/src/content/pages/zh-cn/resources/community.mdx
index 7da90b303d..f0aa376e8e 100644
--- a/src/content/pages/zh-cn/resources/community.mdx
+++ b/src/content/pages/zh-cn/resources/community.mdx
@@ -1,20 +1,17 @@
---
-title: Community
-description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions.
+title: 社区
+description: 加入Express.js社区,了解技术委员会相关信息、查找各类资源、浏览社区贡献模块并参与相关讨论。
---
import LogoDisplay from '@components/patterns/LogoDisplay/LogoDisplay.astro';
-## Technical committee
+## 技术委员会
-The Express technical committee meets online every two weeks (as needed) to discuss development and maintenance of Express,
-and other issues relevant to the Express project. Each meeting is typically announced in an
-[expressjs/discussions issue](https://github.com/expressjs/discussions/issues) with a link to join or view the meeting, which is
-open to all observers.
+Express技术委员会每两周按需召开线上会议,研讨Express的开发、维护工作以及项目相关的其他事宜。 每次会议通常会在[expressjs/discussions 议题](https://github.com/expressjs/discussions/issues)中发布通知,附带参会或旁听链接,所有人员均可列席观摩。
-The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g).
+会议全程录播,可前往 [Express.js YouTube 频道](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g)查看录播列表。
-Members of the Express technical committee are:
+Express技术委员会成员如下:
**Active:**
@@ -35,35 +32,33 @@ Members of the Express technical committee are:
- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce
- [@troygoode](https://github.com/troygoode) - Troy Goode
-## Express is made of many modules
+## Express由众多模块构成
Our vibrant community has created a large variety of extensions,
[middleware modules](/resources/middleware) and higher-level frameworks.
-Additionally, the Express community maintains modules in these two GitHub orgs:
+此外,Express社区在以下两个GitHub组织中维护各类模块:
- [jshttp](https://github.com/jshttp) modules providing useful utility functions; see [Utility modules](/resources/utils).
-- [pillarjs](https://github.com/pillarjs): low-level modules that Express uses internally.
+- [pillarjs](https://github.com/pillarjs):Express内部使用的底层模块。
-To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/).
+想要跟进整个社区动态,可查看 [ExpressJS 项目动态看板](https://expressjs.github.io/statusboard/)。
## Issues
-If you've come across what you think is a bug, or just want to make
-a feature request open a ticket in the [issue queue](https://github.com/expressjs/express/issues).
+若发现疑似漏洞,或是想要提交功能需求,请在[问题追踪列表](https://github.com/expressjs/express/issues)中新建工单。
## Examples
-View dozens of Express application [examples](https://github.com/expressjs/express/tree/master/examples)
-in the repository covering everything from API design and authentication to template engine integration.
+可在代码仓库查看数十个 Express 应用[示例](https://github.com/expressjs/express/tree/master/examples),内容涵盖接口设计、身份认证至模板引擎集成等各类场景。
## Github Discussions
-The [GitHub Discussions](https://github.com/expressjs/discussions) section is an excellent space to engage in conversations about the development and maintenance of Express, as well as to share ideas and discuss topics related to its usage.
+[GitHub 讨论区](https://github.com/expressjs/discussions)是交流Express开发维护事宜、分享想法以及探讨使用相关话题的优质平台。
## Express.js Logo
-Express is a project of the OpenJS Foundation. Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Express.js logos and marks.
+Express 是 OpenJS 基金会旗下项目。 如需了解Express.js标识与商标的合规使用规范,请查阅[商标使用规范](https://trademark-policy.openjsf.org/)。
### Wordmark
@@ -83,7 +78,7 @@ Express is a project of the OpenJS Foundation. Please review the [trademark poli
### Kawaii
-This logo was created by [SAWARATSUKI](https://github.com/SAWARATSUKI).
+该Logo由[SAWARATSUKI](https://github.com/SAWARATSUKI)设计。
-Before reporting a vulnerability, please review the [Express Threat Model](#the-express-threat-model) to check if the issue falls within Express's security scope.
+提交漏洞前,请先查阅【Express威胁模型](#the-express-threat-model),确认问题在Express安全受理范围内。
-The Express team and community take all security vulnerabilities seriously.
-Thank you for improving the security of Express and related projects.
-We appreciate your efforts in responsible disclosure and will make every effort
-to acknowledge your contributions.
+Express 团队与社区高度重视所有安全漏洞问题。
+感谢您助力提升 Express 及其相关项目的安全性。
+感谢您遵循负责任披露原则提交漏洞,我们会尽全力标注致谢您的贡献。
-A [Security triage team member](https://github.com/expressjs/security-wg#security-triage-team-expressjssecurity-triage)
-or [the repo captain](https://github.com/expressjs/discussions/blob/master/docs/contributing/captains_and_committers.md)
-will acknowledge your report as soon as possible.
-These timelines may extend when our triage
-volunteers are away on holiday, particularly at the end of the year.
+安全初审组成员(链接:[Security triage team member](https://github.com/expressjs/security-wg#security-triage-team-expressjssecurity-triage))或仓库负责人(链接:[the repo captain](https://github.com/expressjs/discussions/blob/master/docs/contributing/captains_and_committers.md))会尽快确认收到你的漏洞报告。
+若漏洞初审志愿者休假(尤其年末时段),上述处理时限可能相应顺延。
-After the initial reply to your report, the security team will
-endeavor to keep you informed of the progress towards a fix and full
-announcement, and may ask for additional information or guidance.
+在初次回复漏洞上报后,安全团队会持续向你同步漏洞修复与正式公告的进展,同时可能会向你索要补充信息或相关说明。
-You can find more information about our process in [this guide](https://github.com/expressjs/security-wg/blob/main/docs/incident_response_plan.md)
+更多处理流程详情可查阅本指南:[this guide](https://github.com/expressjs/security-wg/blob/main/docs/incident_response_plan.md)
-#### Reporting Security Bugs via GitHub Security Advisory (Preferred)
+#### 通过 GitHub 安全通告上报安全漏洞(推荐方式)
-The preferred way to report security vulnerabilities is through
-[GitHub Security Advisories](https://github.com/advisories).
-This allows us to collaborate on a fix while maintaining the
-confidentiality of the report.
+上报安全漏洞的首选方式是通过 [GitHub 安全通告](https://github.com/advisories)。
+该方式便于我们在保密漏洞报告的前提下协作完成漏洞修复。
-To report a vulnerability
-([docs](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability)):
+漏洞上报方式(参考文档:[docs](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability))
-1. Visit the **Security** tab of the affected repository on GitHub.
-2. Click **Report a vulnerability** and follow the provided steps.
+1. 在 GitHub 上进入受影响仓库的**安全**标签页。
+2. 点击**上报漏洞**并按照指引步骤操作。
-This process applies to any repositories within the Express ecosystem.
-If you are unsure whether a repository falls under this policy,
-feel free to reach out via email.
+本流程适用于Express生态下的所有代码仓库。
+若无法确定对应仓库是否适用本规范,可通过邮件咨询。
-#### Reporting via Email
+#### 通过邮件上报
-If you prefer, you can also report security issues by emailing `express-security@lists.openjsf.org`.
+如需,你也可通过发送邮件至`express-security@lists.openjsf.org`来上报安全问题。
-To ensure a timely response, please include all relevant details directly in the email body rather than linking to external sources or attaching files.
+如需及时得到回复,请将全部相关信息直接写在邮件正文中,不要使用外链或附件。
-The lead maintainer will acknowledge your email within 48 hours and provide an initial response outlining the next steps. The security team will keep you updated on the progress and may request additional details.
+项目主维护人员会在48小时内确认收到邮件,并给出初步回复说明后续处理步骤。 安全团队会同步处理进度,并可能需要你补充相关细节。
-#### Third-Party Modules
+#### 第三方模块
-If the security issue pertains to a third-party module that is not directly maintained within the Express ecosystem, please report it to the maintainers of that module.
+若该安全问题属于非Express生态直接维护的第三方模块,请向对应模块维护者提交漏洞报告。
-### Disclosure Policy
+### 披露规范
-When the security team receives a security bug report, they will assign it to a
-primary handler. This person will coordinate the fix and release process,
-involving the following steps:
+安全团队收到安全漏洞报告后,会指派一名主要负责人处理。 该负责人统筹修复与发布流程,包含以下步骤:
-- Confirm the problem and determine the affected versions.
-- Audit code to find any potential similar problems.
-- Prepare fixes for all releases still under maintenance. These fixes will be
- released as fast as possible to npm.
+- 确认问题并确定受影响的版本。
+- 审核代码以查找所有潜在的同类问题。
+- 为所有仍在维护的版本准备修复方案。 这些修复会尽快发布至npm。
-### Comments on this Policy
+### 对此规范的意见
-If you have suggestions on how this process could be improved please submit a
-pull request.
+如果你对改进该流程有相关建议,请提交拉取请求。
-### The Express Threat Model
+### Express 威胁模型划
-The Express threat model defines the boundaries of what the framework considers its security responsibility. It establishes which elements are trusted (such as the developer, the runtime environment, and application code) versus untrusted (such as data from network connections). Issues arising from trusted elements are considered out of scope, while Express is responsible for safely handling untrusted data.
+Express 威胁模型划定了该框架所需承担安全责任的边界范围。 该文档划定了可信主体(如开发者、运行环境、应用代码)与不可信数据源(如网络传输数据)的界定范围。 由可信资源引发的问题不在(框架)负责范围内,而 Express 负责安全处理不可信数据。
-Many commonly reported concerns fall outside Express's security scope and are the responsibility of the application developer. Such as prototype pollution from unsanitized user input, misconfigured static file serving, or issues in third-party dependencies.
+很多常见反馈的安全隐患不在 Express 的安全保障范畴内,需要由应用开发者自行负责处理。 例如未经过滤的用户输入导致的原型污染、静态文件服务配置错误,或第三方依赖项中存在的问题。
-For complete details, see the [Express Threat Model](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md).
+完整细则请参阅:[Express 威胁模型](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md)。
diff --git a/src/content/pages/zh-cn/resources/glossary.mdx b/src/content/pages/zh-cn/resources/glossary.mdx
index 722d87bf44..cbf818e3d7 100644
--- a/src/content/pages/zh-cn/resources/glossary.mdx
+++ b/src/content/pages/zh-cn/resources/glossary.mdx
@@ -1,60 +1,59 @@
---
-title: Glossary
-description: A comprehensive glossary of terms related to Express.js, Node.js, middleware, routing, and other key concepts to help you understand and use Express effectively.
+title: 专业术语词汇表
+description: 涵盖 Express.js、Node.js、中间件、路由及其他核心概念的综合术语表,帮助你更好地理解并高效使用 Express。
---
import Alert from '@components/primitives/Alert/Alert.astro';
-## application
+## 应用程序
-In general, one or more programs that are designed to carry out operations for a specific purpose. In the context of Express, a program that uses the Express API running on the Node.js platform. Might also refer to an [app object](/api#express).
+通常指一个或多个为特定目的而设计并执行操作的程序。 在 Express 语境中,指运行在 Node.js 平台上并使用 Express API 的程序。 Might also refer to an [app object](/api#express).
## API
-Application programming interface. Spell out the abbreviation when it is first used.
+应用程序编程接口。 首次使用时请写出缩写的全称。
## Express
-A fast, un-opinionated, minimalist web framework for Node.js applications. In general, "Express" is preferred to "Express.js," though the latter is acceptable.
+一个快速、无约束、极简的 Node.js Web 应用框架。 一般情况下,推荐使用“Express”,而不是“Express.js”,不过后者也是可以接受的。
## libuv
-A multi-platform support library which focuses on asynchronous I/O, primarily developed for use by Node.js.
+一个跨平台支持库,专注于异步 I/O,主要为 Node.js 开发和使用。
-## middleware
+## 中间件
-A function that is invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:
+一个在 Express 路由层中、最终请求处理函数之前被调用的函数,它位于原始请求与最终目标路由处理之间。 关于中间件术语的一些细微说明:
-- `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware.
-- `app.use(mw)` is called _adding the middleware to the global processing stack_.
-- `app.get('/foo', mw, function (req, res) { ... })` is called _adding the middleware to the "GET /foo" processing stack_.
+- `var foo = require('middleware')` 被称为“引入”或“使用”一个 Node.js 模块。 随后,语句 `var mw = foo()` 通常会返回该中间件。
+- `app.use(mw)` 被称为“将中间件添加到全局处理栈中”。
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
-A software platform that is used to build scalable network applications. Node.js uses JavaScript as its scripting language, and achieves high throughput via non-blocking I/O and a single-threaded event loop. See [nodejs.org](https://nodejs.org/en/). **Usage note**: Initially, "Node.js," thereafter "Node".
+用于构建可扩展网络应用的软件平台。 Node.js 使用 JavaScript 作为脚本语言,并通过非阻塞 I/O 和单线程事件循环实现高吞吐量。 See [nodejs.org](https://nodejs.org/en/). **用法说明**:首次使用写“Node.js”,之后统一写“Node”。
## open-source, open source
-When used as an adjective, hyphenate; for example: "This is open-source software." See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software).
+用作形容词时需加连字符,例如:“This is open-source software”。 See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software).
-Although it is common not to hyphenate this term, we are using the standard English rules for
-hyphenating a compound adjective.
+尽管这个词通常不加连字符,但我们遵循标准英语规则,对复合形容词进行连字符处理。
## request
-An HTTP request. A client submits an HTTP request message to a server, which returns a response. The request must use one of several [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) such as GET, POST, and so on.
+一次 HTTP 请求。 客户端向服务器发送一条 HTTP 请求消息,服务器随后返回响应。 The request must use one of several [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) such as GET, POST, and so on.
## response
-An HTTP response. A server returns an HTTP response message to the client. The response contains completion status information about the request and might also contain requested content in its message body.
+一个 HTTP 响应。 服务器向客户端返回一条 HTTP 响应消息。 该响应包含请求的完成状态信息,并且可能在消息体中包含所请求的内容。
## route
-Part of a URL that identifies a resource. For example, in `http://foo.com/products/id`, "/products/id" is the route.
+URL 中用于标识资源的部分。 例如,在 `http://foo.com/products/id` 中,“/products/id” 就是路由。
## router
diff --git a/src/content/pages/zh-cn/resources/index.mdx b/src/content/pages/zh-cn/resources/index.mdx
index 10db57860d..25264b7585 100644
--- a/src/content/pages/zh-cn/resources/index.mdx
+++ b/src/content/pages/zh-cn/resources/index.mdx
@@ -1,42 +1,36 @@
---
-title: Resources
-description: Explore Express.js resources including community, contributing guidelines, glossary, utilities, and middleware.
+title: 资源
+description: 探索Express.js资源,包括社区、贡献准则、词汇、 公共组件和中间件等。
---
import Card from '@components/primitives/Card/Card.astro';
import { CardList } from '@components/patterns';
-Find resources to help you learn, contribute, and connect with the Express.js ecosystem. Whether you're looking to get involved in the community, explore middleware, or understand key concepts, you'll find what you need here.
+查找资源,帮助你学习、参与贡献并融入 Express.js 生态系统。 无论你是想参与社区、探索中间件,还是了解核心概念,都能在这里找到所需内容。
-
+
-
+
diff --git a/src/content/pages/zh-cn/resources/middleware/body-parser.mdx b/src/content/pages/zh-cn/resources/middleware/body-parser.mdx
index 05dd86fc9e..6e253b5a45 100644
--- a/src/content/pages/zh-cn/resources/middleware/body-parser.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/body-parser.mdx
@@ -1,33 +1,27 @@
---
-title: body-parser middleware
-description: Node.js body parsing middleware
+title: body-parser 中间件
+description: Node.js 请求体解析中间件
---
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-Node.js body parsing middleware.
+Node.js 请求体解析中间件
-Parse incoming request bodies in a middleware before your handlers, available
-under the `req.body` property.
+在处理程序之前,通过中间件解析传入的请求体,解析结果可通过 `req.body` 属性访问。
-**Note** As `req.body`'s shape is based on user-controlled input, all
-properties and values in this object are untrusted and should be validated
-before trusting. For example, `req.body.foo.toString()` may fail in multiple
-ways, for example the `foo` property may not be there or may not be a string,
-and `toString` may not be a function and instead a string or other user input.
+**注意** 由于 `req.body` 的结构由用户可控的输入决定,因此该对象中的所有属性和值均不可信,在使用前应进行验证。 例如,`req.body.foo.toString()` 可能会以多种方式报错,例如 `foo` 属性可能不存在或不是字符串,且 `toString` 可能并非函数,而是字符串或其他用户输入。
-[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction).
+[了解 Node.js 中 HTTP 请求交互的构成](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction)
-_This does not handle multipart bodies_, due to their complex and typically
-large nature. For multipart bodies, you may be interested in the following
-modules:
+**此中间件不处理多部分(multipart)请求体**,因其结构复杂且通常体积较大。 对于多部分请求体,你可能需要以下模块:
- [busboy](https://www.npmjs.com/package/busboy#readme) and
[connect-busboy](https://www.npmjs.com/package/connect-busboy#readme)
@@ -36,23 +30,21 @@ modules:
- [formidable](https://www.npmjs.com/package/formidable#readme)
- [multer](https://www.npmjs.com/package/multer#readme)
-This module provides the following parsers:
+此模块提供以下解析器:
- [JSON body parser](#bodyparserjsonoptions)
- [Raw body parser](#bodyparserrawoptions)
- [Text body parser](#bodyparsertextoptions)
- [URL-encoded form body parser](#bodyparserurlencodedoptions)
-Other body parsers you might be interested in:
+你可能感兴趣的其他请求体解析器:
- [body](https://www.npmjs.com/package/body#readme)
- [co-body](https://www.npmjs.com/package/co-body#readme)
-## Installation
+## 安装
-```sh
-$ npm install body-parser
-```
+
## API
@@ -67,19 +59,13 @@ const raw = require('body-parser/raw');
const text = require('body-parser/text');
```
-The `bodyParser` object exposes various factories to create middlewares. All
-middlewares will populate the `req.body` property with the parsed body when
-the `Content-Type` request header matches the `type` option.
+`bodyParser` 对象提供了多种工厂方法来创建中间件。 所有中间件在请求头`Content-Type`与`type`选项匹配时,都会将解析后的请求体存入`req.body`属性。
-The various errors returned by this module are described in the
-[errors section](#errors).
+该模块抛出的各类错误在[错误章节](#errors)中有相关说明。
### bodyParser.json([options])
-Returns middleware that only parses `json` and only looks at requests where
-the `Content-Type` header matches the `type` option. This parser accepts any
-Unicode encoding of the body and supports automatic inflation of `gzip`,
-`br` (brotli) and `deflate` encodings.
+返回仅解析`json`且仅解析请求头`Content-Type`与`type`选项匹配的请求的中间件。 该解析器可识别请求体的任意Unicode编码,并自动解压`gzip`、`br`(brotli)与`deflate`编码的数据。
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`).
@@ -112,7 +98,7 @@ to `'100kb'`.
The `reviver` option is passed directly to `JSON.parse` as the second
argument. You can find more information on this argument
-[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strict
diff --git a/src/content/pages/zh-cn/resources/middleware/compression.mdx b/src/content/pages/zh-cn/resources/middleware/compression.mdx
index f896116e97..17719320ff 100644
--- a/src/content/pages/zh-cn/resources/middleware/compression.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js compression middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/cookie-parser.mdx b/src/content/pages/zh-cn/resources/middleware/cookie-parser.mdx
index 15d7e4b104..4e7eec2292 100644
--- a/src/content/pages/zh-cn/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Parse HTTP request cookies
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
@@ -90,7 +89,7 @@ The `secret` argument can be an array or string. If a string is provided, this
is used as the secret. If an array is provided, an attempt will be made to
unsign the cookie with each secret in order.
-## Example
+## 示例
```js
var express = require('express');
diff --git a/src/content/pages/zh-cn/resources/middleware/cookie-session.mdx b/src/content/pages/zh-cn/resources/middleware/cookie-session.mdx
index 96de6ea703..f818929b63 100644
--- a/src/content/pages/zh-cn/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie session middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/cors.mdx b/src/content/pages/zh-cn/resources/middleware/cors.mdx
index 3c33a19356..683153992f 100644
--- a/src/content/pages/zh-cn/resources/middleware/cors.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
@@ -33,15 +34,13 @@ CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://exp
- [License](#license)
- [Original Author](#original-author)
-## Installation
+## 安装
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Usage
diff --git a/src/content/pages/zh-cn/resources/middleware/errorhandler.mdx b/src/content/pages/zh-cn/resources/middleware/errorhandler.mdx
index 16839dc50a..7d784fd534 100644
--- a/src/content/pages/zh-cn/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Development-only error handler middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/index.mdx b/src/content/pages/zh-cn/resources/middleware/index.mdx
new file mode 100644
index 0000000000..df34d1fcb6
--- /dev/null
+++ b/src/content/pages/zh-cn/resources/middleware/index.mdx
@@ -0,0 +1,42 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | 描述 |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ 这些信息指的是第三方站点、产品或模块,它们不是由Expressjs团队维护的。 此处的罗列并不代表 Express
+ 项目团队的认可或推荐。
+
+
+| Middleware module | 描述 |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/zh-cn/resources/middleware/method-override.mdx b/src/content/pages/zh-cn/resources/middleware/method-override.mdx
index 0595f08d82..ed86353bd4 100644
--- a/src/content/pages/zh-cn/resources/middleware/method-override.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Override HTTP verbs
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/morgan.mdx b/src/content/pages/zh-cn/resources/middleware/morgan.mdx
index 4568ece4b5..59f33ca00b 100644
--- a/src/content/pages/zh-cn/resources/middleware/morgan.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: HTTP request logger middleware for Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -16,15 +17,13 @@ HTTP request logger middleware for node.js
> Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion.
-## Installation
+## 安装
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ If no format is given, then the default is `web`.
The HTTP version of the request.
-##### :method
+#####
The HTTP method of the request.
-##### :pid
+#####
The process ID of the Node.js process handling the request.
-##### :referrer
+#####
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
@@ -239,7 +238,7 @@ headers are written, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :status
+#####
The status code of the response.
@@ -255,7 +254,7 @@ has finished being written out to the connection, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :url
+#####
The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
diff --git a/src/content/pages/zh-cn/resources/middleware/multer.mdx b/src/content/pages/zh-cn/resources/middleware/multer.mdx
index 86f1ecd667..7ce51d950c 100644
--- a/src/content/pages/zh-cn/resources/middleware/multer.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware for handling multipart/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -34,11 +35,9 @@ This README is also available in other languages:
| [Việt Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese |
| [Türkçe](https://github.com/expressjs/multer/blob/main/doc/README-tr.md) | Turkish |
-## Installation
+## 安装
-```sh
-$ npm install multer
-```
+
## Usage
@@ -129,7 +128,7 @@ app.post('/stats', upload.single('uploaded_file'), function (req, res) {
Each file contains the following information:
-| Key | Description | Note |
+| Key | 描述 | Note |
| -------------- | --------------------------------------------- | --------------- |
| `fieldname` | Field name specified in the form | |
| `originalname` | Name of the file on the user's computer | |
@@ -152,7 +151,7 @@ renaming function can be customized according to your needs.
The following are the options that can be passed to Multer.
-| Key | Description |
+| Key | 描述 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dest` or `storage` | Where to store the files |
| `fileFilter` | Function to control which files are accepted |
@@ -284,15 +283,16 @@ An object specifying the size limits of the following optional properties. Multe
The following integer values are available:
-| Key | Description | Default |
-| --------------- | ----------------------------------------------------------------------- | --------- |
-| `fieldNameSize` | Max field name size | 100 bytes |
-| `fieldSize` | Max field value size (in bytes) | 1MB |
-| `fields` | Max number of non-file fields | Infinity |
-| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
-| `files` | For multipart forms, the max number of file fields | Infinity |
-| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
-| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| Key | 描述 | Default |
+| ------------------- | -------------------------------------------------------------------------- | --------- |
+| `fieldNameSize` | Max field name size | 100 bytes |
+| `fieldSize` | Max field value size (in bytes) | 1MB |
+| `fields` | Max number of non-file fields | Infinity |
+| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
+| `files` | For multipart forms, the max number of file fields | Infinity |
+| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
+| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Error handling
When encountering an error, Multer will delegate the error to Express. You can
diff --git a/src/content/pages/zh-cn/resources/middleware/response-time.mdx b/src/content/pages/zh-cn/resources/middleware/response-time.mdx
index 588ec099d7..a7cb9e15de 100644
--- a/src/content/pages/zh-cn/resources/middleware/response-time.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Response time for Node.js servers
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/serve-favicon.mdx b/src/content/pages/zh-cn/resources/middleware/serve-favicon.mdx
index 73a788eb06..887862b21a 100644
--- a/src/content/pages/zh-cn/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon serving middleware with caching
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/serve-index.mdx b/src/content/pages/zh-cn/resources/middleware/serve-index.mdx
index 912781757b..b49ab49eb3 100644
--- a/src/content/pages/zh-cn/resources/middleware/serve-index.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Serve directory listings
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/serve-static.mdx b/src/content/pages/zh-cn/resources/middleware/serve-static.mdx
index 38af6fc42f..d9becdd2f5 100644
--- a/src/content/pages/zh-cn/resources/middleware/serve-static.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Serve static files
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/session.mdx b/src/content/pages/zh-cn/resources/middleware/session.mdx
index 17e2353d92..611b322471 100644
--- a/src/content/pages/zh-cn/resources/middleware/session.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/session.mdx
@@ -5,22 +5,21 @@ description: Simple session middleware for Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-## Installation
+## 安装
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -124,9 +123,7 @@ Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](https://githu
attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not.
By default, the `Partitioned` attribute is not set.
-**Note** This is an attribute that has not yet been fully standardized, and may
-change in the future. This also means many clients may ignore this attribute until
-they understand it.
+**Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
More information about can be found in [the proposal](https://github.com/privacycg/CHIPS).
@@ -146,8 +143,10 @@ Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribut
More information about the different priority levels can be found in
[the specification][rfc-west-cookie-priority-00-4.1].
-**Note** This is an attribute that has not yet been fully standardized, and may change in the future.
-This also means many clients may ignore this attribute until they understand it.
+**Note** This is an attribute that has not yet been fully standardized, and may
+change in the future.
+This also means many clients may ignore this attribute until
+they understand it.
##### cookie.sameSite
@@ -165,7 +164,8 @@ More information about the different enforcement levels can be found in
[the specification][rfc-6265bis-03-4.1.2.7].
**Note** This is an attribute that has not yet been fully standardized, and may change in
-the future. This also means many clients may ignore this attribute until they understand it.
+the future. This also means many clients may ignore this attribute until
+they understand it.
**Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been
diff --git a/src/content/pages/zh-cn/resources/middleware/timeout.mdx b/src/content/pages/zh-cn/resources/middleware/timeout.mdx
index 4942e10a44..40fa16af93 100644
--- a/src/content/pages/zh-cn/resources/middleware/timeout.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Request timeout middleware for Connect/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Times out a request in the Connect/Express application framework.
@@ -20,9 +21,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/zh-cn/resources/middleware/vhost.mdx b/src/content/pages/zh-cn/resources/middleware/vhost.mdx
index 7d641e0a70..ecfb9c5daa 100644
--- a/src/content/pages/zh-cn/resources/middleware/vhost.mdx
+++ b/src/content/pages/zh-cn/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Virtual domain hosting
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-cn/resources/utils.md b/src/content/pages/zh-cn/resources/utils.md
index 739b352f3e..71b3537216 100644
--- a/src/content/pages/zh-cn/resources/utils.md
+++ b/src/content/pages/zh-cn/resources/utils.md
@@ -1,22 +1,21 @@
---
-title: Express utilities
-description: Discover utility modules related to Express.js and Node.js, including tools for cookies, CSRF protection, URL parsing, routing, and more to enhance your applications.
+title: Express 实用工具
+description: 探索与 Express.js 和 Node.js 相关的实用工具模块,包括 Cookie 处理、CSRF 防护、URL 解析、路由等工具,以增强你的应用程序功能。
---
-## Express utility functions
+## Express 实用函数
-The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules
-for utility functions that may be generally useful.
+[pillarjs](https://github.com/pillarjs) GitHub 组织包含许多实用函数模块,这些模块在一般情况下也可能非常有用。
-| Utility modules | Description |
-| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| [cookies](https://www.npmjs.com/package/cookies) | Get and set HTTP(S) cookies that can be signed to prevent tampering, using Keygrip. Can be used with the Node.js HTTP library or as Express middleware. |
-| [csrf](https://www.npmjs.com/package/csrf) | Contains the logic behind CSRF token creation and verification. Use this module to create custom CSRF middleware. |
-| [finalhandler](https://www.npmjs.com/package/finalhandler) | Function to invoke as the final step to respond to HTTP request. |
-| [parseurl](https://www.npmjs.com/package/parseurl) | Parse a URL with caching. |
-| [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) | Turn an Express-style path string such as \`\`/user/:name\` into a regular expression. |
-| [resolve-path](https://www.npmjs.com/package/resolve-path) | Resolves a relative path against a root path with validation. |
-| [router](https://www.npmjs.com/package/router) | Simple middleware-style router. |
-| [send](https://www.npmjs.com/package/send) | Library for streaming files as a HTTP response, with support for partial responses (ranges), conditional-GET negotiation, and granular events. |
+| 实用工具模块 | 描述 |
+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| [cookies](https://www.npmjs.com/package/cookies) | 获取和设置 HTTP(S) Cookie,可使用 Keygrip 进行签名以防止篡改。 可与 Node.js HTTP 库一起使用,或作为 Express 中间件使用。 |
+| [csrf](https://www.npmjs.com/package/csrf) | 包含 CSRF 令牌创建与验证的核心逻辑。 使用该模块创建自定义 CSRF 中间件。 |
+| [finalhandler](https://www.npmjs.com/package/finalhandler) | 用于作为 HTTP 请求响应最后一步调用的函数。 |
+| [parseurl](https://www.npmjs.com/package/parseurl) | 解析 URL,并支持缓存。 |
+| [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) | 将类似 `/user/:name` 的 Express 风格路径字符串转换为正则表达式。 |
+| [resolve-path](https://www.npmjs.com/package/resolve-path) | 将相对路径解析为基于根路径的绝对路径,并进行校验。 |
+| [router](https://www.npmjs.com/package/router) | 简单的中间件风格路由器。 |
+| [send](https://www.npmjs.com/package/send) | 用于将文件以 HTTP 响应流式传输的库,支持部分响应(Range)、条件 GET 协商以及细粒度事件。 |
For additional low-level HTTP-related modules, see [jshttp](https://github.com/jshttp).
diff --git a/src/content/pages/zh-cn/support.md b/src/content/pages/zh-cn/support.md
index d083fab364..d0e47896ee 100644
--- a/src/content/pages/zh-cn/support.md
+++ b/src/content/pages/zh-cn/support.md
@@ -1,23 +1,23 @@
---
-title: Version Support
-description: Find information about the support schedule for different Express.js versions, including which versions are currently maintained and end-of-life policies.
+title: 版本支持
+description: 了解不同 Express.js 版本的支持计划,包括当前仍受维护的版本以及生命周期终止政策。
---
-Only the latest version of any given major release line is supported.
+任何主版本分支仅支持其最新版本。
-Versions that are EOL (end-of-life) _may_ receive updates for critical security vulnerabilities, but the Express team offers no guarantee and does not plan to address or release fixes for any issues found.
+已终止生命周期(end-of-life)的版本**可能**会针对严重安全漏洞发布更新,但 Express 团队不作任何保证,也不计划修复或发布任何已发现问题的补丁。
-| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
-| ------------------- | ----------------------- | ------------------ | ---------------- |
-| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
-| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
-| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | March 2011 | July 2012 |
-| **v1.x** | 0.2.0 | December 2010 | March 2011 |
-| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
+| 主版本号 | 最低 Node.js 版本要求 | 支持开始日期 | 支持结束日期 |
+| -------------------------------------------------------------- | --------------------- | -------------- | ------------- |
+| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
+| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
+| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | March 2011 | July 2012 |
+| **v1.x** | 0.2.0 | December 2010 | March 2011 |
+| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
-## Commercial Support Options
+## 商业支持选项
-If you are unable to update to a supported version of Express, please contact one of our partners to receive security updates:
+如果你无法升级到受支持的 Express 版本,请联系以下合作伙伴获取安全更新:
- [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page)
diff --git a/src/content/pages/zh-tw/advanced/best-practice-performance.md b/src/content/pages/zh-tw/advanced/best-practice-performance.md
index 206df197d2..62980393ca 100644
--- a/src/content/pages/zh-tw/advanced/best-practice-performance.md
+++ b/src/content/pages/zh-tw/advanced/best-practice-performance.md
@@ -33,7 +33,7 @@ Here are some things you can do in your code to improve your application's perfo
Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:
-```js
+```cjs title="index.cjs"
const compression = require('compression');
const express = require('express');
const app = express();
@@ -41,6 +41,15 @@ const app = express();
app.use(compression());
```
+```mjs title="index.mjs"
+import compression from 'compression';
+import express from 'express';
+
+const app = express();
+
+app.use(compression());
+```
+
For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.
### Don't use synchronous functions
@@ -76,7 +85,7 @@ Before diving into these topics, you should have a basic understanding of Node/E
For more on the fundamentals of error handling, see:
-- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)
+- [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors)
#### Use try-catch
@@ -159,7 +168,7 @@ Setting NODE_ENV to "production" makes Express:
- Cache CSS files generated from CSS extensions.
- Generate less verbose error messages.
-[Tests indicate](https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
+[Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!
If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.
@@ -248,7 +257,7 @@ In a multi-core system, you can increase the performance of a Node app by many t

-IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](http://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
+IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.
In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().
@@ -288,7 +297,7 @@ For more information on clustering with PM2, see [Cluster Mode](https://pm2.keym
Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.
-Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/nginx-caching/)) to greatly improve the speed and performance of your app.
+Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app.
### Use a load balancer
@@ -302,4 +311,4 @@ With load balancing, you might have to ensure that requests that are associated
A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.
-Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://www.nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
+Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production.
diff --git a/src/content/pages/zh-tw/advanced/best-practice-security.mdx b/src/content/pages/zh-tw/advanced/best-practice-security.mdx
index cb960fcbbf..2b96bbceef 100644
--- a/src/content/pages/zh-tw/advanced/best-practice-security.mdx
+++ b/src/content/pages/zh-tw/advanced/best-practice-security.mdx
@@ -4,6 +4,7 @@ description: Discover crucial security best practices for Express apps in produc
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
The term _"production"_ refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the _"development"_ stage, you're still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as _production_ and _development_ environments, respectively.
@@ -18,21 +19,19 @@ Policies and Procedures.
Security best practices for Express applications in production include:
-- [Production Best Practices: Security](#production-best-practices-security)
- - [Overview](#overview)
- - [Don't use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
- - [Use TLS](#use-tls)
- - [Do not trust user input](#do-not-trust-user-input)
- - [Prevent open redirects](#prevent-open-redirects)
- - [Use Helmet](#use-helmet)
- - [Reduce fingerprinting](#reduce-fingerprinting)
- - [Use cookies securely](#use-cookies-securely)
- - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
- - [Set cookie security options](#set-cookie-security-options)
- - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
- - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
- - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
- - [Additional considerations](#additional-considerations)
+- [Don't use deprecated or vulnerable versions of Express](#dont-use-deprecated-or-vulnerable-versions-of-express)
+- [Use TLS](#use-tls)
+- [Do not trust user input](#do-not-trust-user-input)
+ - [Prevent open redirects](#prevent-open-redirects)
+- [Use Helmet](#use-helmet)
+- [Reduce fingerprinting](#reduce-fingerprinting)
+- [Use cookies securely](#use-cookies-securely)
+ - [Don't use the default session cookie name](#dont-use-the-default-session-cookie-name)
+ - [Set cookie security options](#set-cookie-security-options)
+- [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization)
+- [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure)
+ - [Avoid other known vulnerabilities](#avoid-other-known-vulnerabilities)
+- [Additional considerations](#additional-considerations)
## Don't use deprecated or vulnerable versions of Express
@@ -44,7 +43,7 @@ Also ensure you are not using any of the vulnerable Express versions listed on t
If your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem "hidden" in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
-You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).
+You may be familiar with Secure Socket Layer (SSL) encryption. In general, we recommend Nginx to handle TLS. In other words, if you were using SSL before, consider upgrading to TLS. In other words, if you were using SSL before, consider upgrading to TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations).
Also, a handy tool to get a free TLS certificate is [Let's Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).
@@ -99,13 +98,11 @@ Each header can be configured or disabled. To read more about it please go to [i
Install Helmet like any other module:
-```bash
-$ npm install helmet
-```
+
Then to use it in your code:
-```js
+```cjs title="index.cjs"
// ...
const helmet = require('helmet');
@@ -114,6 +111,16 @@ app.use(helmet());
// ...
```
+```mjs title="index.mjs"
+import helmet from 'helmet';
+
+// ...
+
+app.use(helmet());
+
+// ...
+```
+
## Reduce fingerprinting
It can help to provide an extra layer of security to reduce the ability of attackers to determine
@@ -177,7 +184,7 @@ Using the default session cookie name can open your app to attacks. The security
To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(
@@ -188,6 +195,18 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'express-session';
+
+app.set('trust proxy', 1); // trust first proxy
+app.use(
+ session({
+ secret: 's3Cur3',
+ name: 'sessionId',
+ })
+);
+```
+
### Set cookie security options
Set the following cookie options to enhance security:
@@ -200,7 +219,7 @@ Set the following cookie options to enhance security:
Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:
-```js
+```cjs title="index.cjs"
const session = require('cookie-session');
const express = require('express');
const app = express();
@@ -221,6 +240,28 @@ app.use(
);
```
+```mjs title="index.mjs"
+import session from 'cookie-session';
+import express from 'express';
+
+const app = express();
+
+const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
+app.use(
+ session({
+ name: 'session',
+ keys: ['key1', 'key2'],
+ cookie: {
+ secure: true,
+ httpOnly: true,
+ domain: 'example.com',
+ path: 'foo/bar',
+ expires: expiryDate,
+ },
+ })
+);
+```
+
## Prevent brute-force attacks against authorization
Make sure login endpoints are protected to make private data more secure.
@@ -259,7 +300,7 @@ $ snyk test
### Avoid other known vulnerabilities
-Keep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
+Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.
Finally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.
diff --git a/src/content/pages/zh-tw/advanced/healthcheck-graceful-shutdown.md b/src/content/pages/zh-tw/advanced/healthcheck-graceful-shutdown.md
index c060e58605..5d7b87ac11 100644
--- a/src/content/pages/zh-tw/advanced/healthcheck-graceful-shutdown.md
+++ b/src/content/pages/zh-tw/advanced/healthcheck-graceful-shutdown.md
@@ -22,7 +22,7 @@ process.on('SIGTERM', () => {
## Health checks
-A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):
+A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//):
- `liveness`, that determines when to restart a container.
- `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers.
diff --git a/src/content/pages/zh-tw/advanced/security-updates.mdx b/src/content/pages/zh-tw/advanced/security-updates.mdx
index 16d9d7191f..535f0aeb91 100644
--- a/src/content/pages/zh-tw/advanced/security-updates.mdx
+++ b/src/content/pages/zh-tw/advanced/security-updates.mdx
@@ -33,7 +33,7 @@ Policies and Procedures.
- The dependency `serve-static` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-cm22-4g7w-348p).
- The dependency `send` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-m6fv-jmcg-4jfg).
- The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j).
- - The dependency `body-parser` has been updated to addres a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url enconding activated.
+ - The dependency `body-parser` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url encoding activated.
- 4.19.0, 4.19.1
- Fixed open redirect vulnerability in `res.location` and `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc), [CVE-2024-29041](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-29041)).
- 4.17.3
diff --git a/src/content/pages/zh-tw/guide/database-integration.mdx b/src/content/pages/zh-tw/guide/database-integration.mdx
index b0855e4a2a..5c3aeab058 100644
--- a/src/content/pages/zh-tw/guide/database-integration.mdx
+++ b/src/content/pages/zh-tw/guide/database-integration.mdx
@@ -4,6 +4,7 @@ description: Discover how to integrate various databases with Express.js applica
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:
@@ -34,13 +35,11 @@ These database drivers are among many that are available. For other options, sea
### Installation
-```bash
-$ npm install cassandra-driver
-```
+
### Example
-```js
+```cjs title="index.cjs"
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'] });
@@ -50,19 +49,28 @@ client.execute('select key from system.local', (err, result) => {
});
```
+```mjs title="index.mjs"
+import cassandra from 'cassandra-driver';
+
+const client = new cassandra.Client({ contactPoints: ['localhost'] });
+
+client.execute('select key from system.local', (err, result) => {
+ if (err) throw err;
+ console.log(result.rows[0]);
+});
+```
+
## Couchbase
**Module**: [couchnode](https://github.com/couchbase/couchnode)
### Installation
-```bash
-$ npm install couchbase
-```
+
### Example
-```js
+```cjs title="index.cjs"
const couchbase = require('couchbase');
const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
@@ -87,19 +95,43 @@ bucket.query(query, [13], (err, result) => {
});
```
+```mjs title="index.mjs"
+import couchbase from 'couchbase';
+
+const bucket = new couchbase.Cluster('http://localhost:8091').openBucket('bucketName');
+
+// add a document to a bucket
+bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+
+// get all documents with shoe size 13
+const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1';
+const query = N1qlQuery.fromString(n1ql);
+bucket.query(query, [13], (err, result) => {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(result);
+ }
+});
+```
+
## CouchDB
**Module**: [nano](https://github.com/dscape/nano)
### Installation
-```bash
-$ npm install nano
-```
+
### Example
-```js
+```js title="index.js"
const nano = require('nano')('http://localhost:5984');
nano.db.create('books');
const books = nano.db.use('books');
@@ -129,13 +161,11 @@ books.list((err, body) => {
### Installation
-```bash
-$ npm install level levelup leveldown
-```
+
### Example
-```js
+```cjs title="index.cjs"
const levelup = require('levelup');
const db = levelup('./mydb');
@@ -150,19 +180,33 @@ db.put('name', 'LevelUP', (err) => {
});
```
+```mjs title="index.mjs"
+import levelup from 'levelup';
+
+const db = levelup('./mydb');
+
+db.put('name', 'LevelUP', (err) => {
+ if (err) return console.log('Ooops!', err);
+
+ db.get('name', (err, value) => {
+ if (err) return console.log('Ooops!', err);
+
+ console.log(`name=${value}`);
+ });
+});
+```
+
## MySQL
**Module**: [mysql](https://github.com/felixge/node-mysql/)
### Installation
-```bash
-$ npm install mysql
-```
+
### Example
-```js
+```cjs title="index.cjs"
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
@@ -182,19 +226,38 @@ connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
connection.end();
```
+```mjs title="index.mjs"
+import mysql from 'mysql';
+
+const connection = mysql.createConnection({
+ host: 'localhost',
+ user: 'dbuser',
+ password: 's3kreee7',
+ database: 'my_db',
+});
+
+connection.connect();
+
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+ if (err) throw err;
+
+ console.log('The solution is: ', rows[0].solution);
+});
+
+connection.end();
+```
+
## MongoDB
**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)
### Installation
-```bash
-$ npm install mongodb
-```
+
### Example (v2.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
@@ -212,7 +275,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {
### Example (v3.\*)
-```js
+```js title="index.js"
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {
@@ -238,13 +301,11 @@ If you want an object model driver for MongoDB, look at [Mongoose](https://githu
### Installation
-```bash
-$ npm install neo4j-driver
-```
+
### Example
-```js
+```cjs title="index.cjs"
const neo4j = require('neo4j-driver');
const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
@@ -262,6 +323,25 @@ session.readTransaction((tx) => {
});
```
+```mjs title="index.mjs"
+import neo4j from 'neo4j-driver';
+
+const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'));
+
+const session = driver.session();
+
+session.readTransaction((tx) => {
+ return tx
+ .run('MATCH (n) RETURN count(n) AS count')
+ .then((res) => {
+ console.log(res.records[0].get('count'));
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+});
+```
+
## Oracle
**Module**: [oracledb](https://github.com/oracle/node-oracledb)
@@ -270,13 +350,11 @@ session.readTransaction((tx) => {
NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).
-```bash
-$ npm install oracledb
-```
+
### Example
-```js
+```cjs title="index.cjs"
const oracledb = require('oracledb');
const config = {
user: '',
@@ -306,19 +384,48 @@ async function getEmployee(empId) {
getEmployee(101);
```
+```mjs title="index.mjs"
+import oracledb from 'oracledb';
+
+const config = {
+ user: '',
+ password: '',
+ connectString: 'localhost:1521/orcl',
+};
+
+async function getEmployee(empId) {
+ let conn;
+
+ try {
+ conn = await oracledb.getConnection(config);
+
+ const result = await conn.execute('select * from employees where employee_id = :id', [empId]);
+
+ console.log(result.rows[0]);
+ } catch (err) {
+ console.log('Ouch!', err);
+ } finally {
+ if (conn) {
+ // conn assignment worked, need to close
+ await conn.close();
+ }
+ }
+}
+
+getEmployee(101);
+```
+
## PostgreSQL
**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
### Installation
-```bash
-$ npm install pg-promise
-```
+
### Example
-```js
+```js title="index.js"
const pgp = require('pg-promise')(/* options */);
const db = pgp('postgres://username:password@host:port/database');
@@ -337,13 +444,11 @@ db.one('SELECT $1 AS value', 123)
### Installation
-```bash
-$ npm install redis
-```
+
### Example
-```js
+```cjs title="index.cjs"
const redis = require('redis');
const client = redis.createClient();
@@ -366,19 +471,41 @@ client.hkeys('hash key', (err, replies) => {
});
```
+```mjs title="index.mjs"
+import redis from 'redis';
+
+const client = redis.createClient();
+
+client.on('error', (err) => {
+ console.log(`Error ${err}`);
+});
+
+client.set('string key', 'string val', redis.print);
+client.hset('hash key', 'hashtest 1', 'some value', redis.print);
+client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
+
+client.hkeys('hash key', (err, replies) => {
+ console.log(`${replies.length} replies:`);
+
+ replies.forEach((reply, i) => {
+ console.log(` ${i}: ${reply}`);
+ });
+
+ client.quit();
+});
+```
+
## SQL Server
**Module**: [tedious](https://github.com/tediousjs/tedious)
### Installation
-```bash
-$ npm install tedious
-```
+
### Example
-```js
+```js title="index.js"
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
@@ -433,13 +560,11 @@ function executeStatement() {
### Installation
-```bash
-$ npm install sqlite3
-```
+
### Example
-```js
+```js title="index.js"
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
@@ -467,13 +592,11 @@ db.close();
### Installation
-```bash
-$ npm install elasticsearch
-```
+
### Example
-```js
+```cjs title="index.cjs"
const elasticsearch = require('elasticsearch');
const client = elasticsearch.Client({
host: 'localhost:9200',
@@ -501,3 +624,33 @@ client
}
);
```
+
+```mjs title="index.mjs"
+import elasticsearch from 'elasticsearch';
+
+const client = elasticsearch.Client({
+ host: 'localhost:9200',
+});
+
+client
+ .search({
+ index: 'books',
+ type: 'book',
+ body: {
+ query: {
+ multi_match: {
+ query: 'express js',
+ fields: ['title', 'description'],
+ },
+ },
+ },
+ })
+ .then(
+ (response) => {
+ const hits = response.hits.hits;
+ },
+ (error) => {
+ console.trace(error.message);
+ }
+ );
+```
diff --git a/src/content/pages/zh-tw/guide/migrating-4.mdx b/src/content/pages/zh-tw/guide/migrating-4.mdx
index c0e246a73c..acd2fb1488 100644
--- a/src/content/pages/zh-tw/guide/migrating-4.mdx
+++ b/src/content/pages/zh-tw/guide/migrating-4.mdx
@@ -4,39 +4,23 @@ description: A guide to migrating your Express.js applications from version 3 to
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 4 is a breaking change from Express 3. That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies.
This article covers:
-
+- [Changes in Express 4](#changes-in-express-4).
+- [An example](#example-app-migration) of migrating an Express 3 app to Express 4.
+- [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator).
## Changes in Express 4
There are several significant changes in Express 4:
-
+- [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
+- [Changes to the routing system.](#the-routing-system)
+- [Various other changes.](#other-changes)
See also:
@@ -252,7 +236,7 @@ it, defines some routes, and mounts it on a path on the main app.
For example, create a router file named `birds.js` in the app directory,
with the following content:
-```js
+```cjs title="birds.cjs"
var express = require('express');
var router = express.Router();
@@ -273,9 +257,31 @@ router.get('/about', (req, res) => {
module.exports = router;
```
+```mjs title="birds.mjs"
+import express from 'express';
+
+const router = express.Router();
+
+// middleware specific to this router
+router.use((req, res, next) => {
+ console.log('Time: ', Date.now());
+ next();
+});
+// define the home page route
+router.get('/', (req, res) => {
+ res.send('Birds home page');
+});
+// define the about route
+router.get('/about', (req, res) => {
+ res.send('About birds');
+});
+
+export default router;
+```
+
Then, load the router module in the app:
-```js
+```cjs title="index.cjs"
var birds = require('./birds');
// ...
@@ -283,6 +289,14 @@ var birds = require('./birds');
app.use('/birds', birds);
```
+```mjs title="index.mjs"
+import birds from './birds';
+
+// ...
+
+app.use('/birds', birds);
+```
+
The app will now be able to handle requests to the `/birds` and
`/birds/about` paths, and will call the `timeLog`
middleware that is specific to the route.
@@ -375,7 +389,7 @@ The files of interest are `app.js` and `package.json`.
Consider an Express v.3 application with the following `app.js` file:
-```js
+```cjs title="index.cjs"
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
@@ -409,6 +423,40 @@ http.createServer(app).listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import http from 'http';
+import path from 'path';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(express.favicon());
+app.use(express.logger('dev'));
+app.use(express.methodOverride());
+app.use(express.session({ secret: 'your secret here' }));
+app.use(express.bodyParser());
+app.use(app.router);
+app.use(express.static(path.join(__dirname, 'public')));
+
+// development only
+if (app.get('env') === 'development') {
+ app.use(express.errorHandler());
+}
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+http.createServer(app).listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
#### `package.json`
The accompanying version 3 `package.json` file might look
@@ -435,9 +483,7 @@ Begin the migration process by installing the required middleware for the
Express 4 app and updating Express and Pug to their respective latest
version with the following command:
-```bash
-$ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save
-```
+
Make the following changes to `app.js`:
@@ -487,7 +533,7 @@ Running the above `npm` command will update `package.json` as follows:
Then, remove invalid code, load the required middleware, and make other
changes as necessary. The `app.js` file will look like this:
-```js
+```cjs title="index.cjs"
var http = require('http');
var express = require('express');
var routes = require('./routes');
@@ -537,6 +583,55 @@ server.listen(app.get('port'), () => {
});
```
+```mjs title="index.mjs"
+import http from 'http';
+import express from 'express';
+import routes from './routes';
+import user from './routes/user';
+import path from 'path';
+import favicon from 'serve-favicon';
+import logger from 'morgan';
+import methodOverride from 'method-override';
+import session from 'express-session';
+import bodyParser from 'body-parser';
+import multer from 'multer';
+import errorHandler from 'errorhandler';
+
+const app = express();
+
+// all environments
+app.set('port', process.env.PORT || 3000);
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
+app.use(logger('dev'));
+app.use(methodOverride());
+app.use(
+ session({
+ resave: true,
+ saveUninitialized: true,
+ secret: 'uwotm8',
+ })
+);
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(multer());
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.get('/', routes.index);
+app.get('/users', user.list);
+
+// error handling middleware should be loaded after the loading the routes
+if (app.get('env') === 'development') {
+ app.use(errorHandler());
+}
+
+const server = http.createServer(app);
+server.listen(app.get('port'), () => {
+ console.log('Express server listening on port ' + app.get('port'));
+});
+```
+
Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way:
@@ -572,18 +667,14 @@ the Express 3 app generator and then install the new
If you already have the Express 3 app generator installed on your system,
you must uninstall it:
-```bash
-$ npm uninstall -g express
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
Now install the new generator:
-```bash
-$ npm install -g express-generator
-```
+
Depending on how your file and directory privileges are configured,
you might need to run this command with `sudo`.
diff --git a/src/content/pages/zh-tw/guide/migrating-5.mdx b/src/content/pages/zh-tw/guide/migrating-5.mdx
index 3dfdd8d0ff..ad3a0d9a31 100644
--- a/src/content/pages/zh-tw/guide/migrating-5.mdx
+++ b/src/content/pages/zh-tw/guide/migrating-5.mdx
@@ -4,6 +4,7 @@ description: A comprehensive guide to migrating your Express.js applications fro
---
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Express 5 is not very different from Express 4; although it maintains the same basic API, there are still changes that break compatibility with the previous version. Therefore, an application built with Express 4 might not work if you update it to use Express 5.
@@ -11,9 +12,7 @@ Express 5 is not very different from Express 4; although it maintains the same b
To install this version, you need to have a **Node.js version 18 or higher**. Then, execute the following command in your application directory:
-```sh
-npm install "express@5"
-```
+
You can then run your automated tests to see what fails, and fix problems according to the updates listed below. 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.
@@ -23,15 +22,11 @@ To help you migrate your express server, we have created a set of codemods that
Run the following command for run all the codemods available:
-```sh
-npx codemod@latest @expressjs/v5-migration-recipe
-```
+
If you want to run a specific codemod, you can run the following command:
-```sh
-npx codemod@latest @expressjs/name-of-the-codemod
-```
+
You can find the list of available codemods [here](https://codemod.link/express).
@@ -49,9 +44,7 @@ Initially, `del` was used instead of `delete`, because `delete` is a reserved ke
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/route-del-to-delete
-```
+
Or you can update your code manually:
@@ -80,9 +73,7 @@ The following method names have been pluralized. In Express 4, using the old met
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/pluralize-method-names
-```
+
Or you can update your code manually:
@@ -103,7 +94,7 @@ Or you can update your code manually:
A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon.
-This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api#app.param), as it makes no mention of the leading colon.
+This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon.
### req.param(name)
@@ -113,9 +104,7 @@ This potentially confusing and dangerous method of retrieving form data has been
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/explicit-request-params
-```
+
Or you can update your code manually:
@@ -140,9 +129,7 @@ Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -161,9 +148,7 @@ Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, se
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -182,16 +167,19 @@ Express 5 no longer supports the signature `res.redirect(url, status)`. Instead,
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/redirect-arg-order
-```
+
Or you can update your code manually:
```diff
app.get('/user', (req, res) => {
-- res.redirect('/users', 301);
-+ res.redirect(301, '/users');
+- res.redirect('/users', 302);
++ res.redirect(302, '/users');
+ });
+
+ // A redirect that relies on the default 302 status is unaffected
+ app.get('/admin', (req, res) => {
+ res.redirect('/dashboard');
});
```
@@ -203,9 +191,7 @@ Express 5 no longer supports the magic string `back` in the `res.redirect()` and
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/back-redirect-deprecated
-```
+
Or you can update your code manually:
@@ -224,9 +210,7 @@ Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -246,9 +230,7 @@ If you need to send a number by using the `res.send()` function, quote the numbe
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/status-send-order
-```
+
Or you can update your code manually:
@@ -267,9 +249,7 @@ The `res.sendfile()` function has been replaced by a camel-cased version `res.se
You can automatically update your code by running the following command:
-```sh
-npx codemod@latest @expressjs/camelcase-sendfile
-```
+
Or you can update your code manually:
@@ -284,6 +264,10 @@ Or you can update your code manually:
The `hidden` and `from` options for `res.sendFile()` are no longer supported. Use `dotfiles` and `root` instead.
+The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in.
+
+This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected.
+
#### How to update
```diff
@@ -293,12 +277,30 @@ The `hidden` and `from` options for `res.sendFile()` are no longer supported. Us
});
```
+If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path:
+
+```diff
+ app.get('/build', (req, res) => {
+- res.sendFile('/var/www/app/.cache/index.html');
++ res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' });
++ // or: res.sendFile('index.html', { root: '/var/www/app/.cache' });
+ });
+```
+
### express.static() options
The `hidden` and `from` options for `express.static()` are no longer supported. Use `dotfiles` and `root` instead. Note that `from` was never documented in the API but was accepted as an alias for `root`. The default value of `dotfiles` is now `"ignore"`.
+The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected.
+
#### How to update
+You can automatically update your code by running the following command:
+
+
+
+Or you can update your code manually:
+
```diff
const express = require('express');
const app = express();
@@ -307,6 +309,13 @@ The `hidden` and `from` options for `express.static()` are no longer supported.
+app.use(express.static('public', { dotfiles: 'allow' }));
```
+If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option:
+
+```diff
+-app.use(express.static('public'));
++app.use(express.static('public', { dotfiles: 'allow' }));
+```
+
### 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.
@@ -449,6 +458,25 @@ Serve specific dot-directories explicitly using the `dotfiles: "allow"` option.
app.use(express.static('public'));
```
+### router.param() with an array of names
+
+`router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.)
+
+#### How to update
+
+Register each parameter name with its own `router.param()` call:
+
+```diff
+-router.param(['id', 'page'], (req, res, next, value) => {
+- // ...
+-});
++const loadParam = (req, res, next, value) => {
++ // ...
++};
++router.param('id', loadParam);
++router.param('page', loadParam);
+```
+
### 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.
diff --git a/src/content/pages/zh-tw/resources/glossary.mdx b/src/content/pages/zh-tw/resources/glossary.mdx
index 722d87bf44..5f7fff790f 100644
--- a/src/content/pages/zh-tw/resources/glossary.mdx
+++ b/src/content/pages/zh-tw/resources/glossary.mdx
@@ -27,7 +27,7 @@ A function that is invoked by the Express routing layer before the final request
- `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware.
- `app.use(mw)` is called _adding the middleware to the global processing stack_.
-- `app.get('/foo', mw, function (req, res) { ... })` is called _adding the middleware to the "GET /foo" processing stack_.
+- `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_.
## Node.js
diff --git a/src/content/pages/zh-tw/resources/middleware/body-parser.mdx b/src/content/pages/zh-tw/resources/middleware/body-parser.mdx
index 05dd86fc9e..82c968475b 100644
--- a/src/content/pages/zh-tw/resources/middleware/body-parser.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/body-parser.mdx
@@ -5,9 +5,10 @@ description: Node.js body parsing middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -50,9 +51,7 @@ Other body parsers you might be interested in:
## Installation
-```sh
-$ npm install body-parser
-```
+
## API
@@ -112,7 +111,7 @@ to `'100kb'`.
The `reviver` option is passed directly to `JSON.parse` as the second
argument. You can find more information on this argument
-[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strict
diff --git a/src/content/pages/zh-tw/resources/middleware/compression.mdx b/src/content/pages/zh-tw/resources/middleware/compression.mdx
index f896116e97..17719320ff 100644
--- a/src/content/pages/zh-tw/resources/middleware/compression.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/compression.mdx
@@ -5,6 +5,7 @@ description: Node.js compression middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/cookie-parser.mdx b/src/content/pages/zh-tw/resources/middleware/cookie-parser.mdx
index 15d7e4b104..0ccd0bb0ba 100644
--- a/src/content/pages/zh-tw/resources/middleware/cookie-parser.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/cookie-parser.mdx
@@ -5,6 +5,7 @@ description: Parse HTTP request cookies
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/cookie-session.mdx b/src/content/pages/zh-tw/resources/middleware/cookie-session.mdx
index 96de6ea703..f818929b63 100644
--- a/src/content/pages/zh-tw/resources/middleware/cookie-session.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/cookie-session.mdx
@@ -5,6 +5,7 @@ description: Cookie session middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/cors.mdx b/src/content/pages/zh-tw/resources/middleware/cors.mdx
index 3c33a19356..c70429abf1 100644
--- a/src/content/pages/zh-tw/resources/middleware/cors.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/cors.mdx
@@ -5,6 +5,7 @@ description: Node.js CORS middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
-CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
+CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.
@@ -39,9 +40,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally):
-```sh
-$ npm install cors
-```
+
## Usage
diff --git a/src/content/pages/zh-tw/resources/middleware/errorhandler.mdx b/src/content/pages/zh-tw/resources/middleware/errorhandler.mdx
index 16839dc50a..7d784fd534 100644
--- a/src/content/pages/zh-tw/resources/middleware/errorhandler.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/errorhandler.mdx
@@ -5,6 +5,7 @@ description: Development-only error handler middleware
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/index.mdx b/src/content/pages/zh-tw/resources/middleware/index.mdx
new file mode 100644
index 0000000000..d335cab822
--- /dev/null
+++ b/src/content/pages/zh-tw/resources/middleware/index.mdx
@@ -0,0 +1,43 @@
+---
+title: Express middleware
+description: Explore a list of Express.js middleware modules maintained by the Express team and the community, including built-in middleware and popular third-party modules.
+---
+
+import Alert from '@components/primitives/Alert/Alert.astro';
+
+The Express middleware modules listed here are maintained by the
+[Expressjs team](https://github.com/orgs/expressjs/people).
+
+| Middleware module | Description |
+| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. |
+| [compression](/resources/middleware/compression) | Compress HTTP responses. |
+| [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). |
+| [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. |
+| [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. |
+| [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. |
+| [method-override](/resources/middleware/method-override) | Override HTTP methods using header. |
+| [morgan](/resources/middleware/morgan) | HTTP request logger. |
+| [multer](/resources/middleware/multer) | Handle multi-part form data. |
+| [response-time](/resources/middleware/response-time) | Record HTTP response time. |
+| [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. |
+| [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. |
+| [serve-static](/resources/middleware/serve-static) | Serve static files. |
+| [session](/resources/middleware/session) | Establish server-based sessions (development only). |
+| [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. |
+| [vhost](/resources/middleware/vhost) | Create virtual domains. |
+
+## Additional middleware modules
+
+These are some additional popular middleware modules.
+
+
+ This information refers to third-party sites, products, or modules that are not maintained by the
+ Expressjs team. Listing here does not constitute an endorsement or recommendation from the
+ Expressjs project team.
+
+
+| Middleware module | Description |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. |
+| [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. |
diff --git a/src/content/pages/zh-tw/resources/middleware/method-override.mdx b/src/content/pages/zh-tw/resources/middleware/method-override.mdx
index 0595f08d82..ed86353bd4 100644
--- a/src/content/pages/zh-tw/resources/middleware/method-override.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/method-override.mdx
@@ -5,6 +5,7 @@ description: Override HTTP verbs
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/morgan.mdx b/src/content/pages/zh-tw/resources/middleware/morgan.mdx
index 4568ece4b5..f63f59d98e 100644
--- a/src/content/pages/zh-tw/resources/middleware/morgan.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/morgan.mdx
@@ -5,9 +5,10 @@ description: HTTP request logger middleware for Node.js
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -22,9 +23,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install morgan
-```
+
## API
@@ -201,15 +200,15 @@ If no format is given, then the default is `web`.
The HTTP version of the request.
-##### :method
+#####
The HTTP method of the request.
-##### :pid
+#####
The process ID of the Node.js process handling the request.
-##### :referrer
+#####
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
@@ -239,7 +238,7 @@ headers are written, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :status
+#####
The status code of the response.
@@ -255,7 +254,7 @@ has finished being written out to the connection, in milliseconds.
The `digits` argument is a number that specifies the number of digits to
include on the number, defaulting to `3`, which provides microsecond precision.
-##### :url
+#####
The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
diff --git a/src/content/pages/zh-tw/resources/middleware/multer.mdx b/src/content/pages/zh-tw/resources/middleware/multer.mdx
index 86f1ecd667..0558a87857 100644
--- a/src/content/pages/zh-tw/resources/middleware/multer.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/multer.mdx
@@ -5,9 +5,10 @@ description: Middleware for handling multipart/form-data
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
@@ -36,9 +37,7 @@ This README is also available in other languages:
## Installation
-```sh
-$ npm install multer
-```
+
## Usage
@@ -284,15 +283,16 @@ An object specifying the size limits of the following optional properties. Multe
The following integer values are available:
-| Key | Description | Default |
-| --------------- | ----------------------------------------------------------------------- | --------- |
-| `fieldNameSize` | Max field name size | 100 bytes |
-| `fieldSize` | Max field value size (in bytes) | 1MB |
-| `fields` | Max number of non-file fields | Infinity |
-| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
-| `files` | For multipart forms, the max number of file fields | Infinity |
-| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
-| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| Key | Description | Default |
+| ------------------- | -------------------------------------------------------------------------- | --------- |
+| `fieldNameSize` | Max field name size | 100 bytes |
+| `fieldSize` | Max field value size (in bytes) | 1MB |
+| `fields` | Max number of non-file fields | Infinity |
+| `fileSize` | For multipart forms, the max file size (in bytes) | Infinity |
+| `files` | For multipart forms, the max number of file fields | Infinity |
+| `parts` | For multipart forms, the max number of parts (fields + files) | Infinity |
+| `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
+| `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
@@ -317,6 +317,15 @@ function fileFilter(req, file, cb) {
}
```
+## Security
+
+Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications:
+
+- `fileSize` -- set to the maximum expected file size for your use case
+- `files` -- set to the maximum number of files per request
+- `fields` -- set to the maximum number of text fields per request
+- `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`)
+
## Error handling
When encountering an error, Multer will delegate the error to Express. You can
diff --git a/src/content/pages/zh-tw/resources/middleware/response-time.mdx b/src/content/pages/zh-tw/resources/middleware/response-time.mdx
index 588ec099d7..4bda25039b 100644
--- a/src/content/pages/zh-tw/resources/middleware/response-time.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/response-time.mdx
@@ -5,6 +5,7 @@ description: Response time for Node.js servers
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/serve-favicon.mdx b/src/content/pages/zh-tw/resources/middleware/serve-favicon.mdx
index 73a788eb06..887862b21a 100644
--- a/src/content/pages/zh-tw/resources/middleware/serve-favicon.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/serve-favicon.mdx
@@ -5,6 +5,7 @@ description: Favicon serving middleware with caching
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/serve-index.mdx b/src/content/pages/zh-tw/resources/middleware/serve-index.mdx
index 912781757b..b49ab49eb3 100644
--- a/src/content/pages/zh-tw/resources/middleware/serve-index.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/serve-index.mdx
@@ -5,6 +5,7 @@ description: Serve directory listings
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/serve-static.mdx b/src/content/pages/zh-tw/resources/middleware/serve-static.mdx
index 38af6fc42f..d9becdd2f5 100644
--- a/src/content/pages/zh-tw/resources/middleware/serve-static.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/serve-static.mdx
@@ -5,6 +5,7 @@ description: Serve static files
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/session.mdx b/src/content/pages/zh-tw/resources/middleware/session.mdx
index 17e2353d92..8bc08bda0e 100644
--- a/src/content/pages/zh-tw/resources/middleware/session.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/session.mdx
@@ -5,11 +5,12 @@ description: Simple session middleware for Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## Installation
@@ -18,9 +19,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install express-session
-```
+
## API
@@ -124,9 +123,7 @@ Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](https://githu
attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not.
By default, the `Partitioned` attribute is not set.
-**Note** This is an attribute that has not yet been fully standardized, and may
-change in the future. This also means many clients may ignore this attribute until
-they understand it.
+**Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
More information about can be found in [the proposal](https://github.com/privacycg/CHIPS).
@@ -146,8 +143,10 @@ Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribut
More information about the different priority levels can be found in
[the specification][rfc-west-cookie-priority-00-4.1].
-**Note** This is an attribute that has not yet been fully standardized, and may change in the future.
-This also means many clients may ignore this attribute until they understand it.
+**Note** This is an attribute that has not yet been fully standardized, and may
+change in the future.
+This also means many clients may ignore this attribute until
+they understand it.
##### cookie.sameSite
@@ -165,7 +164,8 @@ More information about the different enforcement levels can be found in
[the specification][rfc-6265bis-03-4.1.2.7].
**Note** This is an attribute that has not yet been fully standardized, and may change in
-the future. This also means many clients may ignore this attribute until they understand it.
+the future. This also means many clients may ignore this attribute until
+they understand it.
**Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01)
that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been
diff --git a/src/content/pages/zh-tw/resources/middleware/timeout.mdx b/src/content/pages/zh-tw/resources/middleware/timeout.mdx
index 4942e10a44..40fa16af93 100644
--- a/src/content/pages/zh-tw/resources/middleware/timeout.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/timeout.mdx
@@ -5,11 +5,12 @@ description: Request timeout middleware for Connect/Express
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
Times out a request in the Connect/Express application framework.
@@ -20,9 +21,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
-```sh
-$ npm install connect-timeout
-```
+
## API
diff --git a/src/content/pages/zh-tw/resources/middleware/vhost.mdx b/src/content/pages/zh-tw/resources/middleware/vhost.mdx
index 7d641e0a70..ecfb9c5daa 100644
--- a/src/content/pages/zh-tw/resources/middleware/vhost.mdx
+++ b/src/content/pages/zh-tw/resources/middleware/vhost.mdx
@@ -5,6 +5,7 @@ description: Virtual domain hosting
import MiddlewareInfo from '@components/patterns/MiddlewareInfo/MiddlewareInfo.astro';
import Alert from '@components/primitives/Alert/Alert.astro';
+import PackageManagerCommand from '@components/patterns/PackageManagerCommand/PackageManagerCommand.astro';
## API
diff --git a/src/content/pages/zh-tw/support.md b/src/content/pages/zh-tw/support.md
index d083fab364..8a814d9c44 100644
--- a/src/content/pages/zh-tw/support.md
+++ b/src/content/pages/zh-tw/support.md
@@ -7,14 +7,14 @@ Only the latest version of any given major release line is supported.
Versions that are EOL (end-of-life) _may_ receive updates for critical security vulnerabilities, but the Express team offers no guarantee and does not plan to address or release fixes for any issues found.
-| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
-| ------------------- | ----------------------- | ------------------ | ---------------- |
-| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
-| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
-| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
-| [**v2.x**](/2x/) | 0.4.1 | March 2011 | July 2012 |
-| **v1.x** | 0.2.0 | December 2010 | March 2011 |
-| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
+| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
+| -------------------------------------------------------------- | ----------------------- | ------------------ | ---------------- |
+| [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** |
+| [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** |
+| [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 |
+| [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | March 2011 | July 2012 |
+| **v1.x** | 0.2.0 | December 2010 | March 2011 |
+| **v0.14.x** | 0.1.98 | December 2010 | December 2010 |
## Commercial Support Options
diff --git a/src/i18n/ui/zh-cn.json b/src/i18n/ui/zh-cn.json
index 85830318f2..ce9b543f48 100644
--- a/src/i18n/ui/zh-cn.json
+++ b/src/i18n/ui/zh-cn.json
@@ -1,188 +1,188 @@
{
"home": {
- "welcome": "Welcome",
- "workInProgress": "This is a work-in-progress homepage.",
+ "welcome": "欢迎",
+ "workInProgress": "这是一个正在开发中的工作首页。",
"reviewDesignSystem": {
- "prefix": "Review the",
- "link": "Design System Foundations",
- "suffix": "demo page to explore all tokens, primitives, and patterns."
+ "prefix": "阅读一下",
+ "link": "设计系统基础",
+ "suffix": "用于探索所有令牌、原始和模式的演示页面。"
}
},
"search": {
- "placeholder": "Start typing...",
- "ariaLabel": "Start typing to search"
+ "placeholder": "开始输入……",
+ "ariaLabel": "开始输入以搜索"
},
"theme": {
- "toggle": "Toggle theme",
- "switchToLight": "Switch to light mode",
- "switchToDark": "Switch to dark mode"
+ "toggle": "切换主题",
+ "switchToLight": "切换到浅色主题",
+ "switchToDark": "切换到暗黑模式"
},
"version": {
- "selectLabel": "Select API version"
+ "selectLabel": "选择 API 版本"
},
"language": {
- "selectLabel": "Select language"
+ "selectLabel": "选择语言"
},
"nav": {
- "mainMenu": "Main menu",
- "toggleMenu": "Toggle menu",
- "home": "home",
- "breadcrumb": "Breadcrumb",
- "mainNavigation": "Main navigation",
- "selectVersion": "Select documentation version"
+ "mainMenu": "主菜单",
+ "toggleMenu": "切换菜单",
+ "home": "主页",
+ "breadcrumb": "面包屑",
+ "mainNavigation": "主导航",
+ "selectVersion": "选择文档版本"
},
"menu": {
"main": {
- "docs": "Docs",
+ "docs": "文档",
"api": "API",
- "resources": "Resources",
- "blog": "Blog",
- "support": "Support"
+ "resources": "资源",
+ "blog": "博客",
+ "support": "支持"
},
"sections": {
- "gettingStarted": "Getting started",
- "guide": "Guide",
- "migration": "Migration guides",
- "advanced": "Advanced topics",
- "express": "express()",
- "application": "Application",
- "request": "Request",
- "response": "Response",
- "router": "Router",
- "middleware": "Middleware"
+ "gettingStarted": "快速开始",
+ "guide": "指南",
+ "migration": "迁移指南",
+ "advanced": "高级主题",
+ "express": "express() ",
+ "application": "应用程序",
+ "request": "请求",
+ "response": "响应",
+ "router": "路由",
+ "middleware": "中间件"
},
"items": {
- "installing": "Installing",
- "helloWorld": "Hello world",
- "expressGenerator": "Express generator",
- "basicRouting": "Basic routing",
- "staticFiles": "Serving static files",
- "examples": "Examples",
- "faq": "FAQ",
- "routing": "Routing",
- "writingMiddleware": "Writing middleware",
- "usingMiddleware": "Using middleware",
- "usingTemplateEngines": "Using template engines",
- "errorHandling": "Error handling",
- "debugging": "Debugging",
- "behindProxies": "Behind proxies",
- "databaseIntegration": "Database integration",
- "overridingExpressApi": "Overriding the Express API",
- "migratingTo4": "Moving to Express 4",
- "migratingTo5": "Moving to Express 5",
- "buildingTemplateEngines": "Building template engines",
- "bestPracticePerformance": "Performance best practices",
- "bestPracticeSecurity": "Security best practices",
- "healthcheckGracefulShutdown": "Health checks & graceful shutdown",
- "securityUpdates": "Security updates",
- "overview": "Overview",
- "properties": "Properties",
- "methods": "Methods",
- "events": "Events",
- "types": "Built-in",
- "community": "Community",
- "glossary": "Glossary",
- "contributing": "Contributing",
- "utils": "Utilities",
- "changelog": "Changelog",
- "middleware": "Middleware"
+ "installing": "安装",
+ "helloWorld": "Hello World",
+ "expressGenerator": "Express 生成器",
+ "basicRouting": "基本路由",
+ "staticFiles": "提供静态文件",
+ "examples": "示例",
+ "faq": "FAQ 常见问题解答",
+ "routing": "路由",
+ "writingMiddleware": "编写中间件",
+ "usingMiddleware": "使用中间件",
+ "usingTemplateEngines": "使用模板引擎",
+ "errorHandling": "错误处理",
+ "debugging": "调试",
+ "behindProxies": "代理后的Express",
+ "databaseIntegration": "数据库集成",
+ "overridingExpressApi": "覆盖 Express API",
+ "migratingTo4": "移动到 Express 4",
+ "migratingTo5": "移动到 Express 5",
+ "buildingTemplateEngines": "构建模板引擎",
+ "bestPracticePerformance": "性能最佳实践",
+ "bestPracticeSecurity": "安全最佳实践",
+ "healthcheckGracefulShutdown": "健康检查与优雅关闭",
+ "securityUpdates": "安全更新",
+ "overview": "概览",
+ "properties": "属性",
+ "methods": "方法",
+ "events": "事件",
+ "types": "内置",
+ "community": "社区",
+ "glossary": "专业术语词汇表",
+ "contributing": "参与贡献",
+ "utils": "实用工具",
+ "changelog": "更改日志",
+ "middleware": "Middleware(中间件)"
},
"aria": {
- "docs": "Documentation",
- "api": "API Reference",
- "resources": "Resources",
- "blog": "Blog",
- "support": "Support",
- "installing": "Installing Express",
- "helloWorld": "Hello world example",
- "expressGenerator": "Express generator",
- "routing": "Routing guide",
- "writingMiddleware": "Writing middleware guide",
- "usingMiddleware": "Using middleware guide",
- "usingTemplateEngines": "Using template engines guide",
- "errorHandling": "Error handling guide",
- "debugging": "Debugging Express",
- "behindProxies": "Express behind proxies",
- "databaseIntegration": "Database integration guide",
- "overridingExpressApi": "Overriding the Express API guide",
- "application": "Application overview",
- "request": "Request overview",
- "response": "Response overview",
- "router": "Router overview",
- "middleware": "Middleware resources",
- "community": "Community resources",
- "glossary": "Glossary of terms",
- "contributing": "Contributing guide",
- "utils": "Utilities",
- "changelog": "Express changelog"
+ "docs": "文档",
+ "api": "API 参考资料",
+ "resources": "资源",
+ "blog": "博客",
+ "support": "支持",
+ "installing": "安装 Express",
+ "helloWorld": "Hello world 示例",
+ "expressGenerator": "Express 生成器",
+ "routing": "路由指南",
+ "writingMiddleware": "编写中间件指南",
+ "usingMiddleware": "使用中间件指南",
+ "usingTemplateEngines": "使用模板引擎指南",
+ "errorHandling": "错误处理指南",
+ "debugging": "调试 Express",
+ "behindProxies": "代理服务器后的 Express",
+ "databaseIntegration": "数据库集成指南",
+ "overridingExpressApi": "扩展与覆盖 Express API 指南",
+ "application": "应用程序概述",
+ "request": "请求概览",
+ "response": "响应概述",
+ "router": "路由概述",
+ "middleware": "中间件资源",
+ "community": "社区资源",
+ "glossary": "术语表",
+ "contributing": "贡献指南",
+ "utils": "实用工具",
+ "changelog": "Express 更新日志"
}
},
"doc": {
- "previousPage": "Previous",
- "nextPage": "Next",
- "pageNavigation": "Page navigation"
+ "previousPage": "上一页",
+ "nextPage": "下一页",
+ "pageNavigation": "页面导航"
},
"page": {
- "editOnGitHub": "Edit on GitHub",
- "translateThis": "Translate this page"
+ "editOnGitHub": "在 GitHub 上编辑",
+ "translateThis": "翻译此页面"
},
"announcement": {
- "readMore": "Read more",
- "checkLatestBlog": "Check out our latest blog"
+ "readMore": "阅读更多",
+ "checkLatestBlog": "查看我们最新的博客"
},
"post": {
- "share": "Share",
- "shareOnX": "Share on X",
- "shareOnBluesky": "Share on Bluesky",
- "shareOnLinkedIn": "Share on LinkedIn",
- "shareOnSlack": "Share on Slack",
- "shareOnTelegram": "Share on Telegram",
- "shareOnWhatsApp": "Share on WhatsApp",
- "rssFeed": "RSS Feed",
- "copyLink": "Copy link",
- "linkCopied": "Link copied!",
- "toc": "On this page",
- "more": "More from Express",
- "writeBanner": "Interested in writing a post? \n Check out our guidelines to get started.",
- "writeGuidelines": "Read the guidelines"
+ "share": "分享",
+ "shareOnX": "分享到 X",
+ "shareOnBluesky": "分享到 Bluesky",
+ "shareOnLinkedIn": "分享到 LinkedIn",
+ "shareOnSlack": "分享到 Slack",
+ "shareOnTelegram": "分享到Telegram",
+ "shareOnWhatsApp": "分享到WhatsApp",
+ "rssFeed": "RSS 订阅源",
+ "copyLink": "复制链接",
+ "linkCopied": "链接已复制!",
+ "toc": "本页总览",
+ "more": "更多 Express 内容",
+ "writeBanner": "有兴趣撰写文章吗? \n 查看我们的指南,开始投稿吧。",
+ "writeGuidelines": "阅读指南"
},
"toc": {
- "overview": "Overview"
+ "overview": "概述"
},
"features": {
- "title": "Clarity over complexity. For every developer.",
+ "title": "清晰胜于复杂,为每一位开发者而生。",
"performance": {
- "title": "Performance",
- "body": "Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love."
+ "title": "性能",
+ "body": "Express 提供了一层轻量级的基础 Web 应用功能,同时不会隐藏你熟悉且喜爱的 Node.js 特性。"
},
"api": {
"title": "APIs",
- "body": "With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy."
+ "body": "借助丰富的 HTTP 工具方法和中间件,你可以快速、轻松地构建健壮的 API。"
},
"middleware": {
- "title": "Middleware",
- "body": "Express is a lightweight and flexible routing framework with minimal core features meant to be augmented through the use of Express middleware modules."
+ "title": "中间件",
+ "body": "Express 是一个轻量且灵活的路由框架,核心功能精简,可通过 Express 中间件模块进行扩展。"
},
"webapplication": {
- "title": "Web Applications",
- "body": "Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications."
+ "title": "Web 应用程序",
+ "body": "Express 是一个简洁而灵活的 Node.js Web 应用框架,为 Web 和移动应用提供了一套强大的功能。"
}
},
"error404": {
- "title": "404 - Page Not Found",
- "description": "The page you are looking for could not be found.",
- "heading": "Page Not Found",
- "message": "The page you are looking for does not exist or has been moved.",
- "goHome": "Go to Home"
+ "title": "404 - 页面未找到",
+ "description": "找不到你要访问的页面。",
+ "heading": "页面未找到",
+ "message": "您查找的页面不存在或已被移动。",
+ "goHome": "返回首页"
},
"common": {
- "download": "Download"
+ "download": "下载"
},
"hero": {
- "tagline": "Fast, unopinionated, minimalist web framework for Node.js",
- "getStarted": "Get Started",
- "kawaiiLogoAlt": "Express.js kawaii logo",
- "videoPause": "Pause background video",
- "videoPlay": "Play background video"
+ "tagline": "适用于 Node.js 的快速、无约束、极简 Web 框架",
+ "getStarted": "马上体验",
+ "kawaiiLogoAlt": "Express.js 卡哇伊风格 Logo",
+ "videoPause": "暂停背景视频",
+ "videoPlay": "播放背景视频"
}
}
| |