diff --git a/_data/de/footer.yml b/_data/de/footer.yml index c04d2822d0..7ca317f1bb 100644 --- a/_data/de/footer.yml +++ b/_data/de/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: Lizenzvertrag \ No newline at end of file +license: Lizenzvertrag diff --git a/_data/de/general.yml b/_data/de/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/de/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/de/menu.yml b/_data/de/menu.yml index 0abd814019..d524e0ace1 100644 --- a/_data/de/menu.yml +++ b/_data/de/menu.yml @@ -1,19 +1,17 @@ # Home home: Home - # Getting started getting_started: Einführung -installing: Installing +installing: Installation hello_world: Hello world generator: Express generator basic_routing: Basisrouting static_files: Statische Dateien examples: More examples faq: Häufig gestellte Fragen - # Guide guide: Leitfaden -routing: Routing +routing: Weiterleitung (Routing) writing_middleware: Middleware schreiben using_middleware: Middleware verwenden overriding_express_api: Overriding the Express API @@ -24,15 +22,12 @@ behind_proxies: Express hinter Proxys migrating_4: Wechsel zu Express 4 migrating_5: Wechsel zu Express 5 database_integration: Datenbankintegration - # API reference - api: API-Referenz 5x: 5.x 4x: 4.x 3x: 3.x (veraltet) 2x: 2.x (veraltet) - # Advanced topics advanced: Themen für Fortgeschrittene developing_template_engines: Template-Engines @@ -40,7 +35,6 @@ security_updates: Sicherheitsupdates best_practice_security: Sicherheitsspezifische Best Practices best_practice_performance: Leistungsspezifische Best Practices healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: Ressourcen glossary: Glossar @@ -49,10 +43,8 @@ community: Community utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/es/footer.yml b/_data/es/footer.yml index b768e5f900..420659956c 100644 --- a/_data/es/footer.yml +++ b/_data/es/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Política de privacidad coc: Código de conducta trademark_policy: Política de marcas security_policy: Seguridad -license: Licencia \ No newline at end of file +license: Licencia diff --git a/_data/es/general.yml b/_data/es/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/es/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/es/menu.yml b/_data/es/menu.yml index fbc3e1f781..4e6360588b 100644 --- a/_data/es/menu.yml +++ b/_data/es/menu.yml @@ -1,16 +1,14 @@ # Home home: Inicio - # Getting started getting_started: Cómo empezar -installing: Instalación -hello_world: Hello world -generator: Generador de Express +installing: Instalando +hello_world: Hola mundo +generator: Generador express basic_routing: Direccionamiento básico static_files: Archivos estáticos -examples: More examples -faq: Preguntas más frecuentes - +examples: Más ejemplos +faq: FAQ # Guide guide: Guía routing: Direccionamiento @@ -24,14 +22,12 @@ behind_proxies: Express detrás de proxies migrating_4: Migración a Express 4 migrating_5: Migración a Express 5 database_integration: Integración de la base de datos - # API reference api: Referencia de API 5x: 5.x 4x: 4.x -3x: 3.x (en desuso) -2x: 2.x (en desuso) - +3x: 3.x (obsoleto) +2x: 2.x (obsoleto) # Advanced topics advanced: Temas avanzados developing_template_engines: Motores de plantilla @@ -39,21 +35,18 @@ security_updates: Actualizaciones de seguridad best_practice_security: Mejores prácticas de seguridad best_practice_performance: Mejores prácticas de rendimiento healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: Recursos glossary: Glosario middleware: Middleware community: Comunidad utils: Utility modules -contributing: Contributing to Express +contributing: Contribuir a Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post all_posts: All posts -write_post: Write a Post +write_post: Escribir un post diff --git a/_data/fr/footer.yml b/_data/fr/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/fr/footer.yml +++ b/_data/fr/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/fr/general.yml b/_data/fr/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/fr/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/fr/menu.yml b/_data/fr/menu.yml index 6e332938af..e458f9dab5 100644 --- a/_data/fr/menu.yml +++ b/_data/fr/menu.yml @@ -1,16 +1,14 @@ # Home home: Accueil - # Getting started getting_started: Mise en route -installing: Installing +installing: Installation hello_world: Hello world generator: Générateur Express basic_routing: Routage de base static_files: Fichiers statiques examples: More examples faq: FAQ - # Guide guide: Guide routing: Routage @@ -24,15 +22,12 @@ behind_proxies: Express derrière Proxys migrating_4: Migration vers Express 4 migrating_5: Migration vers Express 5 database_integration: Intégration de bases de données - # API reference - api: API reference 5x: 5.x 4x: 4.x 3x: 3.x (obsolète) 2x: 2.x (obsolète) - # Advanced topics advanced: Rubriques avancées developing_template_engines: Moteurs de modèles @@ -40,7 +35,6 @@ security_updates: Mises à jour de sécurité best_practice_security: Meilleures pratiques en termes de sécurité best_practice_performance: Meilleures pratiques en termes de performances healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: Ressources glossary: Glossaire @@ -49,10 +43,8 @@ community: Communauté utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/it/footer.yml b/_data/it/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/it/footer.yml +++ b/_data/it/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/it/general.yml b/_data/it/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/it/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/it/menu.yml b/_data/it/menu.yml index b8a5fbb6e0..38544bad5a 100644 --- a/_data/it/menu.yml +++ b/_data/it/menu.yml @@ -1,6 +1,5 @@ # Home home: Home - # Getting started getting_started: Introduzione installing: Installazione @@ -10,7 +9,6 @@ basic_routing: Routing di base static_files: File statici examples: More examples faq: FAQ - # Guide guide: Guide routing: Routing @@ -24,15 +22,12 @@ behind_proxies: Express con i proxy migrating_4: Passaggio a Express 4 migrating_5: Passaggio a Express 5 database_integration: Integrazione database - # API reference - api: Riferimento API 5x: 5.x 4x: 4.x 3x: 3.x (deprecato) 2x: 2.x (deprecato) - # Advanced topics advanced: Argomenti avanzati developing_template_engines: Motori di template @@ -40,19 +35,16 @@ security_updates: Aggiornamenti sulla sicurezza best_practice_security: Best practice sulla sicurezza best_practice_performance: Best practice sulle prestazioni healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: Risorse -glossary: Glossary +glossary: Glossario middleware: Middleware community: Community utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/ja/footer.yml b/_data/ja/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/ja/footer.yml +++ b/_data/ja/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/ja/general.yml b/_data/ja/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/ja/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/ja/menu.yml b/_data/ja/menu.yml index 9ceef0ced8..2eee50b2a4 100644 --- a/_data/ja/menu.yml +++ b/_data/ja/menu.yml @@ -1,6 +1,5 @@ # Home home: ホーム - # Getting started getting_started: 概説 installing: インストール @@ -10,7 +9,6 @@ basic_routing: 基本的なルーティング static_files: 静的ファイル examples: More examples faq: FAQ - # Guide guide: ガイド routing: ルーティング @@ -24,15 +22,12 @@ behind_proxies: プロキシーの背後の Express migrating_4: Express 4 への移行 migrating_5: Express 5 への移行 database_integration: データベースの統合 - # API reference - api: API リファレンス 5x: 5.x 4x: 4.x 3x: 3.x (非推奨) 2x: 2.x (非推奨) - # Advanced topics advanced: 高度なトピック developing_template_engines: テンプレート・エンジン @@ -40,7 +35,6 @@ security_updates: セキュリティー更新 best_practice_security: セキュリティーに関するベスト・プラクティス best_practice_performance: パフォーマンスに関するベスト・プラクティス healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: リソース glossary: 用語集 @@ -49,10 +43,8 @@ community: コミュニティー utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/ko/footer.yml b/_data/ko/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/ko/footer.yml +++ b/_data/ko/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/ko/general.yml b/_data/ko/general.yml index 2903d0067a..1ed861c663 100644 --- a/_data/ko/general.yml +++ b/_data/ko/general.yml @@ -1,8 +1,6 @@ -title_announcement: "Express 5.0 documentation is now available." -body_announcement: "The API documentation is a work in progress. For information on what's in the release, see the Express release history" - +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." community-caveat-alert: "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." - warning: 'Warning' note: 'Note' -caution: 'Caution' \ No newline at end of file +caution: 'Caution' diff --git a/_data/ko/menu.yml b/_data/ko/menu.yml index b8ecb43be9..7bef82a1e8 100644 --- a/_data/ko/menu.yml +++ b/_data/ko/menu.yml @@ -1,6 +1,5 @@ # Home home: 홈 - # Getting started getting_started: 시작하기 installing: 설치 @@ -10,9 +9,8 @@ basic_routing: 기본 라우팅 static_files: 정적 파일 examples: More examples faq: 자주 묻는 질문(FAQ) - # Guide -guide: 안내서 +guide: Gu안내서ide routing: 라우팅 writing_middleware: 미들웨어 작성 using_middleware: 미들웨어 사용 @@ -24,15 +22,12 @@ behind_proxies: 프록시 환경에서 Express 사용 migrating_4: Express 4로의 이전 migrating_5: Express 5로의 이전 database_integration: 데이터베이스 통합 - # API reference - api: API 참조 5x: 5.x 4x: 4.x 3x: 3.x(더 이상 사용되지 않음) 2x: 2.x(더 이상 사용되지 않음) - # Advanced topics advanced: 고급 주제 developing_template_engines: 템플리트 엔진 @@ -40,7 +35,6 @@ security_updates: 보안 업데이트 best_practice_security: 보안 우수 사례 best_practice_performance: 성능 우수 사례 healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: 자원 glossary: 용어집 @@ -49,10 +43,8 @@ community: 커뮤니티 utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/pt-br/footer.yml b/_data/pt-br/footer.yml index 5db69348bf..333dfebf6e 100644 --- a/_data/pt-br/footer.yml +++ b/_data/pt-br/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Política de Privacidade coc: Código de Conduta trademark_policy: Política de Marcas security_policy: Política de Segurança -license: Licença \ No newline at end of file +license: Licença diff --git a/_data/pt-br/general.yml b/_data/pt-br/general.yml index 2903d0067a..1ed861c663 100644 --- a/_data/pt-br/general.yml +++ b/_data/pt-br/general.yml @@ -1,8 +1,6 @@ -title_announcement: "Express 5.0 documentation is now available." -body_announcement: "The API documentation is a work in progress. For information on what's in the release, see the Express release history" - +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." community-caveat-alert: "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." - warning: 'Warning' note: 'Note' -caution: 'Caution' \ No newline at end of file +caution: 'Caution' diff --git a/_data/pt-br/menu.yml b/_data/pt-br/menu.yml index 4b6d49b40b..c481f58273 100644 --- a/_data/pt-br/menu.yml +++ b/_data/pt-br/menu.yml @@ -1,6 +1,5 @@ # Home home: Página Inicial - # Getting started getting_started: Introdução installing: Instalação @@ -9,8 +8,7 @@ generator: Gerador do Express basic_routing: Roteamento Básico static_files: Arquivos Estáticos examples: Perguntas mais frequentes -faq: FAQ - +faq: Perguntas mais frequentes # Guide guide: Guide routing: Roteamento @@ -24,15 +22,12 @@ behind_proxies: Express atrás de proxies migrating_4: Migrando para o Express 4 migrating_5: Migrando para o Express 5 database_integration: Integração de Banco de dados - # API reference - api: Referência da API 5x: 5.x 4x: 4.x 3x: 3.x (descontinuada) 2x: 2.x (descontinuada) - # Advanced topics advanced: Tópicos Avançados developing_template_engines: Mecanismos de modelo @@ -40,7 +35,6 @@ security_updates: Atualizações de segurança best_practice_security: Melhores práticas de segurança best_practice_performance: Melhores práticas de desempenho healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: Recursos glossary: Glossário @@ -49,10 +43,8 @@ community: Comunidade utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Suporte - # Blog blog: Blog latest_post: Ultimos post diff --git a/_data/zh-cn/footer.yml b/_data/zh-cn/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/zh-cn/footer.yml +++ b/_data/zh-cn/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/zh-cn/general.yml b/_data/zh-cn/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/zh-cn/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/zh-cn/menu.yml b/_data/zh-cn/menu.yml index cb569aa801..c0fe7b7a8c 100644 --- a/_data/zh-cn/menu.yml +++ b/_data/zh-cn/menu.yml @@ -1,6 +1,5 @@ # Home home: 主页 - # Getting started getting_started: 入门 installing: 安装 @@ -10,7 +9,6 @@ basic_routing: 基本路由 static_files: 静态文件 examples: More examples faq: 常见问题及解答 - # Guide guide: 指南 routing: 路由 @@ -24,15 +22,12 @@ behind_proxies: 代理背后的 Express migrating_4: 迁移到 Express 4 migrating_5: 迁移到 Express 5 database_integration: 数据库集成 - # API reference - api: API 参考 5x: 5.x 4x: 4.x 3x: 3.x (不推荐) 2x: 2.x (不推荐) - # Advanced topics advanced: 高级主题 developing_template_engines: 模板引擎 @@ -40,7 +35,6 @@ security_updates: 安全更新 best_practice_security: 安全最佳实践 best_practice_performance: 性能最佳实践 healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: 资源 glossary: 词汇表 @@ -49,10 +43,8 @@ community: 社区 utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/_data/zh-tw/footer.yml b/_data/zh-tw/footer.yml index 6d3291d58c..fe92f52ca8 100644 --- a/_data/zh-tw/footer.yml +++ b/_data/zh-tw/footer.yml @@ -3,4 +3,4 @@ privacy_policy: Privacy Policy coc: Code of Conduct trademark_policy: Trademark Policy security_policy: Security Policy -license: License \ No newline at end of file +license: License diff --git a/_data/zh-tw/general.yml b/_data/zh-tw/general.yml new file mode 100644 index 0000000000..1ed861c663 --- /dev/null +++ b/_data/zh-tw/general.yml @@ -0,0 +1,6 @@ +title_announcement: "Express@5.1.0: Now the Default on npm with LTS Timeline" +body_announcement: "Express 5.1.0 is now the default on npm, and we're introducing an official LTS schedule for the v4 and v5 release lines. Check out our latest blog for more information." +community-caveat-alert: "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." +warning: 'Warning' +note: 'Note' +caution: 'Caution' diff --git a/_data/zh-tw/menu.yml b/_data/zh-tw/menu.yml index bf2f92add8..14fdb2afa2 100644 --- a/_data/zh-tw/menu.yml +++ b/_data/zh-tw/menu.yml @@ -1,6 +1,5 @@ # Home home: 首頁 - # Getting started getting_started: 入門 installing: 安裝 @@ -10,7 +9,6 @@ basic_routing: 基本路由 static_files: 靜態檔案 examples: More examples faq: 常見問題 (FAQ) - # Guide guide: 手冊 routing: 路由 @@ -24,15 +22,12 @@ behind_proxies: 位於 Proxy 背後的 Express migrating_4: 移至 Express 4 migrating_5: 移至 Express 5 database_integration: 資料庫整合 - # API reference - api: API 參照 5x: 5.x 4x: 4.x 3x: 3.x 已淘汰 2x: 2.x (已淘汰) - # Advanced topics advanced: 進階主題 developing_template_engines: 範本引擎 @@ -40,7 +35,6 @@ security_updates: 安全更新 best_practice_security: 安全最佳作法 best_practice_performance: 效能最佳作法 healthcheck_graceful_shutdown: Health checks & shutdown - # Resources resources: 資源 glossary: 名詞解釋 @@ -49,10 +43,8 @@ community: 社群 utils: Utility modules contributing: Contributing to Express changelog: Release Change Log - # Support support: Support - # Blog blog: Blog latest_post: Latest post diff --git a/de/3x/api.md b/de/3x/api.md old mode 100755 new mode 100644 index 9315550841..de6a67412f --- a/de/3x/api.md +++ b/de/3x/api.md @@ -1,33 +1,26 @@ --- -layout: 3x-api +layout: api +version: 3x title: Express 3.x - API-Referenz description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. -menu: api lang: de +redirect_from: " " --- +
**Express 3.x WIRD NICHT MEHR GEWARTET** - Bekannte und unbekannte Probleme bei Sicherheit und Leistung in 3.x wurden seit dem letzten Update (1. August 2015) noch nicht behoben. Es wird dringend empfohlen, die aktuelle Version von Express zu verwenden. -
- -

3.x-API

+Bekannte und unbekannte Probleme bei Sicherheit und Leistung in 3.x wurden seit dem letzten Update (1. August 2015) noch nicht behoben. Es wird dringend empfohlen, die aktuelle Version von Express zu verwenden. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
- - {% include api/en/3x/res.md %} +

3.x-API

- - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %} diff --git a/de/4x/api.md b/de/4x/api.md old mode 100755 new mode 100644 index 736e92231a..495d6d08fe --- a/de/4x/api.md +++ b/de/4x/api.md @@ -1,27 +1,27 @@ --- -layout: 4x-api +layout: api +version: 4x title: Express 4.x - API-Referenz description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. -menu: api lang: de +redirect_from: " " --- +

4.x-API

- - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
diff --git a/de/5x/api.md b/de/5x/api.md index d4c783a87c..b0f4528ac6 100644 --- a/de/5x/api.md +++ b/de/5x/api.md @@ -1,18 +1,25 @@ --- -layout: 5x-api +layout: api +version: 5x title: Express 5.x - API-Referenz description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. -menu: api lang: de +redirect_from: " " ---

5.x API

-{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/de/advanced/best-practice-performance.md b/de/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 559c1ec354..3c638a17ca --- a/de/advanced/best-practice-performance.md +++ b/de/advanced/best-practice-performance.md @@ -4,30 +4,36 @@ title: Leistungsspezifische Best Practices für Express-Anwendungen in Produktio description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: de +redirect_from: " " --- # Best Practices in Produktionsumgebungen: Leistung und Zuverlässigkeit -## Überblick - In diesem Beitrag werden Best Practices in Bezug auf Leistung und Zuverlässigkeit für Express-Anwendungen behandelt, die in der Produktionsumgebung bereitgestellt werden. Dieses Thema gehört sicherlich zur "DevOps"-Welt und deckt traditionelle Entwicklungs- und Betriebsprozesse ab. Entsprechend sind die Informationen hier in zwei Teile unterteilt: -* [Empfehlungen für Maßnahmen an Ihrem Code](#code) (Entwicklung). -* [Empfehlungen für Maßnahmen an Ihrer Umgebung/Ihrem Setup](#env) (Betrieb). - - - -## Empfehlungen für Maßnahmen an Ihrem Code +- Things to do in your code (the dev part): + - Für statische Dateien Middleware verwenden + - Keine synchronen Funktionen verwenden + - [Do logging correctly](#do-logging-correctly) + - [Handle exceptions properly](#handle-exceptions-properly) +- Things to do in your environment / setup (the ops part): + - NODE_ENV auf "production" festlegen + - Automatischen Neustart Ihrer Anwendung sicherstellen + - Anwendung in einem Cluster ausführen + - Anforderungsergebnisse im Cache speichern + - Load Balancer verwenden + - Reverse Proxy verwenden + +## Things to do in your code {#in-code} Dies sind einige Beispiele für Maßnahmen, die Sie an Ihrem Code vornehmen können, um die Anwendungsleistung zu verbessern: -* GZIP-Komprimierung verwenden -* Keine synchronen Funktionen verwenden -* Für statische Dateien Middleware verwenden -* Auf ordnungsgemäße Protokollierung achten -* Ausnahmebedingungen ordnungsgemäß handhaben +- Für statische Dateien Middleware verwenden +- Keine synchronen Funktionen verwenden +- [Do logging correctly](#do-logging-correctly) +- [Handle exceptions properly](#handle-exceptions-properly) ### GZIP-Komprimierung verwenden @@ -37,6 +43,7 @@ Mit der GZIP-Komprimierung lässt sich die Größe des Antworthauptteils deutlic const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` @@ -48,19 +55,11 @@ Synchrone Funktionen und Methoden belasten den Ausführungsprozess, bis sie zur Auch wenn Node und viele andere Module synchrone und asynchrone Versionen ihrer Funktionen bieten, sollten Sie in Produktionsumgebungen immer die asynchrone Version verwenden. Nur beim ersten Systemstart ist die Verwendung einer synchronen Funktion begründet. -Wenn Sie Node.js 4.0 und höher oder io.js 2.1.0 und höher verwenden, können Sie über das Befehlszeilenflag `--trace-sync-io` eine Warnung und einen Stack-Trace ausgeben, wenn Ihre Anwendung eine synchrone API verwendet. Auch wenn Sie diese natürlich nicht in der Produktionsumgebung verwenden werden, soll dadurch trotzdem sichergestellt werden, dass Ihr Code in der Produktionsumgebung eingesetzt werden kann. Weitere Informationen hierzu siehe [Wöchentliches Update für io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0). - -### Für statische Dateien Middleware verwenden - -Bei der Entwicklung können Sie [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) für statische Dateien verwenden. Dies gilt jedoch nicht für die Produktionsumgebung, da diese Funktion bei jeder Dateianforderung aus dem Dateisystem lesen muss. Dadurch kommt es zu deutlichen Latenzen, die sich negativ auf die Gesamtleistung der Anwendung auswirken. Beachten Sie, dass `res.sendFile()` *nicht* mit dem Systemaufruf [sendfile](http://linux.die.net/man/2/sendfile) implementiert wird, wodurch dieser deutlich effizienter wäre. +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. Auch wenn Sie diese natürlich nicht in der Produktionsumgebung verwenden werden, soll dadurch trotzdem sichergestellt werden, dass Ihr Code in der Produktionsumgebung eingesetzt werden kann. Weitere Informationen hierzu siehe [Wöchentliches Update für io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0). -Verwenden Sie stattdessen die Middleware [serve-static](https://www.npmjs.com/package/serve-static) (oder etwas Vergleichbares), die für die Bereitstellung von Dateien für Express-Anwendungen optimiert ist. +### Do logging correctly -Die bessere Option wäre, für statische Dateien einen Reverse Proxy zu verwenden. Weitere Informationen siehe [Reverse Proxy verwenden](#proxy). - -### Auf ordnungsgemäße Protokollierung achten - -Im Allgemeinen gibt es für die Protokollierung Ihrer Anwendung zwei Gründe: 1) Debugging und 2) Protokollierung von Anwendungsaktivitäten (im Wesentlichen alles andere, außer Debugging). Die Verwendung von`console.log()` oder `console.err()` zur Ausgabe von Protokollnachrichten an das Terminal ist in der Entwicklung gängige Praxis. [Diese Funktionen sind jedoch synchron](https://nodejs.org/api/console.html#console_console_1), wenn das Ziel ein Terminal oder eine Datei ist. Sie sind also für Produktionsumgebungen nicht geeignet, es sei denn, Sie leiten die Ausgabe per Pipe zu einem anderen Programm um. +Im Allgemeinen gibt es für die Protokollierung Ihrer Anwendung zwei Gründe: 1) Debugging und 2) Protokollierung von Anwendungsaktivitäten (im Wesentlichen alles andere, außer Debugging). Die Verwendung von`console.log()` oder `console.err()` zur Ausgabe von Protokollnachrichten an das Terminal ist in der Entwicklung gängige Praxis. 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. #### Für Debuggingzwecke @@ -68,43 +67,29 @@ Wenn Sie die Protokollierung für Debuggingzwecke nutzen, sollten Sie statt `con #### Für Anwendungsaktivitäten -Wenn Sie Anwendungsaktivitäten protokollieren (z. B. den Datenverkehr oder API-Aufrufe aufzeichnen), sollten Sie statt `console.log()` eine Protokollierungsbibliothek wie [Winston](https://www.npmjs.com/package/winston) oder [Bunyan](https://www.npmjs.com/package/bunyan) verwenden. Einen ausführlichen Vergleich dieser beiden Bibliotheken finden Sie im StrongLoop-Blogbeitrag [Vergleich von Winston und Bunyan für die Node.js-Protokollierung](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/). - - +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. ### Ausnahmebedingungen ordnungsgemäß handhaben -Node-Anwendungen stürzen ab, wenn eine nicht abgefangene Ausnahmebedingung vorkommt. Wenn diese Ausnahmebedingungen nicht behandelt und entsprechende Maßnahmen eingeleitet werden, stürzt Ihre Express-Anwendung ab und geht offline. Wenn Sie dem nachfolgenden Rat in [Sicherstellen, dass Ihre Anwendung automatisch neu gestartet wird](#restart) folgen, wird Ihre Anwendung nach einem Absturz wiederhergestellt. Glücklicherweise haben Express-Anwendungen nur eine kurze Initialisierungszeit. Nichtsdestotrotz sollten Sie in erster Linie solche Abstürze vermeiden. Und hierzu müssen Sie Ausnahmebedingungen ordnungsgemäß handhaben. +Node-Anwendungen stürzen ab, wenn eine nicht abgefangene Ausnahmebedingung vorkommt. Wenn diese Ausnahmebedingungen nicht behandelt und entsprechende Maßnahmen eingeleitet werden, stürzt Ihre Express-Anwendung ab und geht offline. Wenn Sie dem nachfolgenden Rat in [Sicherstellen, dass Ihre Anwendung automatisch neu gestartet wird](#restart) folgen, wird Ihre Anwendung nach einem Absturz wiederhergestellt. Glücklicherweise haben Express-Anwendungen nur eine kurze Initialisierungszeit. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly. Mit folgenden Verfahren stellen Sie sicher, dass alle Ausnahmebedingungen gehandhabt werden: -* ["try-catch" verwenden](#try-catch) -* ["Promises" verwenden](#promises) +- ["try-catch" verwenden](#try-catch) +- ["Promises" verwenden](#promises) Um näher auf diese Themen eingehen zu können, müssen Sie sich ein grundlegendes Verständnis der Fehlerbehandlung in Node und Express aneignen: Verwendung von Error-first-Callbacks und Propagieren von Fehlern in Middleware. Node verwendet die Konvention "Error-first-Callback" für die Rückgabe von Fehlern von asynchronen Funktionen, bei denen der erste Parameter zur Callback-Funktion das Fehlerobjekt ist, gefolgt von Ergebnisdaten in den nachfolgenden Parametern. Um anzugeben, dass kein Fehler vorliegt, müssen Sie "null" als ersten Parameter übergeben. Die Callback-Funktion muss der Konvention "Error-first-Callback" folgen, um den Fehler sinnvoll bearbeiten zu können. In Express hat sich bewährt, die Funktion "next()" zu verwenden, um Fehler über die Middleware-Chain zu propagieren. Weitere Informationen zu den Grundlagen der Fehlerbehandlung siehe: -* [Fehlerbehandlung in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Aufbau leistungsfähiger Node-Anwendungen: Fehlerbehandlung](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (StrongLoop-Blog) - -#### Was Sie unterlassen sollten - -Sie sollten *auf keinen* Fall per Listener das Ereignis `uncaughtException` überwachen, das ausgegeben wird, wenn eine Ausnahmebedingung bis zurück zur Ereignisschleife bestehen bleibt. Durch das Hinzufügen eines Ereignislisteners für `uncaughtException` verändert sich das Standardverhalten des Prozesses, über das eine Ausnahmebedingung festgestellt wird. Der Prozess läuft dann trotz der Ausnahmebedingung weiter. Dies mag sich vielleicht gut anhören, um einem Absturz Ihrer Anwendung vorzubeugen. Das Ausführen einer Anwendung nach einer nicht abgefangenen Ausnahmebedingung ist aber eine durchaus riskante Vorgehensweise und wird nicht empfohlen, da der Prozessstatus störanfällig und unvorhersehbar wird. - -Außerdem wird die Verwendung von `uncaughtException` offiziell als [grobes Vorgehen](https://nodejs.org/api/process.html#process_event_uncaughtexception) angesehen, sodass es den [Vorschlag](https://github.com/nodejs/node-v0.x-archive/issues/2582) gibt, die Funktion aus dem Kern zu entfernen. Das Überwachen von `uncaughtException` per Listener ist also keine gute Idee. Daher empfehlen wir Dinge wie Mehrfachprozesse und Supervisoren: Ein Absturz und anschließender Neustart ist häufig die zuverlässigste Art der Fehlerbehebung. - -Zudem empfehlen wir, [domains](https://nodejs.org/api/domain.html) nicht zu verwenden. Mit diesem Modul, das zudem veraltet ist, lässt sich das Problem in der Regel nicht lösen. - - +- [Fehlerbehandlung in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### "try-catch" verwenden "try-catch" ist ein JavaScript-Sprachkonstrukt, mit dem Sie Ausnahmebedingungen in synchronem Code abfangen können. Verwenden Sie "try-catch" beispielsweise, um JSON-Parsing-Fehler wie unten gezeigt zu bearbeiten. -Verwenden Sie ein Tool wie [JSHint](http://jshint.com/) oder [JSLint](http://www.jslint.com/), um implizite Ausnahmebedingungen wie [Referenzfehler bei nicht definierten Variablen](http://www.jshint.com/docs/options/#undef) zu finden. - -Dies ist ein Beispiel zur Verwendung von "try-catch", um eine potenzielle "process-crashing"-Ausnahmebedingung zu handhaben. Diese Middlewarefunktion akzeptiert einen Abfragefeldparameter mit dem Namen "params", der ein JSON-Objekt ist. +Dies ist ein Beispiel zur Verwendung von "try-catch", um eine potenzielle "process-crashing"-Ausnahmebedingung zu handhaben. +Diese Middlewarefunktion akzeptiert einen Abfragefeldparameter mit dem Namen "params", der ein JSON-Objekt ist. ```js app.get('/search', (req, res) => { @@ -123,85 +108,70 @@ app.get('/search', (req, res) => { "try-catch" funktioniert jedoch nur in synchronem Code. Da die Node-Plattform primär asynchron ist (insbesondere in einer Produktionsumgebung), lassen sich mit "try-catch" nicht besonders viele Ausnahmebedingungen abfangen. - - #### "Promises" verwenden -Mit "Promises" werden alle Ausnahmebedingungen (explizite und implizite) in asynchronen Codeblöcken gehandhabt, die `then()` verwenden. Sie müssen nur `.catch(next)` am Ende der Promises-Ketten hinzufügen. Beispiel: +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -Jetzt werden alle asynchronen und synchronen Fehler zur Middleware "error" propagiert. - -Es gibt jedoch zwei Vorbehalte: - -1. Der gesamte asynchrone Code muss "Promises" zurückgeben (außer Emitter). Wenn eine bestimmte Bibliothek keine "Promises" zurückgibt, müssen Sie das Basisobjekt mit einer Helper-Funktion wie [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html) konvertieren. -2. Ereignisemitter (wie Streams) können nach wie vor nicht abgefangene Ausnahmebedingungen verursachen. Sie müssen also sicherstellen, dass Sie das Fehlerereignis ordnungsgemäß handhaben. Beispiel: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -Weitere Informationen zur Fehlerbehandlung mithilfe von "Promises" siehe: +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. -* [Asynchrone Fehlerbehandlung in Express mit "Promises", Generatoren und ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* ["Promises" in Node.js mit Q – eine Alternative zu Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +#### What not to do - +Sie sollten _auf keinen_ Fall per Listener das Ereignis `uncaughtException` überwachen, das ausgegeben wird, wenn eine Ausnahmebedingung bis zurück zur Ereignisschleife bestehen bleibt. Durch das Hinzufügen eines Ereignislisteners für `uncaughtException` verändert sich das Standardverhalten des Prozesses, über das eine Ausnahmebedingung festgestellt wird. Das Ausführen einer Anwendung nach einer nicht abgefangenen Ausnahmebedingung ist aber eine durchaus riskante Vorgehensweise und wird nicht empfohlen, da der Prozessstatus störanfällig und unvorhersehbar wird. -## Empfehlungen für Maßnahmen an Ihrer Umgebung/Ihrem Setup +Außerdem wird die Verwendung von `uncaughtException` offiziell als [grobes Vorgehen](https://nodejs.org/api/process.html#process_event_uncaughtexception) angesehen, sodass es den [Vorschlag](https://github.com/nodejs/node-v0.x-archive/issues/2582) gibt, die Funktion aus dem Kern zu entfernen. Das Überwachen von `uncaughtException` per Listener ist also keine gute Idee. Daher empfehlen wir Dinge wie Mehrfachprozesse und Supervisoren: Ein Absturz und anschließender Neustart ist häufig die zuverlässigste Art der Fehlerbehebung. -Dies sind einige Beispiele für Maßnahmen, die Sie an Ihrer Systemumgebung vornehmen können, um die Anwendungsleistung zu verbessern: +Zudem empfehlen wir, [domains](https://nodejs.org/api/domain.html) nicht zu verwenden. Mit diesem Modul, das zudem veraltet ist, lässt sich das Problem in der Regel nicht lösen. -* NODE_ENV auf "production" festlegen -* Automatischen Neustart Ihrer Anwendung sicherstellen -* Anwendung in einem Cluster ausführen -* Anforderungsergebnisse im Cache speichern -* Load Balancer verwenden -* Reverse Proxy verwenden +## Things to do in your environment / setup -### NODE_ENV auf "production" festlegen +{#in-environment} -In der Umgebungsvariablen NODE_ENV wird die Umgebung angegeben, in der eine Anwendung ausgeführt wird (in der Regel ist dies die Entwicklungs- oder Produktionsumgebung). Am einfachsten lässt sich die Leistung verbessern, indem NODE_ENV auf "production" festgelegt wird. +Dies sind einige Beispiele für Maßnahmen, die Sie an Ihrer Systemumgebung vornehmen können, um die Anwendungsleistung zu verbessern: -Durch das Festlegen von NODE_ENV auf "production" führt Express Folgendes aus: +- NODE_ENV auf "production" festlegen +- Automatischen Neustart Ihrer Anwendung sicherstellen +- Anwendung in einem Cluster ausführen +- Anforderungsergebnisse im Cache speichern +- Load Balancer verwenden +- Reverse Proxy verwenden -* Speichern von Anzeigevorlagen im Cache. -* Speichern von CSS-Dateien, die aus CSS-Erweiterungen generiert wurden, im Cache. -* Generieren von weniger ausführlichen Fehlernachrichten. +### NODE_ENV auf "production" festlegen -[Tests deuten darauf hin](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/), dass alleine dadurch die Anwendungsleistung um den Faktor 3 verbessert werden kann! +In der Umgebungsvariablen NODE_ENV wird die Umgebung angegeben, in der eine Anwendung ausgeführt wird (in der Regel ist dies die Entwicklungs- oder Produktionsumgebung). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. -Wenn Sie umgebungsspezifischen 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 Werts seiner Umgebungsvariablen eine leistungsbezogene Penalisierung nach sich zieht. Sie sollten also sehr sparsam damit umgehen. +Durch das Festlegen von NODE_ENV auf "production" führt Express Folgendes aus: -In einer Entwicklungsumgebung wird die Umgebungsvariable in der Regel in Ihrer interaktiven Shell festgelegt, indem Sie beispielsweise `export` oder Ihre Datei `.bash_profile` verwenden. Im Allgemeinen sollten Sie dies nicht auf dem Produktionsserver vornehmen. Verwenden Sie stattdessen das Init-System (systemd oder Upstart) Ihres Betriebssystems. Der nächste Abschnitt enthält weitere Details zur Verwendung des Init-Systems im Allgemeinen. Die Festlegung von NODE_ENV ist jedoch für das Leistungsverhalten so wichtig (und so einfach durchzuführen), dass hier besonders darauf eingegangen wird. +- Speichern von Anzeigevorlagen im Cache. +- Speichern von CSS-Dateien, die aus CSS-Erweiterungen generiert wurden, im Cache. +- Generieren von weniger ausführlichen Fehlernachrichten. -Verwenden Sie bei Upstart das Schlüsselwort `env` in Ihrer Jobdatei. Beispiel: +[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! -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` +Wenn Sie umgebungsspezifischen 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 Werts seiner Umgebungsvariablen eine leistungsbezogene Penalisierung nach sich zieht. -Weitere Informationen hierzu siehe [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables). +In einer Entwicklungsumgebung wird die Umgebungsvariable in der Regel in Ihrer interaktiven Shell festgelegt, indem Sie beispielsweise `export` oder Ihre Datei `.bash_profile` verwenden. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). Der nächste Abschnitt enthält weitere Details zur Verwendung des Init-Systems im Allgemeinen. Die Festlegung von NODE_ENV ist jedoch für das Leistungsverhalten so wichtig (und so einfach durchzuführen), dass hier besonders darauf eingegangen wird. Verwenden Sie bei systemd die Anweisung `Environment` in Ihrer Einheitendatei. Beispiel: @@ -210,16 +180,14 @@ Verwenden Sie bei systemd die Anweisung `Environment` in Ihrer Einheitendatei. B Environment=NODE_ENV=production ``` -Weitere Informationen siehe [Umgebungsvariablen in systemd-Einheiten verwenden](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html). - -Wenn Sie StrongLoop Process Manager verwenden, können Sie auch die [Umgebungsvariable festlegen, wenn Sie StrongLoop Process Manager als Service installieren](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables). +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Automatischen Neustart Ihrer Anwendung sicherstellen In der Produktionsumgebung sollte die Anwendung nie offline sein. Das bedeutet, dass Sie sicherstellen müssen, dass die Anwendung bei einem Absturz der Anwendung oder des Servers immer wieder neu gestartet wird. Auch wenn man hofft, das keines dieser Ereignisse jemals eintritt, muss man doch mit beiden Möglichkeiten rechnen und: -* einen Prozessmanager verwenden, um die Anwendung (und Node) bei einem Absturz neu zu starten. -* das Init-System Ihres Betriebssystems verwenden, um den Prozessmanager bei einem Absturz des Betriebssystems neu zu starten. Außerdem kann das Init-System auch ohne einen Prozessmanager verwendet werden. +- einen Prozessmanager verwenden, um die Anwendung (und Node) bei einem Absturz neu zu starten. +- das Init-System Ihres Betriebssystems verwenden, um den Prozessmanager bei einem Absturz des Betriebssystems neu zu starten. Außerdem kann das Init-System auch ohne einen Prozessmanager verwendet werden. Node-Anwendungen stürzen ab, wenn eine nicht abgefangene Ausnahmebedingung auftritt. Als Erstes müssen Sie in einem solchen Fall sicherstellen, dass Ihre Anwendung ausreichend getestet wurde und in der Lage ist, alle Ausnahmebedingungen zu handhaben (weitere Informationen siehe [Ausnahmebedingungen ordnungsgemäß handhaben](#exceptions)). Die sicherste Maßnahme ist jedoch, einen Mechanismus zu implementieren, über den bei einem Absturz der Anwendung ein automatischer Neustart der Anwendung ausgeführt wird. @@ -229,54 +197,35 @@ In Entwicklungumgebungen wird die Anwendung einfach über die Befehlszeile mit ` Neben einem Neustart der Anwendung nach einem Absturz bietet ein Prozessmanager noch weitere Möglichkeiten: -* Einblicke in die Laufzeitleistung und die Ressourcennutzung -* Dynamische Änderung der Einstellungen zur Verbesserung des Leistungsverhaltens -* Steuerung des Clustering (StrongLoop PM und PM2) +- Einblicke in die Laufzeitleistung und die Ressourcennutzung +- Dynamische Änderung der Einstellungen zur Verbesserung des Leistungsverhaltens +- Control clustering (pm2). -Die gängigsten Prozessmanager für Node sind: - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -Einen Vergleich der Features und Funktionen dieser Prozessmanager finden Sie hier: [http://strong-pm.io/compare/](http://strong-pm.io/compare/). - -Die Verwendung eines dieser Prozessmanager reicht aus, um Ihre Anwendung betriebsbereit zu halten, selbst wenn sie hin und wieder abstürzt. - -StrongLoop PM verfügt jedoch über zahlreiche Features und Funktionen, die sich speziell auf Implementierungen in der Produktionsumgebung beziehen. Sie können diesen Prozessmanager und die zugehörigen StrongLoop-Tools für folgende Zwecke verwenden: - -* Lokales Erstellen und Packen Ihrer Anwendung mit anschließender sicherer Bereitstellung auf Ihrem Produktionssystem -* Automatischer Neustart Ihrer Anwendung nach einem Absturz aus irgendeinem Grund -* Verwaltung Ihrer Cluster über Fernzugriff -* Anzeige von CPU-Profilen und Heapspeichermomentaufnahmen (Heap-Snapshots) zur Optimierung der Leistung und Diagnose von Speicherlecks -* Anzeige von Leistungsmessdaten für Ihre Anwendung -* Einfache Skalierung auf mehrere Hosts mit integrierter Steuerung für Nginx Load Balancer - -Wie unten beschrieben, erfolgt ein automatischer Neustart beim Systemwiederanlauf, wenn Sie StrongLoop Process Manager über Ihr Init-System als Betriebssystemservice installieren. Dadurch bleiben Ihre Anwendungsprozesse und Cluster dauerhaft betriebsbereit. +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 -Als nächste Ebene der Zuverlässigkeit müssen Sie sicherstellen, dass Ihre Anwendung bei einem Serverneustart neu gestartet wird. Systeme können immer wieder aus verschiedenen Gründen abstürzen. Um sicherzustellen, dass Ihre Anwendung bei einem Serverabsturz neu gestartet wird, können Sie das in Ihr Betriebssystem integrierte Init-System verwenden. Die beiden wichtigsten Init-Systeme sind aktuell [systemd](https://wiki.debian.org/systemd) und [Upstart](http://upstart.ubuntu.com/). +Als nächste Ebene der Zuverlässigkeit müssen Sie sicherstellen, dass Ihre Anwendung bei einem Serverneustart neu gestartet wird. Systeme können immer wieder aus verschiedenen Gründen abstürzen. Um sicherzustellen, dass Ihre Anwendung bei einem Serverabsturz neu gestartet wird, können Sie das in Ihr Betriebssystem integrierte Init-System verwenden. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Es gibt zwei Möglichkeiten, Init-Systeme mit Ihrer Express-Anwendung zu verwenden: -* Ausführung Ihrer Anwendung in einem Prozessmanager und Installation des Prozessmanagers als Service mit dem Init-System. Der Prozessmanager wird neu gestartet, wenn Ihre Anwendung abstürzt. Das Init-System startet dann den Prozessmanager neu, sobald das Betriebssystem neu gestartet wird. Dies ist die empfohlene Vorgehensweise. -* Ausführung Ihrer Anwendung (und von Node) direkt mit dem Init-System. Diese Vorgehensweise ist zwar etwas einfacher, Sie profitieren jedoch nicht von den zusätzlichen Vorteilen des Einsatzes eines Prozessmanagers. +- Ausführung Ihrer Anwendung in einem Prozessmanager und Installation des Prozessmanagers als Service mit dem Init-System. Der Prozessmanager wird neu gestartet, wenn Ihre Anwendung abstürzt. Dies ist die empfohlene Vorgehensweise. +- Ausführung Ihrer Anwendung (und von Node) direkt mit dem Init-System. Diese Vorgehensweise ist zwar etwas einfacher, Sie profitieren jedoch nicht von den zusätzlichen Vorteilen des Einsatzes eines Prozessmanagers. ##### systemd "systemd" ist ein Linux-System und Service-Manager. Die meisten wichtigen Linux-Distributionen haben "systemd" als Init-Standardsystem übernommen. -Eine "systemd"-Servicekonfigurationsdatei wird als *Einheitendatei* bezeichnet, die die Endung ".service" hat. Dies ist ein Beispiel für eine Einheitendatei zur direkten Verwaltung einer Node-Anwendung (ersetzen Sie den Text in Fettdruck durch Werte für Ihr System und Ihre Anwendung): +Eine "systemd"-Servicekonfigurationsdatei wird als _Einheitendatei_ bezeichnet, die die Endung ".service" hat. Dies ist ein Beispiel für eine Einheitendatei zur direkten Verwaltung einer Node-Anwendung (ersetzen Sie den Text in Fettdruck durch Werte für Ihr System und Ihre Anwendung): Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -298,143 +247,67 @@ Restart=always [Install] WantedBy=multi-user.target ``` -Weitere Informationen zu "systemd" siehe [systemd-Referenz (Man-Page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). -##### StrongLoop Process Manager als "systemd"-Service - -Sie können StrongLoop Process Manager problemlos als "systemd"-Service installieren. Dadurch wird beim Serverneustart StrongLoop Process Manager automatisch neu gestartet. Dadurch wiederum werden alle Anwendungen neu gestartet, die von diesem Prozessmanager verwaltet werden. - -So installieren Sie StrongLoop Process Manager als "systemd"-Service: - -```bash -$ sudo sl-pm-install --systemd -``` - -Starten Sie dann den Service mit: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -Weitere Informationen hierzu finden Sie im Thema [Produktionshost einrichten (in der StrongLoop-Dokumentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10). - -##### Upstart - -"Upstart" ist ein Systemtool, das auf vielen Linux-Distributionen verfügbar ist. Mit diesem Tool können Aufgaben (Tasks) und Services beim Systemstart gestartet, beim Herunterfahren gestoppt und auch überwacht werden. Sie können Ihre Express-Anwendung oder einen Prozessmanager als Service konfigurieren. "Upstart" startet diese dann bei einem Absturz automatisch neu. - -Ein "Upstart"-Service wird als Jobkonfigurationsdatei (auch als "Job" bezeichnet) definiert, deren Dateiname mit `.conf` endet. Das folgende Beispiel zeigt, wie ein Job namens "myapp" für eine Anwendung namens "myapp" erstellt wird, wobei sich die Hauptdatei im Verzeichnis `/projects/myapp/index.js` befindet. - -Erstellen Sie eine Datei namens `myapp.conf` unter `/etc/init/` mit dem folgenden Inhalt (ersetzen Sie den Text in Fettdruck durch Werte für Ihr System und Ihre Anwendung): -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn +Weitere Informationen zu "systemd" siehe [systemd-Referenz (Man-Page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` +### Anwendung in einem Cluster ausführen -Hinweis: Dieses Script erfordert Upstart 1.4 oder höher mit Unterstützung auf Ubuntu 12.04-14.10. +In einem Multi-Core-System können Sie die Leistung einer Node-Anwendung mehrmals erhöhen, indem Sie einen Cluster von Prozessen starten. Ein Cluster führt mehrere Instanzen der Anwendung aus, idealerweise eine Instanz auf jedem CPU-Core. -Da der Job so konfiguriert ist, dass er beim Systemstart ausgeführt wird, wird Ihre Anwendung zusammen mit dem Betriebssystem gestartet und automatisch neu gestartet, wenn die Anwendung abstürzt oder das System heruntergefahren wird. +![Balancing between application instances using the cluster API](/images/clustering.png) -Neben dem automatischen Neustart der Anwendung können Sie mit Upstart die folgenden Befehle verwenden: +Wichtig. Da die Anwendungsinstanzen als separate Prozesse ausgeführt werden, nutzen sie nicht dieselbe Hauptspeicherkapazität gemeinsam. Das heißt, Objekte befinden sich für jede Instanz der Anwendung auf lokaler Ebene. Daher kann der Status im Anwendungscode nicht beibehalten werden. Sie können jedoch einen speicherinternen Datenspeicher wie [Redis](http://redis.io/) verwenden, um sitzungsrelevante Daten und Statusinformationen zu speichern. Diese Einschränkung trifft im Wesentlichen auf alle Formen der horizontalen Skalierung zu, unabhängig davon, ob es sich um Clustering mit mehreren Prozessen oder mehreren physischen Servern handelt. -* `start myapp` – Anwendung starten -* `restart myapp` – Anwendung neu starten -* `stop myapp` – Anwendung stoppen +Bei in Gruppen zusammengefassten Anwendungen (geclusterte Anwendungen) können Verarbeitungsprozesse einzeln ausfallen, ohne dass sich dies auf die restlichen Prozesse auswirkt. Neben den Leistungsvorteilen ist die Fehlerisolierung ein weiterer Grund, einen Cluster von Anwendungsprozessen auszuführen. Wenn ein Verarbeitungsprozess abstürzt, müssen Sie sicherstellen, dass das Ereignis protokolliert und ein neuer Prozess mithilfe von "cluster.fork()" gestartet wird. -Weitere Informationen zu "Upstart" siehe [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook). +#### Clustermodule von Node verwenden -##### StrongLoop Process Manager als "Upstart"-Service +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). Dadurch wird ein Masterprozess eingeleitet, um Verarbeitungsprozesse zu starten und eingehende Verbindungen auf die Verarbeitungsprozesse zu verteilen. -Sie können StrongLoop Process Manager problemlos als "Upstart"-Service installieren. Dadurch wird beim Serverneustart StrongLoop Process Manager automatisch neu gestartet. Dadurch wiederum werden alle Anwendungen neu gestartet, die von diesem Prozessmanager verwaltet werden. +#### Using PM2 -So installieren Sie StrongLoop Process Manager als "Upstart 1.4"-Service: +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). -```bash -$ sudo sl-pm-install -``` +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. -Fühen Sie dann den Service aus mit: +To enable cluster mode, start your application like so: ```bash -$ sudo /sbin/initctl start strong-pm +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -Hinweis: Auf Systemen, die Upstart 1.4 nicht unterstützen, sind die Befehle leicht unterschiedlich. Weitere Informationen hierzu siehe das -Thema [Einrichtung eines Produktionshosts (in der StrongLoop-Dokumentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10). +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. -### Anwendung in einem Cluster ausführen - -In einem Multi-Core-System können Sie die Leistung einer Node-Anwendung mehrmals erhöhen, indem Sie einen Cluster von Prozessen starten. Ein Cluster führt mehrere Instanzen der Anwendung aus, idealerweise eine Instanz auf jedem CPU-Core. Dadurch werden die Arbeitslasten und die Tasks auf die Instanzen verteilt. - - - -Wichtig. Da die Anwendungsinstanzen als separate Prozesse ausgeführt werden, nutzen sie nicht dieselbe Hauptspeicherkapazität gemeinsam. Das heißt, Objekte befinden sich für jede Instanz der Anwendung auf lokaler Ebene. Daher kann der Status im Anwendungscode nicht beibehalten werden. Sie können jedoch einen speicherinternen Datenspeicher wie [Redis](http://redis.io/) verwenden, um sitzungsrelevante Daten und Statusinformationen zu speichern. Diese Einschränkung trifft im Wesentlichen auf alle Formen der horizontalen Skalierung zu, unabhängig davon, ob es sich um Clustering mit mehreren Prozessen oder mehreren physischen Servern handelt. - -Bei in Gruppen zusammengefassten Anwendungen (geclusterte Anwendungen) können Verarbeitungsprozesse einzeln ausfallen, ohne dass sich dies auf die restlichen Prozesse auswirkt. Neben den Leistungsvorteilen ist die Fehlerisolierung ein weiterer Grund, einen Cluster von Anwendungsprozessen auszuführen. Wenn ein Verarbeitungsprozess abstürzt, müssen Sie sicherstellen, dass das Ereignis protokolliert und ein neuer Prozess mithilfe von "cluster.fork()" gestartet wird. - -#### Clustermodule von Node verwenden - -Das Clustering erfolgt über das [Clustermodul](https://nodejs.org/docs/latest/api/cluster.html) von Node. Dadurch wird ein Masterprozess eingeleitet, um Verarbeitungsprozesse zu starten und eingehende Verbindungen auf die Verarbeitungsprozesse zu verteilen. Anstatt dieses Modul jedoch direkt zu verwenden, ist es deutlich besser, eines der vielen angebotenen Tools einzusetzen, das diesen Vorgang automatisch für Sie ausführt, wie beispielsweise [node-pm](https://www.npmjs.com/package/node-pm) oder [cluster-service](https://www.npmjs.com/package/cluster-service). - -#### StrongLoop Process Manager verwenden - -Wenn Sie Ihre Anwendung auf StrongLoop Process Manager (PM) bereitstellen, können Sie die Vorteile des Clustering nutzen, *ohne* Ihren Anwendungscode ändern zu müssen. - -Wenn StrongLoop Process Manager (PM) eine Anwendung ausführt, wird diese automatisch in einem Cluster ausgeführt. Die Anzahl der Verarbeitungsprozesse entspricht dabei der Anzahl der CPU-Cores im System. Sie können die Anzahl der Verarbeitungsprozesse manuell im Cluster ändern. Hierfür verwenden Sie das Befehlszeilentool "slc", ohne die Anwendung stoppen zu müssen. - -Beispiel: Angenommen, Sie haben Ihre Anwendung auf prod.foo.com bereitgestellt, und StrongLoop PM ist auf Port 8701 (Standardport) empfangsbereit. Dann müssen Sie die Clustergröße mithilfe von "slc" auf "8" einstellen. +Once running, the application can be scaled like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ pm2 scale my-app 2 ``` -Weitere Informationen zum Clustering mit StrongLoop PM finden Sie im Thema [Clustering](https://docs.strongloop.com/display/SLC/Clustering) in der StrongLoop-Dokumentation. +For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation. ### Anforderungsergebnisse im Cache speichern Eine weitere Strategie zur Verbesserung des Leistungsverhaltens in Produktionsumgebungen ist das Speichern von Anforderungergebnissen im Cache. Ihre Anwendung muss also diese Operation nicht wiederholt ausführen, um dieselbe Anforderung wiederholt zu bedienen. -Mithilfe eines Caching-Servers wie [Varnish](https://www.varnish-cache.org/) oder [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (siehe auch [Nginx Caching](https://serversforhackers.com/nginx-caching/)) lassen sich Geschwindigkeit und Leistung Ihrer Anwendung hervorragend verbessern. +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. ### Load Balancer verwenden -Unabhängig davon, wie gut eine Anwendung optimiert wurde, kann eine Einzelinstanz nur eine begrenzte Arbeitslast oder einen begrenzten Datenverkehr handhaben. Eine Möglichkeit, eine Anwendung zu skalieren, ist die Ausführung mehrerer Instanzen dieser Anwendung und die Verteilung des Datenverkehrs über eine Lastausgleichsfunktion (Load Balancer) vorzunehmen. Die Einrichtung eines solchen Load Balancer kann helfen, Leistung und Geschwindigkeit Ihrer Anwendung zu verbessern. Zudem lässt sich dadurch die Anwendung besser skalieren als mit einer Einzelinstanz. - -Ein Load Balancer ist in der Regel ein Reverse Proxy, der den Datenverkehr zu und von mehreren Anwendungsinstanzen und Servern koordiniert. Sie können ohne großen Aufwand einen Load Balancer für Ihre Anwendung einrichten. Verwenden Sie hierzu [Nginx](http://nginx.org/en/docs/http/load_balancing.html) oder [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). - -Bei einer solchen Lastverteilung müssen Sie sicherstellen, dass Anforderungen, die einer bestimmten Sitzungs-ID zugeordnet sind, mit dem Prozess verbunden sind, von dem sie ursprünglich stammen. Dies wird auch als *Sitzungsaffinität* oder *Affine Sitzungen* bezeichnet und kann durch den obigen Vorschlag, einen Datenspeicher wie Redis für Sitzungsdaten zu verwenden (je nach Anwendung), umgesetzt werden. Eine Beschreibung hierzu siehe [Mehrere Knoten verwenden](https://socket.io/docs/v4/using-multiple-nodes/). +Unabhängig davon, wie gut eine Anwendung optimiert wurde, kann eine Einzelinstanz nur eine begrenzte Arbeitslast oder einen begrenzten Datenverkehr handhaben. Eine Möglichkeit, eine Anwendung zu skalieren, ist die Ausführung mehrerer Instanzen dieser Anwendung und die Verteilung des Datenverkehrs über eine Lastausgleichsfunktion (Load Balancer) vorzunehmen. Die Einrichtung eines solchen Load Balancer kann helfen, Leistung und Geschwindigkeit Ihrer Anwendung zu verbessern. -#### StrongLoop Process Manager mit einem Nginx Load Balancer verwenden +Ein Load Balancer ist in der Regel ein Reverse Proxy, der den Datenverkehr zu und von mehreren Anwendungsinstanzen und Servern koordiniert. 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). -[StrongLoop Process Manager](http://strong-pm.io/) lässt sich in einen Nginx-Controller integrieren und erleichtert dadurch das Konfigurieren von Produktionsumgebungen mit mehreren Hosts. Weitere Informationen finden Sie im Thema zum [Skalieren auf mehrere Server](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers) (in der StrongLoop-Dokumentation). - +Bei einer solchen Lastverteilung müssen Sie sicherstellen, dass Anforderungen, die einer bestimmten Sitzungs-ID zugeordnet sind, mit dem Prozess verbunden sind, von dem sie ursprünglich stammen. Dies wird auch als _Sitzungsaffinität_ oder _Affine Sitzungen_ bezeichnet und kann durch den obigen Vorschlag, einen Datenspeicher wie Redis für Sitzungsdaten zu verwenden (je nach Anwendung), umgesetzt werden. Eine Beschreibung hierzu siehe [Mehrere Knoten verwenden](https://socket.io/docs/v4/using-multiple-nodes/). ### Reverse Proxy verwenden -Ein Reverse Proxy befindet sich vor einer Webanwendung und führt Unterstützungsoperationen für die Anforderungen aus (außer das Weiterleiten von Anforderungen an die Anwendung). Er kann u. a. Fehlerseiten, Komprimierungen und Caching bearbeiten, Dateien bereitstellen und Lastverteilungen vornehmen. +Ein Reverse Proxy befindet sich vor einer Webanwendung und führt Unterstützungsoperationen für die Anforderungen aus (außer das Weiterleiten von Anforderungen an die Anwendung). Fehlerseiten, Komprimierungen und Caching bearbeiten, Dateien bereitstellen und Lastverteilungen vornehmen. -Durch die Übergabe von Tasks, die keine Kenntnis des Anwendungsstatus erfordern, an einen Reverse Proxy muss Express keine speziellen Anwendungstasks mehr ausführen. Aus diesem Grund wird empfohlen, in Produktionsumgebungen Express hinter einem Reverse Proxy wie [Nginx](https://www.nginx.com/) oder [HAProxy](http://www.haproxy.org/) auszuführen. +Durch die Übergabe von Tasks, die keine Kenntnis des Anwendungsstatus erfordern, an einen Reverse Proxy muss Express keine speziellen Anwendungstasks mehr ausführen. 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. diff --git a/de/advanced/best-practice-security.md b/de/advanced/best-practice-security.md old mode 100755 new mode 100644 index db0a1c2efb..54ca976e7d --- a/de/advanced/best-practice-security.md +++ b/de/advanced/best-practice-security.md @@ -4,18 +4,44 @@ title: Sicherheitsspezifische Best Practices für Express-Anwendungen in Produkt description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: de +redirect_from: " " --- # Best Practices in Produktionsumgebungen: Sicherheit ## Überblick -Der Begriff *"Produktion"* bezieht sich auf die Phase im Softwarelebenszyklus, in der eine Anwendung oder API für Endbenutzer oder Verbraucher allgemein verfügbar ist. Im Gegensatz dazu wird in der Phase *"Entwicklung"* noch aktiv Code geschrieben und getestet. Die Anwendung ist in dieser Phase noch nicht für externen Zugriff verfügbar. Die entsprechenden Systemumgebungen werden als *Produktionsumgebungen* und *Entwicklungsumgebungen* bezeichnet. +Der Begriff _"Produktion"_ bezieht sich auf die Phase im Softwarelebenszyklus, in der eine Anwendung oder API für Endbenutzer oder Verbraucher allgemein verfügbar ist. Im Gegensatz dazu wird in der Phase _"Entwicklung"_ noch aktiv Code geschrieben und getestet. Die Anwendung ist in dieser Phase noch nicht für externen Zugriff verfügbar. Die entsprechenden Systemumgebungen werden als _Produktionsumgebungen_ und _Entwicklungsumgebungen_ bezeichnet. Entwicklungs- und Produktionsumgebungen werden in der Regel unterschiedlich konfiguriert und weisen deutliche Unterschiede bei den Anforderungen auf. Was in der Entwicklung funktioniert, muss in der Produktion nicht unbedingt akzeptabel sein. Beispiel: In einer Entwicklungsumgebung ist eine ausführliche Protokollierung von Fehlern für Debuggingzwecke sinnvoll. Dieselbe Vorgehensweise kann in einer Produktionsumgebung jedoch zu einem Sicherheitsproblem führen. In einer Entwicklungsumgebung müssen Sie sich keine Gedanken zu Themen wie Skalierbarkeit, Zuverlässigkeit und Leistung machen, während dies in einer Produktionsumgebung kritische Faktoren sind. +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + In diesem Beitrag werden einige der Best Practices in Bezug auf das Thema Sicherheit für Express-Anwendungen behandelt, die in der Produktionsumgebung bereitgestellt werden. +- [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) + - Über [hsts](https://github.com/helmetjs/hsts) werden `Strict-Transport-Security`-Header festgelegt, über die sichere (HTTP over SSL/TLS) Verbindungen zum Server durchgesetzt werden. + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - "Helmet" ist eine Ansammlung von neun kleineren Middlewarefunktionen, über die sicherheitsrelevante HTTP-Header festgelegt werden. + - [Reduce fingerprinting](#reduce-fingerprinting) + - Über [xssFilter](https://github.com/helmetjs/x-xss-protection) werden `X-XSS-Protection`-Header festgelegt, um XSS-Filter (Cross-site Scripting) in den meisten aktuellen Web-Browsern zu aktivieren. + - Über [noCache](https://github.com/helmetjs/nocache) werden `Cache-Control`- und Pragma-Header festgelegt, um clientseitiges Caching zu deaktivieren. + - Über [ieNoOpen](https://github.com/helmetjs/ienoopen) werden `X-Download-Options`-Header für IE8+ festgelegt. + - [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) + ## Verwenden Sie keine veralteten oder anfälligen Versionen von Express Express 2.x und 3.x werden nicht mehr gepflegt. Sicherheits- und Leistungsprobleme in diesen Versionen werden nicht mehr behoben. Verwenden Sie diese Versionen nicht! Wenn Sie noch nicht auf Version 4 umgestellt haben, befolgen Sie die Anweisungen im [Migrationshandbuch](/{{ page.lang }}/guide/migrating-4.html). @@ -26,45 +52,83 @@ Stellen Sie außerdem sicher, dass Sie keine anfälligen Express-Versionen verwe Wenn über Ihre Anwendung vertrauliche Daten bearbeitet oder übertragen werden, sollten Sie [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) verwenden, um die Verbindung und die Daten zu schützen. Diese Technologie verschlüsselt Daten, bevor sie vom Client zum Server gesendet werden. Dadurch lassen sich einige gängige (und einfache) Hackerattacken vermeiden. Auch wenn Ajax- und POST-Anforderungen nicht sofort offensichtlich und in Browsern "versteckt" zu sein scheinen, ist deren Netzverkehr anfällig für das [Ausspionieren von Paketen](https://en.wikipedia.org/wiki/Packet_analyzer) und [Man-in-the-Middle-Attacken](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). -Möglicherweise sind Sie mit SSL-Verschlüsselung (Secure Socket Layer) bereits vertraut. [TLS ist einfach der nächste Entwicklungsschritt bei SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). In anderen Worten: Wenn Sie bisher SSL verwendet haben, sollten Sie ein Upgrade auf TLS in Erwägung ziehen. Generell empfehlen wir für TLS den Nginx-Server. Eine gute Referenz zum Konfigurieren von TLS auf Nginx (und anderen Servern) ist [Empfohlene Serverkonfigurationen (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). +Möglicherweise sind Sie mit SSL-Verschlüsselung (Secure Socket Layer) bereits vertraut. [TLS ist einfach der nächste Entwicklungsschritt bei SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). In anderen Worten: Wenn Sie bisher SSL verwendet haben, sollten Sie ein Upgrade auf TLS in Erwägung ziehen. Generell empfehlen wir für TLS den Nginx-Server. Eine gute Referenz zum Konfigurieren von TLS auf Nginx (und anderen Servern) ist [Empfohlene Serverkonfigurationen (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). Ein handliches Tool zum Abrufen eines kostenloses TLS-Zertifikats ist außerdem [Let's Encrypt](https://letsencrypt.org/about/), eine kostenlose, automatisierte und offene Zertifizierungsstelle der [Internet Security Research Group (ISRG)](https://letsencrypt.org/isrg/). +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## "Helmet" verwenden [Helmet](https://www.npmjs.com/package/helmet) kann beim Schutz Ihrer Anwendung gegen einige gängige Schwachstellen hilfreiche Dienste leisten, indem die HTTP-Header entsprechend konfiguriert werden. -"Helmet" ist eine Ansammlung von neun kleineren Middlewarefunktionen, über die sicherheitsrelevante HTTP-Header festgelegt werden. +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: -* Über [csp](https://github.com/helmetjs/csp) wird der `Content-Security-Policy`-Header festgelegt, um Cross-Site Scripting-Attacken und anderen standortübergreifenden Injektionen vorzubeugen. -* Über [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) wird der `X-Powered-By`-Header entfernt. -* Über [hsts](https://github.com/helmetjs/hsts) werden `Strict-Transport-Security`-Header festgelegt, über die sichere (HTTP over SSL/TLS) Verbindungen zum Server durchgesetzt werden. -* Über [ieNoOpen](https://github.com/helmetjs/ienoopen) werden `X-Download-Options`-Header für IE8+ festgelegt. -* Über [noCache](https://github.com/helmetjs/nocache) werden `Cache-Control`- und Pragma-Header festgelegt, um clientseitiges Caching zu deaktivieren. -* Über [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) werden `X-Content-Type-Options`-Header festgelegt, um bei Browsern MIME-Sniffing von Antworten weg vom deklarierten Inhaltstyp (declared content-type) vorzubeugen. -* Über [frameguard](https://github.com/helmetjs/frameguard) wird der `X-Frame-Options`-Header festgelegt, um [Clickjacking](https://www.owasp.org/index.php/Clickjacking)-Schutz zu gewährleisten. -* Über [xssFilter](https://github.com/helmetjs/x-xss-protection) werden `X-XSS-Protection`-Header festgelegt, um XSS-Filter (Cross-site Scripting) in den meisten aktuellen Web-Browsern zu aktivieren. +- `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 +- `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 +- `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 + +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Installieren Sie "Helmet" wie alle anderen Module: ```bash -$ npm install --save helmet +$ npm install helmet ``` So verwenden Sie "Helmet" in Ihrem Code: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### Deaktivieren Sie mindestens den X-Powered-By-Header +## Reduce fingerprinting -Wenn Sie "Helmet" nicht verwenden wollen, sollten Sie mindestens den `X-Powered-By`-Header deaktivieren. Angreifer können diesen Header (der standardmäßig aktiviert ist) zum Erkennen von Anwendungen mit Express verwenden und dann gezielte Attacken in die Wege leiten. +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. Ein bewährtes Verfahren ist also, diesen Header mit der Methode `app.disable()` zu deaktivieren: @@ -72,7 +136,37 @@ Ein bewährtes Verfahren ist also, diesen Header mit der Methode `app.disable()` app.disable('x-powered-by') ``` -Wenn Sie `helmet.js` verwenden, kümmert sich das Tool darum. +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## Cookies sicher verwenden @@ -80,8 +174,8 @@ Um sicherzustellen, dass Cookies Ihre Anwendung nicht für Angriffsmöglichkeite Es gibt zwei wesentliche Middleware-Cookie-Sitzungsmodule: -* [express-session](https://www.npmjs.com/package/express-session), das in Express 3.x integrierte `express.session`-Middleware ersetzt. -* [cookie-session](https://www.npmjs.com/package/cookie-session), das in Express 3.x integrierte `express.cookieSession`-Middleware ersetzt. +- [express-session](https://www.npmjs.com/package/express-session), das in Express 3.x integrierte `express.session`-Middleware ersetzt. +- [cookie-session](https://www.npmjs.com/package/cookie-session), das in Express 3.x integrierte `express.cookieSession`-Middleware ersetzt. Der Hauptunterschied zwischen diesen beiden Modulen liegt darin, wie die Cookie-Sitzungsdaten gespeichert werden. Die [express-session](https://www.npmjs.com/package/express-session)-Middleware speichert Sitzungsdaten auf dem Server. Sie speichert nur die Sitzungs-ID im Cookie und nicht die Sitzungsdaten. Standardmäßig wird dabei der speicherinterne Speicher verwendet. Eine Verwendung der Middleware in der Produktionsumgebung ist nicht vorgesehen. In der Produktionsumgebung müssen Sie einen skalierbaren "Session-Store" einrichten. Siehe hierzu die Liste der [kompatiblen Session-Stores](https://github.com/expressjs/session#compatible-session-stores). @@ -91,7 +185,7 @@ Im Gegensatz dazu implementiert die [cookie-session](https://www.npmjs.com/packa Die Verwendung des standardmäßigen Namens des Sitzungscookies kann Ihre Anwendung anfällig für Attacken machen. Das mögliche Sicherheitsproblem ist vergleichbar mit `X-Powered-By`: ein potenzieller Angreifer kann diesen Header verwenden, um einen elektronischen Fingerabdruck des Servers zu erstellen und Attacken entsprechend zu platzieren. -Dieses Problem lässt sich vermeiden, wenn Sie allgemeine Cookienamen verwenden; z. B. durch Verwendung der [express-session](https://www.npmjs.com/package/express-session)-Middleware: +Über [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) werden `X-Content-Type-Options`-Header festgelegt, um bei Browsern MIME-Sniffing von Antworten weg vom deklarierten Inhaltstyp (declared content-type) vorzubeugen. ```js const session = require('express-session') @@ -99,19 +193,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### Cookie-Sicherheitsoptionen festlegen Legen Sie die folgenden Cookieoptionen fest, um die Sicherheit zu erhöhen: -* `secure` - Stellt sicher, dass der Browser das Cookie nur über HTTPS sendet. -* `httpOnly` - Stellt sicher, dass das Cookie nur über HTTP(S) und nicht über das Client-JavaScript gesendet wird und dadurch Schutz gegen Cross-Site Scripting-Attacken besteht. -* `domain` - Gibt die Domäne des Cookies an, die für den Vergleich mit der Domäne des Servers verwendet wird, in der die URL angefordert wird. Stimmen diese beiden überein, müssen Sie das Pfadattribut überprüfen. -* `path` - Gibt den Pfad des Cookies an, der für den Vergleich mit dem Anforderungspfad verwendet wird. Wenn dieser Pfad und die Domäne übereinstimmen, können Sie das Cookie in der Anforderung senden. -* `expires` - Wird verwendet, um das Ablaufdatum für persistente Cookies festzulegen. +- `secure` - Stellt sicher, dass der Browser das Cookie nur über HTTPS sendet. +- `httpOnly` - Stellt sicher, dass das Cookie nur über HTTP(S) und nicht über das Client-JavaScript gesendet wird und dadurch Schutz gegen Cross-Site Scripting-Attacken besteht. +- `domain` - Gibt die Domäne des Cookies an, die für den Vergleich mit der Domäne des Servers verwendet wird, in der die URL angefordert wird. Stimmen diese beiden überein, müssen Sie das Pfadattribut überprüfen. +- `path` - Gibt den Pfad des Cookies an, der für den Vergleich mit dem Anforderungspfad verwendet wird. Wenn dieser Pfad und die Domäne übereinstimmen, können Sie das Cookie in der Anforderung senden. +- `expires` - Wird verwendet, um das Ablaufdatum für persistente Cookies festzulegen. Dies ist ein Beispiel zur Verwendung der [cookie-session](https://www.npmjs.com/package/cookie-session)-Middleware: @@ -131,23 +224,59 @@ app.use(session({ path: 'foo/bar', expires: expiryDate } -}) -) +})) ``` -## Weitere Überlegungen +## 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. + +[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) + +## 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. + +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` + +If you want to stay more secure, consider [Snyk](https://snyk.io/). -Dies sind einige weitere Empfehlungen aus der hervorragenden [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). In diesem Blogbeitrag finden Sie alle Details zu diesen Empfehlungen: +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: -* Implementieren Sie Rate-Limiting, um Brute-Force-Attacken gegen Authentifizierungen zu verhindern. Hierfür können Sie beispielsweise das [StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) verwenden, um eine Rate-Limiting-Richtlinie durchzusetzen. Alternativ können Sie eine Middleware wie [express-limiter](https://www.npmjs.com/package/express-limiter) verwenden. Hierzu müssen Sie jedoch Ihren Code etwas modifizieren. -* Filtern und bereinigen Sie immer Benutzereingaben, um sich gegen XS-Angriffe (Cross-Site Scripting) und Befehlsinjektionsattacken zu schützen. -* Implementieren Sie Verteidungsmaßnahmen gegen SQL-Injection-Attacken, indem sie parametrisierte Abfragen oder vorbereitete Anweisungen einsetzen. -* Nutzen Sie das Open-Source-Tool [sqlmap](http://sqlmap.org/), um SQL-Injection-Schwachstellen in Ihrer Anwendung zu erkennen. -* Verwenden Sie die Tools [nmap](https://nmap.org/) und [sslyze](https://github.com/nabla-c0d3/sslyze), um die Konfiguration Ihrer SSL-Verschlüsselungen, -Schlüssel und Neuvereinbarungen sowie die Gültigkeit Ihres Zertifikats zu testen. -* Verwenden Sie [safe-regex](https://www.npmjs.com/package/safe-regex), um sicherzustellen, dass Ihre regulären Ausdrücke nicht für [Denial-of-Service-Attacken](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) anfällig sind. +```bash +$ npm install -g snyk +$ cd your-app +``` -## Vermeiden Sie andere Schwachstellen +Use this command to test your application for vulnerabilities: + +```bash +$ snyk test +``` + +### Vermeiden Sie andere Schwachstellen Achten Sie auf [Node Security Project](https://npmjs.com/advisories)-Empfehlungen, die Express oder andere Module, die Ihre Anwendung nutzt, beeinträchtigen können. Im Allgemeinen ist Node Security Project aber eine exzellente Ressource mit Wissen und Tools zur Sicherheit von Node. Letztendlich können Express-Anwendungen – wie viele andere Webanwendungen auch – anfällig für eine Vielzahl webbasierter Attacken sein. Machen Sie sich deshalb mit bekannten [webspezifischen Schwachstellen](https://www.owasp.org/www-project-top-ten/) vertraut und treffen Sie die geeigneten Vorkehrungen, um diese zu vermeiden. + +## Weitere Überlegungen + +Dies sind einige weitere Empfehlungen aus der hervorragenden [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). In diesem Blogbeitrag finden Sie alle Details zu diesen Empfehlungen: + +- Filtern und bereinigen Sie immer Benutzereingaben, um sich gegen XS-Angriffe (Cross-Site Scripting) und Befehlsinjektionsattacken zu schützen. +- Implementieren Sie Verteidungsmaßnahmen gegen SQL-Injection-Attacken, indem sie parametrisierte Abfragen oder vorbereitete Anweisungen einsetzen. +- Nutzen Sie das Open-Source-Tool [sqlmap](http://sqlmap.org/), um SQL-Injection-Schwachstellen in Ihrer Anwendung zu erkennen. +- Verwenden Sie die Tools [nmap](https://nmap.org/) und [sslyze](https://github.com/nabla-c0d3/sslyze), um die Konfiguration Ihrer SSL-Verschlüsselungen, -Schlüssel und Neuvereinbarungen sowie die Gültigkeit Ihres Zertifikats zu testen. +- Verwenden Sie [safe-regex](https://www.npmjs.com/package/safe-regex), um sicherzustellen, dass Ihre regulären Ausdrücke nicht für [Denial-of-Service-Attacken](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) anfällig sind. + +[helmet]: \ No newline at end of file diff --git a/de/advanced/developing-template-engines.md b/de/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 309e2d1b66..dd42f55a90 --- a/de/advanced/developing-template-engines.md +++ b/de/advanced/developing-template-engines.md @@ -4,6 +4,7 @@ title: Template-Engines für Express entwickeln 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. menu: advanced lang: de +redirect_from: " " --- # Template-Engines für Express entwickeln @@ -16,9 +17,10 @@ Der folgende Code ist ein Beispiel für die Implementierung einer sehr einfachen const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) @@ -33,10 +35,13 @@ Ihre Anwendung ist jetzt in der Lage, `.ntl`-Dateien auszugeben. Erstellen Sie i #title# #message# ``` + Erstellen Sie dann in Ihrer Anwendung die folgende Route. + ```js app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -Wenn Sie eine Anforderung zur Homepage einleiten, wird `index.ntl` im HTML-Format ausgegeben. + +Wenn Sie eine Anforderung zur Homepage einleiten, wird `index.ntl` im HTML-Format ausgegeben. \ No newline at end of file diff --git a/de/advanced/healthcheck-graceful-shutdown.md b/de/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..34085a504f --- /dev/null +++ b/de/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: de +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### Beispiel + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/de/advanced/security-updates.md b/de/advanced/security-updates.md old mode 100755 new mode 100644 index ec7bab2ba3..3b573ae521 --- a/de/advanced/security-updates.md +++ b/de/advanced/security-updates.md @@ -4,6 +4,7 @@ title: Express-Sicherheitsupdates description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: de +redirect_from: " " --- # Sicherheitsupdates @@ -15,32 +16,73 @@ Schwachstellen bei Node.js wirken sich direkt auf Express aus. Daher sollten Sie Die folgende Liste enthält die Express-Schwachstellen, die im angegebenen Versionsupdate behoben wurden. +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * Offenlegungsgefahr beim Rootpfad in `express.static`, `res.sendfile` und `res.sendFile` behoben. - * 4.10.7 - * Offene Umadressierungsschwachstelle in `express.static` ([Empfehlung](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)) behoben. - * 4.8.8 - * Schwachstellen durch Directory-Traversal-Technik in `express.static` ([Empfehlung](http://npmjs.com/advisories/32) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)) behoben. - * 4.8.4 - * Node.js 0.10 kann in bestimmten Situationen Lecks bei `fd` aufweisen, die sich auf `express.static` und `res.sendfile` auswirken. Böswillige Anforderungen können zu Lecks bei `fd` führen und letztendlich `EMFILE`-Fehler nach sich ziehen und bewirken, dass Server nicht antworten. - * 4.8.0 - * Sparse-Arrays mit extrem hohen Indizes in der Abfragezeichenfolge können bewirken, dass für die Prozessausführung nicht genügend Arbeitsspeicher zur Verfügung steht und es zu einem Serverabsturz kommt. - * Extrem verschachtelte Abfragezeichenfolgenobjekte können bewirken, dass der Prozess blockiert und der Server dadurch vorübergehend nicht antwortet. +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - Offenlegungsgefahr beim Rootpfad in `express.static`, `res.sendfile` und `res.sendFile` behoben. +- 4.10.7 + - Offene Umadressierungsschwachstelle in `express.static` ([Empfehlung](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)) behoben. +- 4.8.8 + - Schwachstellen durch Directory-Traversal-Technik in `express.static` ([Empfehlung](http://npmjs.com/advisories/32) , [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)) behoben. +- 4.8.4 + - Node.js 0.10 kann in bestimmten Situationen Lecks bei `fd` aufweisen, die sich auf `express.static` und `res.sendfile` auswirken. Böswillige Anforderungen können zu Lecks bei `fd` führen und letztendlich `EMFILE`-Fehler nach sich ziehen und bewirken, dass Server nicht antworten. +- 4.8.0 + - Sparse-Arrays mit extrem hohen Indizes in der Abfragezeichenfolge können bewirken, dass für die Prozessausführung nicht genügend Arbeitsspeicher zur Verfügung steht und es zu einem Serverabsturz kommt. + - Extrem verschachtelte Abfragezeichenfolgenobjekte können bewirken, dass der Prozess blockiert und der Server dadurch vorübergehend nicht antwortet. ## 3.x - * 3.19.1 - * Offenlegungsgefahr beim Rootpfad in `express.static`, `res.sendfile` und `res.sendFile` behoben. - * 3.19.0 - * Offene Umadressierungsschwachstelle in `express.static` ([Empfehlung](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)) behoben. - * 3.16.10 - * Schwachstellen durch Directory-Traversal-Technik in `express.static` behoben. - * 3.16.6 - * Node.js 0.10 kann in bestimmten Situationen Lecks bei `fd` aufweisen, die sich auf `express.static` und `res.sendfile` auswirken. Böswillige Anforderungen können zu Lecks bei `fd` führen und letztendlich `EMFILE`-Fehler nach sich ziehen und bewirken, dass Server nicht antworten. - * 3.16.0 - * Sparse-Arrays mit extrem hohen Indizes in der Abfragezeichenfolge können bewirken, dass für die Prozessausführung nicht genügend Arbeitsspeicher zur Verfügung steht und es zu einem Serverabsturz kommt. - * Extrem verschachtelte Abfragezeichenfolgenobjekte können bewirken, dass der Prozess blockiert und der Server dadurch vorübergehend nicht antwortet. - * 3.3.0 - * Die Antwort 404 bei einem nicht unterstützten Überschreibungsversuch war anfällig gegen Cross-Site Scripting-Attacken. +
+ **Express 3.x WIRD NICHT MEHR GEWARTET** + +Bekannte und unbekannte Probleme bei Sicherheit und Leistung in 3.x wurden seit dem letzten Update (1. August 2015) noch nicht behoben. Es wird dringend empfohlen, die aktuelle Version von Express zu verwenden. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
+ +- 3.19.1 + - Offenlegungsgefahr beim Rootpfad in `express.static`, `res.sendfile` und `res.sendFile` behoben. +- 3.19.0 + - Offene Umadressierungsschwachstelle in `express.static` ([Empfehlung](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)) behoben. +- 3.16.10 + - Schwachstellen durch Directory-Traversal-Technik in `express.static` behoben. +- 3.16.6 + - Node.js 0.10 kann in bestimmten Situationen Lecks bei `fd` aufweisen, die sich auf `express.static` und `res.sendfile` auswirken. Böswillige Anforderungen können zu Lecks bei `fd` führen und letztendlich `EMFILE`-Fehler nach sich ziehen und bewirken, dass Server nicht antworten. +- 3.16.0 + - Sparse-Arrays mit extrem hohen Indizes in der Abfragezeichenfolge können bewirken, dass für die Prozessausführung nicht genügend Arbeitsspeicher zur Verfügung steht und es zu einem Serverabsturz kommt. + - Extrem verschachtelte Abfragezeichenfolgenobjekte können bewirken, dass der Prozess blockiert und der Server dadurch vorübergehend nicht antwortet. +- 3.3.0 + - Die Antwort 404 bei einem nicht unterstützten Überschreibungsversuch war anfällig gegen Cross-Site Scripting-Attacken. \ No newline at end of file diff --git a/de/api.md b/de/api.md old mode 100755 new mode 100644 index 1891b944f7..1b091208fc --- a/de/api.md +++ b/de/api.md @@ -1,26 +1,21 @@ --- -layout: 4x-api -title: Express 4.x - API-Referenz +layout: api +version: 5x +title: Express 5.x - API-Referenz description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: de +redirect_from: " " --- -
- -

4.x-API

- - - {% include api/en/4x/express.md %} +
+

5.x API

+ {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
diff --git a/de/changelog/index.md b/de/changelog/index.md new file mode 100644 index 0000000000..4bd4edc3ab --- /dev/null +++ b/de/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: de +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
+ +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
    +
  • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
    +
  • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
    +
  • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
    +
  • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
  • + +
  • + Starting with this version, Express supports Node.js 18.x. +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
  • + +
  • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
  • + +
  • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
  • + +
  • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
  • + +
  • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
    +
  • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
    +
  • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
  • + +
  • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
  • + +
  • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
  • + +
  • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
  • + +
  • + Starting with this version, Express supports Node.js 14.x. +
  • + +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
    +
  • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
    +
  • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
  • + +
  • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
  • + +
  • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
  • + +
  • + Starting with this version, Express supports Node.js 10.x and 12.x. +
  • + +
  • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
  • + +
  • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
    +
  • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
    +
  • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
  • + +
  • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
  • + +
  • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
    +
  • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
    +
  • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
    +
  • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
  • + +
  • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
  • + +
  • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
  • + +
  • + Starting with this version, Express supports Node.js 8.x. +
  • + +
  • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
  • + +
  • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
  • + +
  • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
  • + +
  • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
    +
  • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
  • + +
  • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
  • + +
  • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
    +
  • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
    +
  • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
  • + +
  • + Fix error when `res.set` cannot add charset to `Content-Type`. +
  • + +
  • + Fix missing `` in HTML document. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
    +
  • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
    +
  • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
    +
  • + Starting with this version, Express supports Node.js 7.x. +
  • + +
  • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
  • + +
  • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
  • + +
  • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
    +
  • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
    +
  • + Starting with this version, Express supports Node.js 6.x. +
  • + +
  • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
  • + +
  • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
  • + +
  • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
  • + +
  • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
  • + +
  • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
  • + +
  • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
  • + +
  • + IP address resolution with proxies has been greatly improved. +
  • + +
  • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
diff --git a/de/guide/behind-proxies.md b/de/guide/behind-proxies.md old mode 100755 new mode 100644 index 22e81dda3b..6e8dfbcdcb --- a/de/guide/behind-proxies.md +++ b/de/guide/behind-proxies.md @@ -4,33 +4,41 @@ title: Express hinter Proxys 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. menu: guide lang: de +redirect_from: " " --- # Express hinter Proxys -Bei der Ausführung einer Express-Anwendung hinter einem Proxy legen Sie die Anwendungsvariable `trust proxy` (mithilfe von [app.set()](/{{ page.lang }}/4x/api.html#app.set)) auf einen der in der folgenden Tabelle enthaltenen Werte fest: +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.
-Auch wenn die Anwendungsausführung nicht fehlschlägt, wenn die Anwendungsvariable `trust proxy` nicht festgelegt wurde, wird die IP-Adresse des Proxys nicht ordnungsgemäß als Client-IP-Adresse eingetragen, es sei denn, `trust proxy` wurde konfiguriert. +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.
+Bei der Ausführung einer Express-Anwendung hinter einem Proxy legen Sie die Anwendungsvariable `trust proxy` (mithilfe von [app.set()](/{{ page.lang }}/4x/api.html#app.set)) auf einen der in der folgenden Tabelle enthaltenen Werte fest: + - - + - +
TypWert
Boolesch -Wenn `true` angegeben wird, wird die IP-Adresse des Clients als der äußerst rechte Eintrag im Header `X-Forwarded-*` interpretiert. +Wenn `true` angegeben wird, wird die IP-Adresse des Clients als der äußerst rechte Eintrag im Header `X-Forwarded-*` interpretiert. + Wenn `false` angegeben wird, wird die Anwendung als direkte Verbindung zum Internet gesehen. Die IP-Adresse des Clients wird dann von `req.connection.remoteAddress` abgeleitet. Dies ist die Standardeinstellung. + +
+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. +
IP-AdressenIP addresses -Eine einzelne IP-Adresse, ein Teilnetz oder ein Array von IP-Adressen und Teilnetzen, denen vertraut werden kann. Die folgende Liste zeigt die vorkonfigurierten Teilnetznamen: -* 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`. +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: + +- 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` Sie können IP-Adressen wie folgt festlegen: @@ -41,19 +49,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -Sobald die Werte angegeben wurden, werden die betreffenden IP-Adressen und Teilnetze aus dem Adressfeststellungsprozess ausgeschlossen. Die nicht vertrauenswürdige IP-Adresse, die am nächsten zum Anwendungsserver liegt, wird als IP-Adresse des Clients festgelegt. +Sobald die Werte angegeben wurden, werden die betreffenden IP-Adressen und Teilnetze aus dem Adressfeststellungsprozess ausgeschlossen. Die nicht vertrauenswürdige IP-Adresse, die am nächsten zum Anwendungsserver liegt, wird als IP-Adresse des Clients festgelegt. 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. +
Zahl -Dem `n`-ten Hop vom Proxy-Server soll als Client vertraut werden. +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. + +
+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. +
FunktionFunction -Individuell angepasste, vertrauenswürdige Implementierung. Dies sollten Sie nur verwenden, wenn Sie genau wissen, was Sie tun. +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -61,16 +74,16 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
-Die Festlegung eines anderen `trust proxy`-Werts als `false` resultiert in drei wichtigen Änderungen: +Enabling `trust proxy` will have the following impact:
    -
  • Der Wert für [req.hostname](/{{ page.lang }}/api.html#req.hostname) wird vom Wert abgeleitet, der im Header `X-Forwarded-Host` festgelegt wurde. Dieser Wert kann vom Client oder Proxy festgelegt werden. -
  • +
  • Der Wert für [req.hostname](/{{ page.lang }}/api.html#req.hostname) wird vom Wert abgeleitet, der im Header `X-Forwarded-Host` festgelegt wurde. Dieser Wert kann vom Client oder Proxy festgelegt werden.
  • `X-Forwarded-Proto` kann vom Reverse Proxy festgelegt werden, um der Anwendung mitzuteilen, ob es sich um `https` oder `http` oder sogar um einen ungültigen Namen handelt. Dieser Wert wird durch [req.protocol](/{{ page.lang }}/api.html#req.protocol) abgebildet.
  • Als Werte für [req.ip](/{{ page.lang }}/api.html#req.ip) und [req.ips](/{{ page.lang }}/api.html#req.ips) wird die Liste der Adressen aus `X-Forwarded-For` herangezogen. diff --git a/de/guide/database-integration.md b/de/guide/database-integration.md old mode 100755 new mode 100644 index 068ff957c2..f02a7bfee5 --- a/de/guide/database-integration.md +++ b/de/guide/database-integration.md @@ -4,211 +4,264 @@ title: Datenbankintegration in Express description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: de +redirect_from: " " --- # Datenbankintegration Die Herstellung einer Verbindung zwischen Datenbanken und Express-Anwendungen erfolgt einfach durch Laden eines geeigneten Node.js-Treibers für die Datenbank in Ihre Anwendung. In diesem Dokument wird in Kurzform beschrieben, wie einige der gängigsten Node.js-Module für Datenbanksysteme Ihrer Express-Anwendung hinzugefügt und verwendet werden: -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
    Diese Datenbanktreiber sind neben zahlreichen anderen Treibern verfügbar. Weitere Optionen finden Sie auf der [npm](https://www.npmjs.com/)-Site.
    - - ## Cassandra **Modul**: [cassandra-driver](https://github.com/datastax/nodejs-driver) **Installation** +### Installation + ```bash $ npm install cassandra-driver ``` -**Beispiel** +### Beispiel + +```js +const cassandra = require('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 -
    -
    -var cassandra = require('cassandra-driver');
    -var client = new cassandra.Client({ contactPoints: ['localhost']});
    +```bash
    +$ npm install couchbase
    +```
     
    -client.execute('select key from system.local', function(err, result) {
    -  if (err) throw err;
    -  console.log(result.rows[0]);
    -});
    -
    -
    +### Beispiel - +```js +const couchbase = require('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) **Installation** +### Installation + ```bash $ npm install nano ``` -**Beispiel** +### Beispiel -
    -
    -var nano = require('nano')('http://localhost:5984');
    -nano.db.create('books');
    -var books = nano.db.use('books');
    +```js
    +const nano = require('nano')('http://localhost:5984')
    +nano.db.create('books')
    +const books = nano.db.use('books')
     
    -//Insert a book document in the books database
    -books.insert({name: 'The Art of war'}, null, function(err, body) {
    -  if (!err){
    -    console.log(body);
    +// Insert a book document in the books database
    +books.insert({ name: 'The Art of war' }, null, (err, body) => {
    +  if (err) {
    +    console.log(err)
    +  } else {
    +    console.log(body)
       }
    -});
    +})
     
    -//Get a list of all books
    -books.list(function(err, body){
    -  console.log(body.rows);
    -});
    -
    -
    - - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **Modul**: [levelup](https://github.com/rvagg/node-levelup) **Installation** +### Installation + ```bash $ npm install level levelup leveldown ``` -**Beispiel** - -
    -
    -var levelup = require('levelup');
    -var db = levelup('./mydb');
    +### Beispiel
     
    -db.put('name', 'LevelUP', function (err) {
    +```js
    +const levelup = require('levelup')
    +const db = levelup('./mydb')
     
    -  if (err) return console.log('Ooops!', err);
    -  db.get('name', function (err, value) {
    -    if (err) return console.log('Ooops!', err);
    -    console.log('name=' + value);
    -  });
    +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/) **Installation** +### Installation + ```bash $ npm install mysql ``` -**Beispiel** +### Beispiel -
    -
    -var mysql      = require('mysql');
    -var connection = mysql.createConnection({
    -  host     : 'localhost',
    -  user     : 'dbuser',
    -  password : 's3kreee7'
    -});
    +```js
    +const mysql = require('mysql')
    +const connection = mysql.createConnection({
    +  host: 'localhost',
    +  user: 'dbuser',
    +  password: 's3kreee7',
    +  database: 'my_db'
    +})
     
    -connection.connect();
    +connection.connect()
     
    -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
    -  if (err) throw err;
    -  console.log('The solution is: ', rows[0].solution);
    -});
    +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
    +  if (err) throw err
     
    -connection.end();
    -
    -
    + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **Modul**: [mongodb](https://github.com/mongodb/node-mongodb-native) **Installation** +### Installation + ```bash $ npm install mongodb ``` -**Beispiel** +### Example (v2.\*) -
    -
    -var MongoClient = require('mongodb').MongoClient;
    +```js
    +const MongoClient = require('mongodb').MongoClient
     
    -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
    -  if (err) {
    -    throw err;
    -  }
    -  db.collection('mammals').find().toArray(function(err, result) {
    -    if (err) {
    -      throw err;
    -    }
    -    console.log(result);
    -  });
    -});
    -
    -
    +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err -Wenn Sie nach einem Objektmodelltreiber für MongoDB suchen, schauen Sie unter [Mongoose](https://github.com/LearnBoost/mongoose) nach. + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err - + console.log(result) + }) +}) +``` + +### Example (v3.\*) + +```js +const MongoClient = require('mongodb').MongoClient + +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err + + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +Wenn Sie nach einem Objektmodelltreiber für MongoDB suchen, schauen Sie unter [Mongoose](https://github.com/LearnBoost/mongoose) nach. ## Neo4j -**Modul**: [apoc](https://github.com/hacksparrow/apoc) -**Installation** +**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver) + +### Installation ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**Beispiel** +### Beispiel -
    -
    -var apoc = require('apoc');
    +```js
    +const neo4j = require('neo4j-driver')
    +const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
     
    -apoc.query('match (n) return n').exec().then(
    -  function (response) {
    -    console.log(response);
    -  },
    -  function (fail) {
    -    console.log(fail);
    -  }
    -);
    -
    -
    +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 @@ -256,129 +309,182 @@ async function getEmployee (empId) { getEmployee(101) ``` - - ## PostgreSQL **Modul**: [pg-promise](https://github.com/vitaly-t/pg-promise) **Installation** +### Installation + ```bash $ npm install pg-promise ``` -**Beispiel** - -
    -
    -var pgp = require("pg-promise")(/*options*/);
    -var db = pgp("postgres://username:password@host:port/database");
    -
    -db.one("SELECT $1 AS value", 123)
    -    .then(function (data) {
    -        console.log("DATA:", data.value);
    -    })
    -    .catch(function (error) {
    -        console.log("ERROR:", error);
    -    });
    -
    -
    +### Beispiel - +```js +const pgp = require('pg-promise')(/* options */) +const db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **Modul**: [redis](https://github.com/mranney/node_redis) **Installation** +### Installation + ```bash $ npm install redis ``` -**Beispiel** +### Beispiel -
    -
    -var client = require('redis').createClient();
    +```js
    +const redis = require('redis')
    +const client = redis.createClient()
     
    -client.on('error', function (err) {
    -  console.log('Error ' + err);
    -});
    +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.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', function (err, replies) {
    +client.hkeys('hash key', (err, replies) => {
    +  console.log(`${replies.length} replies:`)
     
    -  console.log(replies.length + ' replies:');
    -  replies.forEach(function (reply, i) {
    -    console.log('    ' + i + ': ' + reply);
    -  });
    +  replies.forEach((reply, i) => {
    +    console.log(`    ${i}: ${reply}`)
    +  })
     
    -  client.quit();
    +  client.quit()
    +})
    +```
     
    -});
    -
    -
    +## SQL Server - +**Module**: [tedious](https://github.com/tediousjs/tedious) + +### Installation + +```bash +$ npm install tedious +``` + +### Beispiel + +```js +const Connection = require('tedious').Connection +const Request = require('tedious').Request + +const config = { + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } +} + +const connection = new Connection(config) + +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **Modul**: [sqlite3](https://github.com/mapbox/node-sqlite3) **Installation** +### Installation + ```bash $ npm install sqlite3 ``` -**Beispiel** - -
    -
    -var sqlite3 = require('sqlite3').verbose();
    -var db = new sqlite3.Database(':memory:');
    +### Beispiel
     
    -db.serialize(function() {
    +```js
    +const sqlite3 = require('sqlite3').verbose()
    +const db = new sqlite3.Database(':memory:')
     
    -  db.run('CREATE TABLE lorem (info TEXT)');
    -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
    +db.serialize(() => {
    +  db.run('CREATE TABLE lorem (info TEXT)')
    +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
     
    -  for (var i = 0; i < 10; i++) {
    -    stmt.run('Ipsum ' + i);
    +  for (let i = 0; i < 10; i++) {
    +    stmt.run(`Ipsum ${i}`)
       }
     
    -  stmt.finalize();
    +  stmt.finalize()
     
    -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
    -    console.log(row.id + ': ' + row.info);
    -  });
    -});
    +  db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
    +    console.log(`${row.id}: ${row.info}`)
    +  })
    +})
     
    -db.close();
    -
    -
    - - +db.close() +``` ## ElasticSearch **Modul**: [elasticsearch](https://github.com/elastic/elasticsearch-js) **Installation** +### Installation + ```bash $ npm install elasticsearch ``` -**Beispiel** +### Beispiel -
    -
    -var elasticsearch = require('elasticsearch');
    -var client = elasticsearch.Client({
    +```js
    +const elasticsearch = require('elasticsearch')
    +const client = elasticsearch.Client({
       host: 'localhost:9200'
    -});
    +})
     
     client.search({
       index: 'books',
    @@ -391,10 +497,9 @@ client.search({
           }
         }
       }
    -}).then(function(response) {
    -  var hits = response.hits.hits;
    -}, function(error) {
    -  console.trace(error.message);
    -});
    -
    -
    +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/de/guide/debugging.md b/de/guide/debugging.md old mode 100755 new mode 100644 index ff1879d7ee..49d8f7d47d --- a/de/guide/debugging.md +++ b/de/guide/debugging.md @@ -4,6 +4,7 @@ title: Debugging bei Express description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: de +redirect_from: " " --- # Debugging bei Express @@ -17,7 +18,7 @@ $ DEBUG=express:* node index.js Verwenden Sie unter Windows den entsprechenden Befehl. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` Die Ausführung dieses Befehls für die durch [express generator](/{{ page.lang }}/starter/generator.html) generierte Standardanwendung resultiert in folgender Ausgabe: @@ -58,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -90,6 +91,8 @@ Wenn Sie nur die Protokolle von der Routerimplementierung sehen wollen, legen Si ## Von `express` generierte Anwendungen +An application generated by the `express` command uses the `debug` module and its debug namespace is scoped to the name of the application. + Beispiel: Wenn Sie die Anwendung mit `$ express sample-app` generiert haben, können Sie die Debuganweisungen mit dem folgenden Befehl aktivieren: ```bash @@ -101,3 +104,27 @@ Sie können mehrere Debug-Namespaces in einer durch Kommas getrennten Namenslist ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/de/guide/error-handling.md b/de/guide/error-handling.md old mode 100755 new mode 100644 index 5e01345df9..dc3fde4319 --- a/de/guide/error-handling.md +++ b/de/guide/error-handling.md @@ -4,11 +4,185 @@ title: Fehlerbehandlung in Express description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: de +redirect_from: " " --- # Fehlerbehandlung +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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. Beispiel: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + Middlewarefunktionen für die Fehlerbehandlung werden in derselben Weise definiert wie andere Middlewarefunktionen, nur, dass Fehlerbehandlungsfunktionen vier anstatt drei Argumente aufweisen: +`(err, req, res, next)`. Beispiel: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +Middleware für die Fehlerbehandlung wird ganz zuletzt nach allen anderen `app.use()`- und Weiterleitungsaufrufen definiert. +Beispiel: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +Wenn Sie Übergaben an die Funktion `next()` vornehmen (außer die Zeichenfolge `'route'`), sieht Express die aktuelle Anforderung als Fehler an und überspringt alle verbleibenden fehlerfreien Behandlungsroutinen und Middlewarefunktionen. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +Bei einem Routenhandler mit mehreren Callback-Funktionen können Sie den Parameter `route` verwenden, um den nächsten Routenhandler zu überspringen. Beispiel: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. Beispiel: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +You could also use a chain of handlers to rely on synchronous error +catching, by reducing the asynchronous code to something trivial. Beispiel: + +```js +app.get('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## Die Standardfehlerbehandlungsroutine (Default Error Handler) + +Express ist bereits mit einer integrierten Fehlerbehandlungsroutine ausgestattet, mit der alle in der Anwendung festgestellten Fehler gehandhabt werden können. Diese Middleware für die Fehlerbehandlung wird am Ende des Middleware-Funktionsstack hinzugefügt. + +Wenn Sie einen Fehler an `next()` übergeben und diesen nicht mit einem Error-Handler bearbeiten, wird dieser über den integrierten Error-Handler bearbeitet. Der Fehler wird mit dem Stack-Trace zum Client geschrieben. Der Stack-Trace ist in der Produktionsumgebung nicht verfügbar. + +
    +Legen Sie die Umgebungsvariable `NODE_ENV` auf `production` fest, um die Anwendung im Produktionsmodus auszuführen. +
    + +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. + +Wenn `next()` mit einem Fehler aufgerufen wird, nachdem Sie mit dem Schreiben der Antwort begonnen haben (z. B., wenn Sie beim Streamen der Antwort zum Client einen Fehler feststellen), schließt die Standardfehlerbehandlungsroutine in Express die Verbindung, und die Anforderung schlägt fehl. + +Wenn Sie also einen angepassten Error-Handler hinzufügen, empfiehlt es sich, eine Delegierung zur Standardfehlerbehandlungsroutine in Express vorzunehmen, wenn die Header bereits an den Client gesendet wurden: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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)`. Beispiel: ```js @@ -18,13 +192,16 @@ app.use((err, req, res, next) => { }) ``` -Middleware für die Fehlerbehandlung wird ganz zuletzt nach allen anderen `app.use()`- und Weiterleitungsaufrufen definiert. Beispiel: +You define error-handling middleware last, after other `app.use()` and routes calls; for example: ```js const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -39,7 +216,10 @@ Für organisatorische Zwecke (und Frameworks der höheren Ebene) können Sie meh const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -57,6 +237,8 @@ function logErrors (err, req, res, next) { In diesem Beispiel wird `clientErrorHandler` wie folgt definiert. In diesem Fall wird der Fehler explizit an den nächsten Error-Handler übergeben: +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) { if (req.xhr) { @@ -66,6 +248,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + Die `errorHandler`-Funktion "catch-all" kann wie folgt implementiert werden: ```js @@ -75,17 +258,16 @@ function errorHandler (err, req, res, next) { } ``` -Wenn Sie Übergaben an die Funktion `next()` vornehmen (außer die Zeichenfolge `'route'`), sieht Express die aktuelle Anforderung als Fehler an und überspringt alle verbleibenden fehlerfreien Behandlungsroutinen und Middlewarefunktionen. Wenn Sie den Fehler bearbeiten wollen, müssen Sie (wie im nächsten Abschnitt beschrieben) eine Fehlerbehandlungsweiterleitung erstellen. - -Bei einem Routenhandler mit mehreren Callback-Funktionen können Sie den Parameter `route` verwenden, um den nächsten Routenhandler zu überspringen. Beispiel: +If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. Beispiel: ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -94,32 +276,9 @@ app.get('/a_route_behind_paywall', }) }) ``` -In diesem Beispiel wird der Handler `getPaidContent` übersprungen. Alle verbleibenden Handler in `app` für `/a_route_behind_paywall` werden jedoch weiter ausgeführt. - -
    -Aufrufe zu `next()` und `next(err)` geben an, dass der aktuelle Handler abgeschlossen ist und welchen Status er aufweist. Durch `next(err)` werden alle verbleibenden Handler in der Kette übersprungen. Ausgenommen hiervor sind die Handler, die konfiguriert sind, um Fehler wie oben beschrieben zu behandeln. -
    - -## Die Standardfehlerbehandlungsroutine (Default Error Handler) - -Express ist bereits mit einer integrierten Fehlerbehandlungsroutine ausgestattet, mit der alle in der Anwendung festgestellten Fehler gehandhabt werden können. Diese Middleware für die Fehlerbehandlung wird am Ende des Middleware-Funktionsstack hinzugefügt. -Wenn Sie einen Fehler an `next()` übergeben und diesen nicht mit einem Error-Handler bearbeiten, wird dieser über den integrierten Error-Handler bearbeitet. Der Fehler wird mit dem Stack-Trace zum Client geschrieben. Der Stack-Trace ist in der Produktionsumgebung nicht verfügbar. +In diesem Beispiel wird der Handler `getPaidContent` übersprungen. Alle verbleibenden Handler in `app` für `/a_route_behind_paywall` werden jedoch weiter ausgeführt.
    -Legen Sie die Umgebungsvariable `NODE_ENV` auf `production` fest, um die Anwendung im Produktionsmodus auszuführen. +Aufrufe zu `next()` und `next(err)` geben an, dass der aktuelle Handler abgeschlossen ist und welchen Status er aufweist. Durch `next(err)` werden alle verbleibenden Handler in der Kette übersprungen. Ausgenommen hiervor sind die Handler, die konfiguriert sind, um Fehler wie oben beschrieben zu behandeln.
    - -Wenn `next()` mit einem Fehler aufgerufen wird, nachdem Sie mit dem Schreiben der Antwort begonnen haben (z. B., wenn Sie beim Streamen der Antwort zum Client einen Fehler feststellen), schließt die Standardfehlerbehandlungsroutine in Express die Verbindung, und die Anforderung schlägt fehl. - -Wenn Sie also einen angepassten Error-Handler hinzufügen, empfiehlt es sich, eine Delegierung zur Standardfehlerbehandlungsroutine in Express vorzunehmen, wenn die Header bereits an den Client gesendet wurden: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/de/guide/migrating-4.md b/de/guide/migrating-4.md old mode 100755 new mode 100644 index 8131f3dddc..04936b7501 --- a/de/guide/migrating-4.md +++ b/de/guide/migrating-4.md @@ -4,6 +4,7 @@ title: Migration auf 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. menu: guide lang: de +redirect_from: " " --- # Wechsel zu Express 4 @@ -25,15 +26,16 @@ In diesem Beitrag werden folgende Themen behandelt: In Express 4 wurden einige signifikante Änderungen vorgenommen: Siehe hierzu auch: -* [Neue Features/Funktionen in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) -* [Migration von 3.x auf 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) +- [Neue Features/Funktionen in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) +- [Migration von 3.x auf 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)

    Änderungen am Express-Core- und Middlewaresystem

    @@ -49,7 +51,7 @@ Ohne integrierte Middleware müssen Sie explizit alle Middlewarefunktionen hinzu In der folgenden Tabelle sind Express 3-Middlewarefunktionen und deren Entsprechungen in Express 4 aufgelistet. - + @@ -81,7 +83,7 @@ In der folgenden Tabelle sind Express 3-Middlewarefunktionen und deren Entsprech -
    Express 3Express 4
    Express 3Express 4
    express.bodyParser body-parser + multer
    serve-index
    express.static serve-static
    + Hier finden Sie die [komplette Liste](https://github.com/senchalabs/connect#middleware) der Express 4-Middleware. @@ -89,25 +91,28 @@ In den meisten Fällen können Sie einfach nur die Middleware der alten Version

    app.use akzeptiert Parameter.

    -In Version 4 können Sie über einen Variablenparameter den Pfad definieren, in den Middlewarefunktionen geladen werden. Dann können Sie den Wert des Parameters aus dem Routenhandler laden. Beispiel: +In Version 4 können Sie über einen Variablenparameter den Pfad definieren, in den Middlewarefunktionen geladen werden. Dann können Sie den Wert des Parameters aus dem Routenhandler laden. +Beispiel: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

    Das Routingsystem

    Anwendungen laden nun implizit Routing-Middleware. Sie müssen sich also keine Gedanken mehr über die Reihenfolge machen, in der die Middleware in Bezug auf die `router`-Middleware geladen wird. -Die Art und Weise, wie Weiterleitungen (Routen) definiert werden, bleibt unverändert. Das Routingsystem verfügt jedoch über zwei neue Funktionen, die beim Organisieren Ihrer Weiterleitungen helfen: +Das Routingsystem verfügt jedoch über zwei neue Funktionen, die beim Organisieren Ihrer Weiterleitungen helfen: {: .doclist } -* Die neue Methode `app.route()` zum Erstellen verkettbarer Routenhandler für einen Weiterleitungspfad -* Die neue Klasse `express.Router` zum Erstellen modular einbindbarer Routenhandler + +- Die neue Methode `app.route()` zum Erstellen verkettbarer Routenhandler für einen Weiterleitungspfad +- Die neue Klasse `express.Router` zum Erstellen modular einbindbarer Routenhandler

    Die Methode app.route()

    @@ -117,13 +122,13 @@ Dies ist ein Beispiel für verkettete Routenhandler, die mit der Funktion `app.r ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -141,16 +146,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -162,7 +167,7 @@ Laden Sie dann das Routermodul in die Anwendung: ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -175,7 +180,7 @@ Weitere Änderungen In der folgenden Tabelle sind andere kleinere, aber trotzdem wichtige Änderungen in Express 4 aufgeführt: - + @@ -198,7 +203,7 @@ Das Modul `http` wird nicht mehr benötigt, es sei denn, Sie müssen direkt mit `app.configure()` @@ -281,11 +286,12 @@ Entfernt. Die Funktionalität ist nun auf die Einstellung des Basis-Cookiewerts begrenzt. Verwenden Sie `res.cookie()`, um weitere Funktionalität zu erhalten. -
    Objekt Beschreibung
    -Die Funktion `app.configure()` wurde entfernt. Verwenden Sie die Funktion `process.env.NODE_ENV` oder `app.get('env')`, um die Umgebung zu erkennen und die Anwendung entsprechend zu konfigurieren. +Die Funktion `app.configure()` wurde entfernt. Verwenden Sie die Funktion `process.env.NODE_ENV` oder `app.get('env')`, um die Umgebung zu erkennen und die Anwendung entsprechend zu konfigurieren.
    +

    Beispiel für eine Anwendungsmigration

    -Dies ist ein Beispiel für die Migration einer Express 3-Anwendung auf Express 4. Die dabei interessanten Dateien sind `app.js` und `package.json`. +Dies ist ein Beispiel für die Migration einer Express 3-Anwendung auf Express 4. +Die dabei interessanten Dateien sind `app.js` und `package.json`.

    Anwendung der Version 3 @@ -324,7 +330,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -361,11 +367,12 @@ $ npm install serve-favicon morgan method-override express-session body-parser m Nehmen Sie an `app.js` die folgenden Änderungen vor: 1. Die integrierten Express-Middlewarefunktionen `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` und - `express.errorHandler` sind im Objekt `express` nicht mehr verfügbar. Sie müssen deren Alternativen manuell installieren und in die Anwendung laden. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` und + `express.errorHandler` sind im Objekt `express` nicht mehr verfügbar. Sie müssen deren Alternativen manuell installieren und in die Anwendung laden. -2. Sie müssen die Funktion `app.router` nicht mehr laden. Sie ist kein gültiges Express 4-Anwendungsobjekt. Entfernen Sie also den Code `app.use(app.router);`. +2. Sie müssen die Funktion `app.router` nicht mehr laden. + Sie ist kein gültiges Express 4-Anwendungsobjekt. Entfernen Sie also den Code `app.use(app.router);`. 3. Stellen Sie sicher, dass die Middlewarefunktionen in der richtigen Reihenfolge geladen werden – laden Sie `errorHandler` nach dem Laden der Anwendungsweiterleitungen. @@ -388,7 +395,7 @@ Durch Ausführung des Befehls `npm` wird `package.json` wie folgt aktualisiert: "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -449,11 +456,10 @@ server.listen(app.get('port'), () => { }) ``` -
    -Wenn Sie nicht direkt mit dem Modul `http` arbeiten müssen (socket.io/SPDY/HTTPS), ist das Laden des Moduls nicht erforderlich. Die Anwendung kann dann einfach wie folgt gestartet werden: +
    Wenn Sie nicht direkt mit dem Modul `http` arbeiten müssen (socket.io/SPDY/HTTPS), ist das Laden des Moduls nicht erforderlich. Die Anwendung kann dann einfach wie folgt gestartet werden: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -483,6 +489,7 @@ $ npm uninstall -g express ``` Abhängig davon, wie Ihre Datei- und Verzeichnissberechtigungen konfiguriert sind, müssen Sie diesen Befehl möglicherweise mit `sudo` ausführen. + Installieren Sie nun den neuen Generator: ```bash @@ -491,7 +498,6 @@ $ npm install -g express-generator Abhängig davon, wie Ihre Datei- und Verzeichnissberechtigungen konfiguriert sind, müssen Sie diesen Befehl möglicherweise mit `sudo` ausführen. - Nun wird der Befehl `express` auf Ihrem System auf den Express 4 App Generator aktualisiert.

    Änderungen am App Generator

    @@ -499,9 +505,10 @@ Nun wird der Befehl `express` auf Ihrem System auf den Express 4 App Generator a Befehlsoptionen und -nutzung bleiben größtenteils unverändert. Es gelten jedoch folgende Ausnahmen: {: .doclist } -* Option `--sessions` wurde entfernt. -* Option `--jshtml` wurde entfernt. -* Option `--hogan` wurde hinzugefügt, um [Hogan.js](http://twitter.github.io/hogan.js/) zu unterstützen. + +- Option `--sessions` wurde entfernt. +- Option `--jshtml` wurde entfernt. +- Option `--hogan` wurde hinzugefügt, um [Hogan.js](http://twitter.github.io/hogan.js/) zu unterstützen.

    Beispiel

    @@ -532,7 +539,7 @@ Um das Verzeichnis `www` zu löschen und alles im "Express 3-Stil" zu belassen, ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` diff --git a/de/guide/migrating-5.md b/de/guide/migrating-5.md old mode 100755 new mode 100644 index de972e1f78..689fae62fc --- a/de/guide/migrating-5.md +++ b/de/guide/migrating-5.md @@ -4,6 +4,7 @@ title: Migration auf Express 5 description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: de +redirect_from: " " --- # Wechsel zu Express 5 @@ -12,19 +13,33 @@ lang: de Express 5.0 befindet sich noch in der Beta-Release-Phase. Hier finden Sie jedoch bereits eine Vorschau zu den Änderungen in diesem Release und zur Migration Ihrer Express 4-Anwendung auf Express 5. -Express 5 unterscheidet sich nicht allzu sehr von Express 4: Die Änderungen an der API sind nicht so signifikant wie von 3.0 zu 4.0. Auch wenn die Basis-API unverändert bleibt, wird es doch einige grundlegende Veränderungen geben. In anderen Worten: Ein vorhandenes Express 4-Programm funktioniert möglicherweise nicht mehr, wenn Sie es für Express 5 aktualisieren. +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -Zum Installieren der aktuellen Alpha-Version und zur Vorschau von Express 5 geben Sie den folgenden Befehl im Stammverzeichnis Ihrer Anwendung ein: - -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` Sie können Ihre automatisierten Tests ausführen, um zu sehen, was fehlschlägt, und Probleme gemäß den folgenden Updates beheben. Nachdem Sie alle Testfehler behoben haben, führen Sie Ihre Anwendung aus, um zu sehen, welche Fehler noch auftreten. Sie werden sofort feststellen, ob die Anwendung Methoden oder Eigenschaften verwendet, die nicht unterstützt werden. -

    Änderungen in Express 5

    +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` -Nachfolgend finden Sie eine Liste mit Änderungen (Stand: Alpha-2-Release), die sich auf Sie als Express-Benutzer auswirken werden. Siehe hierzu auch die [Pull-Anforderung](https://github.com/expressjs/express/pull/2237) mit einer Liste aller geplanten Features und Funktionen. +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

    Änderungen in Express 5

    **Entfernte Methoden und Eigenschaften** @@ -36,26 +51,40 @@ Nachfolgend finden Sie eine Liste mit Änderungen (Stand: Alpha-2-Release), die
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
-**Geändert** +**Verbesserungen** -**Verbesserungen** +**Geändert** -

Entfernte Methoden und Eigenschaften

+### Entfernte Methoden und Eigenschaften Wenn Sie eine dieser Methoden oder Eigenschaften in Ihrer Anwendung verwenden, stürzt die Anwendung ab. Sie müssen also Ihre Anwendung ändern, wenn Sie auf Version 5 umgestellt haben. @@ -63,21 +92,75 @@ Wenn Sie eine dieser Methoden oder Eigenschaften in Ihrer Anwendung verwenden, s Express 5 unterstützt die Funktion `app.del()` nicht mehr. Wenn Sie diese Funktion verwenden, wird ein Fehler ausgelöst. Für die Registrierung von HTTP DELETE-Weiterleitungen verwenden Sie stattdessen die Funktion `app.delete()`. -Anfänglich wurde `del` statt `delete` verwendet, weil `delete` in JavaScript ein reserviertes Schlüsselwort ist. Ab ECMAScript 6 jedoch können `delete` und andere reservierte Schlüsselwörter legal als Eigenschaftsnamen verwendet werden. Lesen hier auch die Diskussion, die zur Einstellung der Unterstützung der Funktion `app.del` geführt hat. +Anfänglich wurde `del` statt `delete` verwendet, weil `delete` in JavaScript ein reserviertes Schlüsselwort ist. Ab ECMAScript 6 jedoch können `delete` und andere reservierte Schlüsselwörter legal als Eigenschaftsnamen verwendet werden. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

app.param(fn)

-Die Signatur `app.param(fn)` wurde für die Änderung der Verhaltensweise der Funktion `app.param(name, fn)` verwendet. Seit v4.11.0 wurde sie nicht mehr verwendet. In Express 5 wird sie überhaupt nicht mehr unterstützt. +Die Signatur `app.param(fn)` wurde für die Änderung der Verhaltensweise der Funktion `app.param(name, fn)` verwendet. Seit v4.11.0 wurde sie nicht mehr verwendet. In Express 5 wird sie überhaupt nicht mehr unterstützt.

Pluralisierte Methodennamen

Die folgenden Methodennamen wurden pluralisiert. In Express 4 wurde bei Verwendung der alten Methoden eine Warnung zur Einstellung der Unterstützung ausgegeben. Express 5 unterstützt diese Methoden nicht mehr. +`req.acceptsLanguage()` wird durch `req.acceptsLanguages()` ersetzt. + `req.acceptsCharset()` wird durch `req.acceptsCharsets()` ersetzt. `req.acceptsEncoding()` wird durch `req.acceptsEncodings()` ersetzt. -`req.acceptsLanguage()` wird durch `req.acceptsLanguages()` ersetzt. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

Führender Doppelpunkt (:) im Namen für app.param(name, fn)

@@ -89,42 +172,334 @@ Dies dürfte keine Auswirkungen auf Ihren Code haben, wenn Sie die Express 4-Dok Dieses potenziell verwirrende und durchaus riskante Verfahren des Abrufens von Formulardaten wurde entfernt. Sie müssen nun ganz speziell nach dem übergebenen Parameternamen im Objekt `req.params`, `req.body` oder `req.query` suchen. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

res.json(obj, status)

Express 5 unterstützt die Signatur `res.json(obj, status)` nicht mehr. Stattdessen müssen Sie den Status festlegen und diesen dann mit `res.json()`-Methoden wie dieser verketten: `res.status(status).json(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

res.jsonp(obj, status)

Express 5 unterstützt die Signatur `res.jsonp(obj, status)` nicht mehr. Stattdessen müssen Sie den Status festlegen und diesen dann mit `res.jsonp()`-Methoden wie dieser verketten: `res.status(status).jsonp(obj)`. -

res.send(body, status)

+{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

res.redirect(url, status)

Express 5 unterstützt die Signatur `res.send(obj, status)` nicht mehr. Stattdessen müssen Sie den Status festlegen und diesen dann mit `res.send()`-Methoden wie dieser verketten: `res.status(status).send(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

res.redirect('back') and res.location('back')

+ +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

res.send(body, status)

+ +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

res.send(status)

-Express 5 unterstützt die Signatur res.send(status), nicht mehr, wobei *`status`* für eine Zahl steht. Verwenden Sie stattdessen die Funktion `res.sendStatus(statusCode)`, mit der der Statuscode für den HTTP-Antwort-Header festgelegt und die Textversion des Codes gesendet wird: "Not Found" (Nicht gefunden), "Internal Server Error" (Interner Serverfehler) usw. Wenn Sie eine Zahl senden und hierfür die Funktion `res.send()` verwenden müssen, müssen Sie die Zahl in Anführungszeichen setzen, um diese in eine Zeichenfolge zu konvertieren. Dadurch interpretiert Express diese Zahl nicht als Versuch, die nicht mehr unterstützte alte Signatur zu verwenden. +Express 5 unterstützt die Signatur res.send(status), nicht mehr, wobei _`status`_ für eine Zahl steht. Verwenden Sie stattdessen die Funktion `res.sendStatus(statusCode)`, mit der der Statuscode für den HTTP-Antwort-Header festgelegt und die Textversion des Codes gesendet wird: "Not Found" (Nicht gefunden), "Internal Server Error" (Interner Serverfehler) usw. +Wenn Sie eine Zahl senden und hierfür die Funktion `res.send()` verwenden müssen, müssen Sie die Zahl in Anführungszeichen setzen, um diese in eine Zeichenfolge zu konvertieren. Dadurch interpretiert Express diese Zahl nicht als Versuch, die nicht mehr unterstützte alte Signatur zu verwenden. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +```

res.sendfile()

Die Funktion `res.sendfile()` wurde durch eine Version in Camel-Schreibweise von `res.sendFile()` in Express 5 ersetzt. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

router.param(fn)

+ +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. Seit v4.11.0 wurde sie nicht mehr verwendet. In Express 5 wird sie überhaupt nicht mehr unterstützt. + +

express.static.mime

+ +In Express 5, `mime` is no longer an exported property of the `static` field. +Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

express:router debug logs

+ +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

Geändert

+

Path route matching syntax

+ +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. Beispiel: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

Rejected promises handled from middleware and handlers

+ +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

express.urlencoded

+ +The `express.urlencoded` method makes the `extended` option `false` by default. + +

app.listen

+ +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +Beispiel: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

app.router

Das Objekt `app.router`, das in Express 4 entfernt wurde, ist in Express 5 wieder verfügbar. In der neuen Version fungiert dieses Objekt nur als Referenz zum Express-Basisrouter – im Gegensatz zu Express 3, wo die Anwendung dieses Objekt explizit laden musste. +

req.body

+ +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

req.host

In Express 4 übergab die Funktion `req.host` nicht ordnungsgemäß eine eventuell vorhandene Portnummer. In Express 5 wird die Portnummer beibehalten.

req.query

-In Express 4.7 und ab Express 5 kann die Abfrageparser-Option `false` akzeptieren, um das Parsing von Abfragezeichenfolgen zu deaktivieren, wenn Sie Ihre eigene Funktion für die Parsinglogik bei Abfragezeichenfolgen verwenden wollen. +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". -

Verbesserungen

+

res.clearCookie

+ +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

res.status

+ +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

res.vary

+ +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### Verbesserungen

res.render()

Diese Methode erzwingt nun asynchrones Verhalten für alle View-Engines, sodass durch View-Engines mit synchroner Implementierung verursachte Fehler vermieden werden, durch die die empfohlene Schnittstelle nicht verwendet werden konnte. + +

Brotli encoding support

+ +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/de/guide/overriding-express-api.md b/de/guide/overriding-express-api.md new file mode 100644 index 0000000000..128fc5aa18 --- /dev/null +++ b/de/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: de +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/de/guide/routing.md b/de/guide/routing.md old mode 100755 new mode 100644 index 70bf497067..da4871a7a6 --- a/de/guide/routing.md +++ b/de/guide/routing.md @@ -4,11 +4,24 @@ title: Weiterleitung in Express description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: de +redirect_from: " " --- # Weiterleitung (Routing) -Der Begriff *Weiterleitung* (Routing) bezieht sich auf die Definition von Anwendungsendpunkten (URIs) und deren Antworten auf Clientanforderungen. Eine Einführung in dieses Routing siehe [Basisrouting](/{{ page.lang }}/starter/basic-routing.html). +Der Begriff _Weiterleitung_ (Routing) bezieht sich auf die Definition von Anwendungsendpunkten (URIs) und deren Antworten auf Clientanforderungen. +Eine Einführung in dieses Routing siehe [Basisrouting](/{{ page.lang }}/starter/basic-routing.html). + +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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. Der folgende Code ist ein Beispiel für ein sehr einfaches Basisrouting. @@ -40,15 +53,10 @@ app.post('/', (req, res) => { }) ``` -Express unterstützt die folgenden Weiterleitungsmethoden, die den HTTP-Methoden entsprechen: `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search` und `connect`. - -
-Verwenden Sie zum Weiterleiten von Methoden, die zu den JavaScript-Variablennamen führen, die Notation "Eckige Klammer". Beispiel: `app['m-search']('/', function ...` -
+Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -Es gibt eine spezielle Weiterleitungsmethode, `app.all()`, die nicht von einer HTTP-Methode abgeleitet wird. Diese Methode wird zum Laden von Middlewarefunktionen bei einem Pfad für alle Anforderungsmethoden verwendet. - -Im folgenden Beispiel wird der Handler für Anforderungen zur Weiterleitung "/secret" ausgeführt, um herauszufinden, ob Sie GET-, POST-, PUT-, DELETE- oder andere HTTP-Anforderungsmethoden verwenden, die im [HTTP-Modul](https://nodejs.org/api/http.html#http_http_methods) unterstützt werden. +Es gibt eine spezielle Weiterleitungsmethode, `app.all()`, die nicht von einer HTTP-Methode abgeleitet wird. Diese Methode wird zum Laden von Middlewarefunktionen bei einem Pfad für alle Anforderungsmethoden verwendet. Im folgenden Beispiel wird der Handler für Anforderungen zur Weiterleitung "/secret" ausgeführt, um herauszufinden, ob Sie GET-, POST-, PUT-, DELETE- oder andere HTTP-Anforderungsmethoden verwenden, die im [HTTP-Modul](https://nodejs.org/api/http.html#http_http_methods) unterstützt werden. ```js app.all('/secret', (req, res, next) => { @@ -61,15 +69,32 @@ app.all('/secret', (req, res, next) => { Über Weiterleitungspfade werden in Kombination mit einer Anforderungsmethode die Endpunkte definiert, bei denen Anforderungen erfolgen können. Weiterleitungspfade können Zeichenfolgen, Zeichenfolgemuster oder reguläre Ausdrücke sein. -
-Express verwendet für den Abgleich der Weiterleitungspfade [path-to-regexp](https://www.npmjs.com/package/path-to-regexp). In der Dokumentation zu "path-to-regexp" finden Sie alle Möglichkeiten zum Definieren von Weiterleitungspfaden. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) ist ein handliches Tool zum Testen von Express-Basisweiterleitungen, auch wenn dieses Tool keine Musterabgleiche unterstützt. -
+{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
-Abfragezeichenfolgen sind nicht Teil des Weiterleitungspfads. -
+{% include admonitions/caution.html content=caution-character %} -Dies sind einige Beispiele für Weiterleitungspfade auf Basis von Zeichenfolgen. +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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 Route Tester](http://forbeslindesay.github.io/express-route-tester/) ist ein handliches Tool zum Testen von Express-Basisweiterleitungen, auch wenn dieses Tool keine Musterabgleiche unterstützt. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. + +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Route paths based on strings Dieser Weiterleitungspfad gleicht Weiterleitungsanforderungen zum Stammverzeichnis (`/`) ab. @@ -95,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -Dies sind einige Beispiele für Weiterleitungspfade auf Basis von Zeichenfolgemustern. +### Route paths based on string patterns + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} Dieser Weiterleitungspfad gleicht `acd` und `abcd` ab. @@ -105,7 +134,7 @@ app.get('/ab?cd', (req, res) => { }) ``` -Dieser Weiterleitungspfad gleicht `abcd`, `abbcd`, `abbbcd` usw. ab. +Dies sind einige Beispiele für Weiterleitungspfade auf Basis von Zeichenfolgemustern. ```js app.get('/ab+cd', (req, res) => { @@ -113,7 +142,7 @@ app.get('/ab+cd', (req, res) => { }) ``` -Dieser Weiterleitungspfad gleicht `abcd`, `abxcd`, `abRABDOMcd`, `ab123cd` usw. ab. +Dies sind einige Beispiele für Weiterleitungspfade auf Basis von Zeichenfolgen. ```js app.get('/ab*cd', (req, res) => { @@ -129,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
-Die Zeichen ?, +, * und () sind Subsets ihrer Entsprechungen in regulären Ausdrücken. Der Bindestrich (-) und der Punkt (.) werden von zeichenfolgebasierten Pfaden förmlich interpretiert. -
- -Beispiele für Weiterleitungspfade auf Basis regulärer Ausdrücke: +### Route paths based on regular expressions Dieser Weiterleitungspfad gleicht alle Weiterleitungsnamen ab, die den Buchstaben "a" enthalten. @@ -143,7 +168,7 @@ app.get(/a/, (req, res) => { }) ``` -Dieser Weiterleitungspfad gleicht `butterfly` und `dragonfly`, jedoch nicht `butterflyman`, `dragonfly man` usw. ab. +Dieser Weiterleitungspfad gleicht `butterfly` und `dragonfly`, jedoch nicht `butterflyman`, `dragonfly man` usw. ```js app.get(/.*fly$/, (req, res) => { @@ -151,6 +176,71 @@ 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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
+The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} +

Routenhandler (Weiterleitungsroutinen)

Sie können mehrere Callback-Funktionen angeben, die sich wie [Middleware](/{{ page.lang }}/guide/using-middleware.html) verhalten, um eine Anforderung zu verarbeiten. Die einzige Ausnahme hierbei ist, dass diese Callbacks möglicherweise `next('route')` aufrufen, um die verbleibenden Weiterleitungs-Callbacks zu umgehen. Mit diesem Verfahren können Sie Vorabbedingungen für eine Weiterleitung festlegen und dann die Steuerung an nachfolgende Weiterleitungen übergeben, wenn kein Grund vorliegt, mit der aktuellen Weiterleitung fortzufahren. @@ -175,6 +265,7 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` + Ein Array von Callback-Funktionen kann eine Weiterleitung verarbeiten. Beispiel: ```js @@ -220,21 +311,22 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => { Über die Methoden für das Antwortobjekt (`res`) in der folgenden Tabelle kann eine Antwort an den Client gesendet und der Anforderung/Antwort-Zyklus beendet werden. Wenn keine dieser Methoden über einen Routenhandler aufgerufen wird, bleibt die Clientanforderung im Status "blockiert". -| Methode | Beschreibung -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Gibt eine Eingabeaufforderung zum Herunterladen einer Datei aus. -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Beendet den Prozess "Antwort". -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Sendet eine JSON-Antwort. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Sendet eine JSON-Antwort mit JSONP-Unterstützung. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Leitet eine Anforderung um. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Gibt eine Anzeigevorlage aus. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Sendet eine Antwort mit unterschiedlichen Typen. -| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Sendet eine Datei als Oktett-Stream. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Legt den Antwortstatuscode fest und sendet dessen Zeichenfolgedarstellung als Antworthauptteil. +| Methode | Beschreibung | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Gibt eine Eingabeaufforderung zum Herunterladen einer Datei aus. | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | End the response process. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Sendet eine JSON-Antwort. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Sendet eine JSON-Antwort mit JSONP-Unterstützung. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Leitet eine Anforderung um. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Render a view template. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Sendet eine Antwort mit unterschiedlichen Typen. | +| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Sendet eine Datei als Oktett-Stream. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Legt den Antwortstatuscode fest und sendet dessen Zeichenfolgedarstellung als Antworthauptteil. |

app.route()

-Sie können mithilfe von `app.route()` verkettbare Routenhandler für einen Weiterleitungspfad erstellen. Da der Pfad an einer einzelnen Position angegeben wird, ist das Erstellen modularer Weiterleitungen hilfreich, da Redundanzen und Schreibfehler reduziert werden. Weitere Informationen zu Weiterleitungen finden Sie in der Dokumentation zu [Router()](/{{ page.lang }}/4x/api.html#router). +Sie können mithilfe von `app.route()` verkettbare Routenhandler für einen Weiterleitungspfad erstellen. +Da der Pfad an einer einzelnen Position angegeben wird, ist das Erstellen modularer Weiterleitungen hilfreich, da Redundanzen und Schreibfehler reduziert werden. Weitere Informationen zu Weiterleitungen finden Sie in der Dokumentation zu [Router()](/{{ page.lang }}/4x/api.html#router). Dies ist ein Beispiel für verkettete Routenhandler, die mit der Funktion `app.route()` definiert werden. @@ -264,10 +356,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -285,9 +379,15 @@ Laden Sie dann das Routermodul in die Anwendung: ```js const birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` Die Anwendung kann nun Anforderungen an die Pfade `/birds` und `/birds/about` bearbeiten und ruft die Middlewarefunktion `timeLog` auf, die speziell für diese Weiterleitung bestimmt ist. + +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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/de/guide/using-middleware.md b/de/guide/using-middleware.md old mode 100755 new mode 100644 index bf3db710c6..2f4d7a5e91 --- a/de/guide/using-middleware.md +++ b/de/guide/using-middleware.md @@ -4,32 +4,34 @@ title: Express-Middleware verwenden description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: de +redirect_from: " " --- # Middleware verwenden Express ist ein Weiterleitungs- und Middleware-Web-Framework, das selbst nur minimale Funktionalität aufweist: Eine Express-Anwendung besteht im Wesentlichen aus einer Reihe von Middlewarefunktionsaufrufen. -*Middlewarefunktionen* sind Funktionen, die Zugriff auf das [Anforderungsobjekt](/{{ page.lang }}/4x/api.html#req) (`req`), das [Antwortobjekt](/{{ page.lang }}/4x/api.html#res) (`res`) und die nächste Middlewarefunktion im Anforderung/Antwort-Zyklus der Anwendung haben. Die nächste Middlewarefunktion wird im Allgemeinen durch die Variable `next` bezeichnet. +_Middlewarefunktionen_ sind Funktionen, die Zugriff auf das [Anforderungsobjekt](/{{ page.lang }}/4x/api.html#req) (`req`), das [Antwortobjekt](/{{ page.lang }}/4x/api.html#res) (`res`) und die nächste Middlewarefunktion im Anforderung/Antwort-Zyklus der Anwendung haben. Die nächste Middlewarefunktion wird im Allgemeinen durch die Variable `next` bezeichnet. Über Middlewarefunktionen lassen sich die folgenden Tasks ausführen: -* Ausführen von Code -* Vornehmen von Änderungen an der Anforderung und an Antwortobjekten -* Beenden des Anforderung/Antwort-Zyklus -* Aufrufen der nächsten Middlewarefunktion im Stack +- Ausführen von Code +- Vornehmen von Änderungen an der Anforderung und an Antwortobjekten +- End the request-response cycle. +- Aufrufen der nächsten Middlewarefunktion im Stack Wenn über die aktuelle Middlewarefunktion der Anforderung/Antwort-Zyklus nicht beendet werden kann, muss `next()` aufgerufen werden, um die Steuerung an die nächste Middlewarefunktion zu übergeben. Andernfalls geht die Anforderung in den Status "Blockiert" über. Eine Express-Anwendung kann die folgenden Middlewaretypen verwenden: - - [Middleware auf Anwendungsebene](#middleware.application) - - [Middleware auf Routerebene](#middleware.router) - - [Middleware für die Fehlerbehandlung](#middleware.error-handling) - - [Integrierte Middleware](#middleware.built-in) - - [Middleware anderer Anbieter](#middleware.third-party) +- [Middleware auf Anwendungsebene](#middleware.application) +- [Middleware auf Routerebene](#middleware.router) +- [Middleware für die Fehlerbehandlung](#middleware.error-handling) +- [Integrierte Middleware](#middleware.built-in) +- [Middleware anderer Anbieter](#middleware.third-party) -Sie können Middleware auf Anwendungsebene und Routerebene mit einem optionalen Mountpfad laden. Sie können auch eine Reihe von Middlewarefunktionen zusammen laden. Dadurch wird ein Sub-Stack des Middlewaresystems am Mountpunkt erstellt. +Sie können Middleware auf Anwendungsebene und Routerebene mit einem optionalen Mountpfad laden. +Sie können auch eine Reihe von Middlewarefunktionen zusammen laden. Dadurch wird ein Sub-Stack des Middlewaresystems am Mountpunkt erstellt.

Middleware auf Anwendungsebene

@@ -38,6 +40,7 @@ Binden Sie Middleware auf Anwendungsebene zu einer Instanz des [Anwendungsobjekt Dieses Beispiel zeigt eine Middlewarefunktion ohne Mountpfad. Die Funktion wird immer dann ausgeführt, wenn die Anwendung eine Anforderung erhält. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -63,7 +66,8 @@ app.get('/user/:id', (req, res, next) => { }) ``` -Dies ist ein Beispiel zum Laden einer Reihe von Middlewarefunktionen an einem Mountpunkt mit einem Mountpfad. Das Beispiel veranschaulicht einen Middleware-Stack, über den Anforderungsinformationen zu einer HTTP-Anforderung zum Pfad `/user/:id` ausgegeben werden. +Dies ist ein Beispiel zum Laden einer Reihe von Middlewarefunktionen an einem Mountpunkt mit einem Mountpfad. +Das Beispiel veranschaulicht einen Middleware-Stack, über den Anforderungsinformationen zu einer HTTP-Anforderung zum Pfad `/user/:id` ausgegeben werden. ```js app.use('/user/:id', (req, res, next) => { @@ -89,11 +93,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` -Wenn Sie den Rest der Middlewarefunktionen eines Weiterleitungs-Middleware-Stack überspringen wollen, rufen Sie `next('route')` auf, um die Steuerung an die nächste Weiterleitung zu übergeben. **HINWEIS**: `next('route')` funktioniert nur in Middlewarefunktionen, die über die Funktionen `app.METHOD()` oder `router.METHOD()` geladen wurden. +Wenn Sie den Rest der Middlewarefunktionen eines Weiterleitungs-Middleware-Stack überspringen wollen, rufen Sie `next('route')` auf, um die Steuerung an die nächste Weiterleitung zu übergeben. + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} Dieses Beispiel zeigt einen Middleware-Sub-Stack, über den GET-Anforderungen zum Pfad `/user/:id` verarbeitet werden. @@ -102,15 +114,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +Dies ist ein Beispiel zur Verwendung der Middlewarefunktion `express.static` mit einem ausführlich dargestellten Optionsobjekt: + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -121,10 +154,13 @@ Middleware auf Routerebene funktioniert in der gleichen Weise wie Middleware auf ```js const router = express.Router() ``` + Laden Sie Middleware auf Routerebene über die Funktionen `router.use()` und `router.METHOD()`. + Der folgende Beispielcode repliziert das Middlewaresystem, das oben für die Middleware auf Anwendungsebene gezeigt wird, durch Verwendung von Middleware auf Routerebene. ```js +const express = require('express') const app = express() const router = express.Router() @@ -148,7 +184,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -163,6 +199,33 @@ router.get('/user/:id', (req, res, next) => { // 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. + +Dieses Beispiel zeigt einen Middleware-Sub-Stack, über den GET-Anforderungen zum Pfad `/user/:id` verarbeitet werden. + +```js +const express = require('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) +}) +``` +

Middleware für die Fehlerbehandlung

@@ -184,52 +247,11 @@ Details zu Middleware für die Fehlerbehandlung siehe [Fehlerbehandlung](/{{ pag Seit Version 4.x bestehen bei Express keine Abhängigkeiten zu [Connect](https://github.com/senchalabs/connect) mehr. Mit Ausnahme von `express.static` befinden sich nun alle Middlewarefunktionen, die bisher in Express enthalten waren, in separaten Modulen. Sehen Sie sich hierzu auch die [Liste der Middlewarefunktionen](https://github.com/senchalabs/connect#middleware) an. -

express.static(root, [options])

- -Die einzige integrierte Middlewarefunktion in Express ist `express.static`. Diese Funktion basiert auf [serve-static](https://github.com/expressjs/serve-static) und ist zuständig für die statischen Assets einer Express-Anwendung. - -Das Argument `root` gibt das Stammverzeichnis an, von dem aus statische Assets bedient werden. - -Das optionale Objekt `options` kann folgende Eigenschaften aufweisen: - -| Eigenschaft | Beschreibung | Typ | Standard | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Option für Dateien mit Punkterweiterung (dotfiles). Mögliche Werte sind "allow", "deny" und "ignore" | Zeichenfolge | "ignore" | -| `etag` | Aktiviert oder inaktiviert die etag-Generierung. | Boolesch | `true` | -| `extensions` | Legt Dateierweiterungs-Fallbacks fest. | Bereich | `[]` | -| `index` | Sendet die verzeichnissspezifische indexierte Datei. Bei `false` wird die Verzeichnisindexierung inaktiviert. | Gemischt | "index.html" | - `lastModified` | Legt den Header `Last-Modified` auf das Datum der letzten Änderung der Datei im Betriebssystem fest. Mögliche Werte sind`true` und `false`. | Boolesch | `true` | -| `maxAge` | Legt die Eigenschaft "max-age" des Headers "Cache-Control" in Millisekunden oder als Zeichenfolge im [ms-Format](https://www.npmjs.org/package/ms) fest. | Zahl | 0 | -| `redirect` | Umleitung zu einem abschließenden "/", wenn der Pfadname ein Verzeichnis ist. | Boolesch | `true` | -| `setHeaders` | Funktion zum Festlegen von HTTP-Headern für die Datei. | Funktion | | - -Dies ist ein Beispiel zur Verwendung der Middlewarefunktion `express.static` mit einem ausführlich dargestellten Optionsobjekt: - -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -Es sind mehrere statische Verzeichnisse pro Anwendung möglich: - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` +Die einzige integrierte Middlewarefunktion in Express ist `express.static`. -Details zur Funktion `serve-static` und deren Optionen finden Sie in der Dokumentation zu [serve-static](https://github.com/expressjs/serve-static). +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**

Middleware anderer Anbieter

diff --git a/de/guide/using-template-engines.md b/de/guide/using-template-engines.md old mode 100755 new mode 100644 index b8a308fbe0..7100c0aec1 --- a/de/guide/using-template-engines.md +++ b/de/guide/using-template-engines.md @@ -4,14 +4,22 @@ title: Template-Engines in Express verwenden description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: de +redirect_from: " " --- # Template-Engines in Express verwenden -Bevor über Express Vorlagendateien ausgegeben werden können, müssen die folgenden Anwendungseinstellungen festgelegt werden: +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. -* `views`, das Verzeichnis, in dem sich die Vorlagendateien befinden. Beispiel: `app.set('views', './views')` -* `view engine`, die zu verwendende Template-Engine. Beispiel: `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, das Verzeichnis, in dem sich die Vorlagendateien befinden. Beispiel: `app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, die zu verwendende Template-Engine. Beispiel: `app.set('view engine', 'pug')` Installieren Sie dann das entsprechende npm-Paket für die Template-Engine: @@ -19,8 +27,10 @@ Installieren Sie dann das entsprechende npm-Paket für die Template-Engine: $ npm install pug --save ``` -
-Express-konforme Template-Engines wie Pug exportieren eine Funktion namens `__express(filePath, options, callback)`, die über die Funktion `res.render()` aufgerufen wird, um den Vorlagencode ausgeben zu können. Einige Template-Engines folgen dieser Konvention nicht. Die Bibliothek [Consolidate.js](https://www.npmjs.org/package/consolidate) folgt dieser Konvention, indem alle gängigen Node.js-Template-Engines zugeordnet werden. Daher ist eine reibungslose Funktion in Express gewährleistet. +
Express-konforme Template-Engines wie Pug exportieren eine Funktion namens `__express(filePath, options, callback)`, die über die Funktion `res.render()` aufgerufen wird, um den Vorlagencode ausgeben zu können. + +Einige Template-Engines folgen dieser Konvention nicht. Die Bibliothek [Consolidate.js](https://www.npmjs.org/package/consolidate) folgt dieser Konvention, indem alle gängigen Node.js-Template-Engines zugeordnet werden. Daher ist eine reibungslose Funktion in Express gewährleistet. +
Nach der Festlegung der View-Engine muss die Engine nicht angegeben oder das Template-Engine-Modul nicht in Ihre Anwendung geladen werden. Express lädt das Modul intern (wie unten für das obige Beispiel gezeigt). @@ -49,4 +59,4 @@ app.get('/', (req, res) => { Wenn Sie eine Anforderung zur Homepage ausführen, wird die Datei `index.pug` im HTML-Format ausgegeben. -Weitere Informationen zur Funktionsweise von Template-Engines in Express siehe ["Template-Engines für Express entwickeln"](/{{ page.lang }}/advanced/developing-template-engines.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/de/guide/writing-middleware.md b/de/guide/writing-middleware.md old mode 100755 new mode 100644 index 63a4068dda..ad8eaccd02 --- a/de/guide/writing-middleware.md +++ b/de/guide/writing-middleware.md @@ -4,31 +4,32 @@ title: Middleware für die Verwendung in Express-Anwendungen schreiben description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: de +redirect_from: " " --- # Middleware für die Verwendung in Express-Anwendungen schreiben

Überblick

-*Middlewarefunktionen* sind Funktionen, die Zugriff auf das [Anforderungsobjekt](/{{ page.lang }}/4x/api.html#req) (`req`), das [Antwortobjekt](/{{ page.lang }}/4x/api.html#res) (`res`) und die nächste Middlewarefunktion im Anforderung/Antwort-Zyklus der Anwendung haben. Die nächste Middlewarefunktion wird im Allgemeinen durch die Variable `next` bezeichnet. +_Middlewarefunktionen_ sind Funktionen, die Zugriff auf das [Anforderungsobjekt](/{{ page.lang }}/4x/api.html#req) (`req`), das [Antwortobjekt](/{{ page.lang }}/4x/api.html#res) (`res`) und die nächste Middlewarefunktion im Anforderung/Antwort-Zyklus der Anwendung haben. Die nächste Middlewarefunktion wird im Allgemeinen durch die Variable `next` bezeichnet. Über Middlewarefunktionen lassen sich die folgenden Tasks ausführen: -* Ausführen von Code -* Vornehmen von Änderungen an der Anforderung und an Antwortobjekten -* Beenden des Anforderung/Antwort-Zyklus -* Aufrufen der nächsten Middleware im Stack +- Ausführen von Code +- Vornehmen von Änderungen an der Anforderung und an Antwortobjekten +- End the request-response cycle. +- Aufrufen der nächsten Middleware im Stack Wenn über die aktuelle Middlewarefunktion der Anforderung/Antwort-Zyklus nicht beendet werden kann, muss `next()` aufgerufen werden, um die Steuerung an die nächste Middlewarefunktion zu übergeben. Andernfalls geht die Anforderung in den Status "Blockiert" über. Das folgende Beispiel zeigt die Elemente eines Middlewarefunktionsaufrufs: - -
-Elements of a middleware function call + + -
Pfad (Weiterleitung), für den die Middlewarefunktion angewendet wird.
@@ -42,7 +43,14 @@ Das folgende Beispiel zeigt die Elemente eines Middlewarefunktionsaufrufs:
+Elements of a middleware function call -
HTTP-Methode, für die die Middlewarefunktion angewendet wird.
+
+
HTTP-Methode, für die die Middlewarefunktion angewendet wird.
-Dies ist ein Beispiel einer einfachen Express-Anwendung namens "Hello World", für die Sie zwei Middlewarefunktionen definieren: +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. + +

Beispiel

+ +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. ```js const express = require('express') @@ -55,8 +63,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

Entwicklung

- +

Dies ist ein Beispiel einer einfachen Express-Anwendung namens "Hello World", für die Sie zwei Middlewarefunktionen definieren:

Dies ist ein einfaches Beispiel einer Middlewarefunktion namens "myLogger". Diese Funktion gibt lediglich "LOGGED" aus, wenn eine Anforderung zur Anwendung über diese Funktion läuft. Die Middlewarefunktion ist der Variablen `myLogger` zugeordnet. ```js @@ -67,11 +74,13 @@ const myLogger = function (req, res, next) { ```
-Beachten Sie den Aufruf oben zu `next()`. Durch den Aufruf dieser Funktion wird die nächste Middlewarefunktion in der Anwendung aufgerufen. Die Funktion `next()` ist nicht Teil der Node.js- oder Express-API, sondern das dritte Argument, das an die Middlewarefunktion übergeben wird. Die Funktion `next()` kann jeden beliebigen Namen haben, per Konvention erhält sie jedoch immer den Namen "next". Um Unklarheiten zu vermeiden, sollten Sie immer diese Konvention verwenden. +Beachten Sie den Aufruf oben zu `next()`. Durch den Aufruf dieser Funktion wird die nächste Middlewarefunktion in der Anwendung aufgerufen. +Die Funktion `next()` ist nicht Teil der Node.js- oder Express-API, sondern das dritte Argument, das an die Middlewarefunktion übergeben wird. Die Funktion `next()` kann jeden beliebigen Namen haben, per Konvention erhält sie jedoch immer den Namen "next". +Um Unklarheiten zu vermeiden, sollten Sie immer diese Konvention verwenden.
- -Zum Laden der Middlewarefunktion rufen Sie `app.use()` auf und geben die Middlewarefunktion an. Beispiel: Durch den folgenden Code wird die Middlewarefunktion `myLogger` vor der Weiterleitung zum Stammverzeichnispfad (/) geladen. +Zum Laden der Middlewarefunktion rufen Sie `app.use()` auf und geben die Middlewarefunktion an. +Beispiel: Durch den folgenden Code wird die Middlewarefunktion `myLogger` vor der Weiterleitung zum Stammverzeichnispfad (/) geladen. ```js const express = require('express') @@ -99,6 +108,8 @@ Wenn `myLogger` nach der Weiterleitung zum Stammverzeichnispfad geladen wird, er Die Middlewarefunktion `myLogger` gibt einfach eine Nachricht aus und übergibt dann die Anforderung zur nächsten Middlewarefunktion im Stack durch Aufruf der Funktion `next()`. +

Middleware function requestTime

+ Im nächsten Beispiel wird die Eigenschaft `requestTime` zum Anforderungsobjekt hinzugefügt. Diese Middlewarefunktion erhält den Namen "requestTime". ```js @@ -129,8 +140,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + Wenn Sie eine Anforderung zum Stammverzeichnis der Anwendung einleiten, zeigt die Anwendung nun die Zeitmarke Ihrer Anforderung im Browser an. +

Middleware function validateCookies

+ +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
+ Da Sie Zugriff auf das Anforderungsobjekt, das Antwortobjekt, die nächste Middlewarefunktion im Stack und die gesamte Node.js-API haben, sind die Möglichkeiten, die Sie mit Middlewarefunktionen haben, nahezu unendlich. Weitere Informationen zur Verwendung von Middleware in Express siehe [ Express-Middleware verwenden](/{{ page.lang }}/guide/using-middleware.html). + +

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 +module.exports = 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') + +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. diff --git a/de/resources/community.md b/de/resources/community.md old mode 100755 new mode 100644 index fa4667e87f..c4d9297ec3 --- a/de/resources/community.md +++ b/de/resources/community.md @@ -4,20 +4,86 @@ title: Express-Community description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: de +redirect_from: " " --- # Community -## Beispiele +## Technical committee -Zeigen Sie Dutzende von [Beispielen](https://github.com/expressjs/express/tree/master/examples) zu Express-Anwendungen im Repository an, das alles abdeckt – von API-Design und Authentifizierung bis zur Einbindung von Template-Engines. +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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +Unsere lebhafte Community hat zu einer Vielzahl von Erweiterungen, [Middlewaremodulen](/{{ page.lang }}/resources/middleware.html) und Frameworks der höheren Ebene geführt. + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## Probleme Wenn Sie Ihrer Meinung nach einen Fehler festgestellt haben oder lediglich ein Feature/eine Funktion anfordern wollen, können Sie in der [Issue Queue](https://github.com/expressjs/express/issues) ein Ticket öffnen. -## Andere Anbieter +## Beispiele + +Zeigen Sie Dutzende von [Beispielen](https://github.com/expressjs/express/tree/master/examples) zu Express-Anwendungen im Repository an, das alles abdeckt – von API-Design und Authentifizierung bis zur Einbindung von Template-Engines. + +## 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. + +# Branding of Express.js + +## Express.js Logo -Unsere lebhafte Community hat zu einer Vielzahl von Erweiterungen, [Middlewaremodulen](/{{ page.lang }}/resources/middleware.html) und Frameworks der höheren Ebene geführt. Diese können Sie im -[Wiki](https://github.com/expressjs/express/wiki) genauer begutachten. +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. +
+
+

Logotype

+ Express.js logo + + + Express.js logo + +
+
+

Logomark

+ Express.js mark + + + Express.js mark + +
+
+
\ No newline at end of file diff --git a/de/resources/contributing.md b/de/resources/contributing.md new file mode 100644 index 0000000000..4f6e759006 --- /dev/null +++ b/de/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: de +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/de/resources/glossary.md b/de/resources/glossary.md old mode 100755 new mode 100644 index 51ae6a2654..399a67424d --- a/de/resources/glossary.md +++ b/de/resources/glossary.md @@ -1,24 +1,17 @@ --- layout: page -title: Express-Glossar +title: Express 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. menu: resources lang: de +redirect_from: " " --- # Glossar -### Anforderung - -Eine HTTP-Anforderung. Ein Client übergibt eine HTTP-Anforderungsnachricht an einen Server, der wiederum eine Antwort zurückgibt. Bei der Anforderung muss eine der [Anforderungsmethoden](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) wie GET, POST usw. verwendet werden. - -### Antwort - -Eine HTTP-Antwort. Ein Server gibt eine HTTP-Antwortnachricht an den Client zurück. Die Antwort enthält Informationen zum Beendigungsstatus in Bezug auf die Anforderung und kann im Nachrichtenhauptteil auch angeforderten Inhalt enthalten. - ### Anwendung -Im Allgemeinen besteht eine Anwendung aus einem oder mehreren Programmen, über die Operationen für bestimmte Zwecke ausgeführt werden. Im Zusammenhang mit Express ist eine Anwendung ein Programm, das die auf der Node.js-Plattform laufende Express-API nutzt. Wird auch als [Anwendungsobjekt](/{{ page.lang }}/api.html#express) bezeichnet. +Im Allgemeinen besteht eine Anwendung aus einem oder mehreren Programmen, über die Operationen für bestimmte Zwecke ausgeführt werden. Im Zusammenhang mit Express ist eine Anwendung ein Programm, das die auf der Node.js-Plattform laufende Express-API nutzt. Wird auch als [Anwendungsobjekt](/{{ page.lang }}/api.html#express) bezeichnet. ### API @@ -32,26 +25,42 @@ Schnelles, offenes, unkompliziertes Web-Framework für Node.js-Anwendungen. Im A Eine plattformübergreifende Unterstützungsbibliothek, bei der die asynchrone Ein-/Ausgabe im Mittelpunkt steht. Sie wurde in erster Linie für die Verwendung in Node.js entwickelt. -### Middleware +### middleware Eine Funktion, die über die Weiterleitungsebene in Express vor dem letzten Anforderungshandler aufgerufen wird. Deshalb befindet sich diese Funktion in der Mitte zwischen einer unformatierten Anforderung und der endgültigen beabsichtigten Weiterleitung. Nachfolgend finden Sie einige Details zur Middlewareterminologie: - * `var foo = require('middleware')` bedeutet, dass ein Node.js-Modul *benötigt* oder *verwendet* wird. Dann gibt die Anweisung `var mw = foo()` in der Regel die Middleware zurück. - * `app.use(mw)` bedeutet, dass die *Middleware dem globalen Verarbeitungsstack hinzugefügt wird*. - * `app.get('/foo', mw, function (req, res) { ... })` bedeutet, dass die *Middleware dem "GET /foo"-Verarbeitungsstack hinzugefügt wird*. +- `var foo = require('middleware')` bedeutet, dass ein Node.js-Modul _benötigt_ oder _verwendet_ wird. Dann gibt die Anweisung `var mw = foo()` in der Regel die Middleware zurück. +- `app.use(mw)` bedeutet, dass die _Middleware dem globalen Verarbeitungsstack hinzugefügt wird_. +- `app.get('/foo', mw, function (req, res) { ... })` bedeutet, dass die _Middleware dem "GET /foo"-Verarbeitungsstack hinzugefügt wird_. ### Node.js -Eine Softwareplattform, die für die Erstellung skalierbarer Netzanwendungen verwendet wird. Node.js verwendet JavaScript als Scripting-Sprache und erzielt den hohen Durchsatz durch nicht blockierende Ein-/Ausgabe und eine Ereignisschleife mit einem Thread. Siehe auch [nodejs.org](http://nodejs.org/). **Hinweis**: Der ursprüngliche Name lautet "Node.js". Mittlerweile ist die Bezeichnung "Node" geläufig. +Eine Softwareplattform, die für die Erstellung skalierbarer Netzanwendungen verwendet wird. Node.js verwendet JavaScript als Scripting-Sprache und erzielt den hohen Durchsatz durch nicht blockierende Ein-/Ausgabe und eine Ereignisschleife mit einem Thread. Siehe auch [nodejs.org](http://nodejs.org/). **Hinweis**: Der ursprüngliche Name lautet "Node.js". ### Open-Source Bei Verwendung als Adjektiv muss dieser Begriff mit Bindestrichen gekoppelt werden: Beispiel: "Dies ist eine Open-Source-Software." Siehe auch [Open-Source-Software in Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). -### Router +{% capture english-rules %} -Siehe [Router](/{{ page.lang }}/4x/api.html#router) in der API-Referenz. +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. + +{% endcapture %} + +{% include admonitions/note.html content=english-rules %} + +### Anforderung + +Eine HTTP-Antwort. Ein Server gibt eine HTTP-Antwortnachricht an den Client zurück. Die Antwort enthält Informationen zum Beendigungsstatus in Bezug auf die Anforderung und kann im Nachrichtenhauptteil auch angeforderten Inhalt enthalten. + +### Antwort + +Eine HTTP-Anforderung. Ein Client übergibt eine HTTP-Anforderungsnachricht an einen Server, der wiederum eine Antwort zurückgibt. The response contains completion status information about the request and might also contain requested content in its message body. ### Weiterleitung (Route) Teil einer URL, die eine Ressource angibt. Beispiel: In `http://foo.com/products/id` ist "/products/id" die Weiterleitung. + +### Router + +Siehe [Router](/{{ page.lang }}/4x/api.html#router) in der API-Referenz. diff --git a/de/resources/middleware.md b/de/resources/middleware.md old mode 100755 new mode 100644 index 798bb22433..2080a46dd8 --- a/de/resources/middleware.md +++ b/de/resources/middleware.md @@ -1,64 +1,44 @@ --- -layout: page +layout: middleware 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. menu: resources lang: de +redirect_from: " " +module: mw-home --- -# Middleware anderer Anbieter +## Express-Middleware Nachfolgend sind einige Express-Middlewaremodule aufgeführt: - - [body-parser](https://github.com/expressjs/body-parser): Bisher: `express.bodyParser`, `json` und `urlencoded`. - Siehe auch: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression): Bisher `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): Connect/Express-Middlewaremodule für optimales Image-Serving. Wechselt Images (wenn möglich) zu `.webp` oder `.jxr`. - - [connect-timeout](https://github.com/expressjs/timeout): Bisher: `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser): Bisher: `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session): Bisher: `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler): Bisher: `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug): Entwicklungstool, mit dem eine Registerkarte mit Informationen zu Vorlagenvariablen (lokalen Variablen), zur aktuellen Sitzung, zu hilfreichen Anforderungsdaten usw. Ihrer Anwendung hinzugefügt werden können. - - [express-partial-response](https://github.com/nemtsov/express-partial-response): Express-Middlewaremodul für die Filterung von Teilen von JSON-Antworten auf Basis der Abfragezeichenfolge `fields` durch Verwendung der Google-API Partial Response. - - [express-session](https://github.com/expressjs/session): Bisher: `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): Express-Middlewaremodul für die Verwendung eines CDN (Content Delivery Network) für statische Assets mit Unterstützung mehrerer Hosts (Beispiel: cdn1.host.com, cdn2.host.com). - - [express-slash](https://github.com/ericf/express-slash): Express-Middlewaremodul für Benutzer, die hohen Wert auf abschließende Schrägstriche legen. - - [express-stormpath](https://github.com/stormpath/stormpath-express): Express-Middlewaremodul für Benutzerspeicher, Authentifizierung, Autorisierung, SSO und Datensicherheit. - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): Middlewaremodul für die Umleitung von HTTP-Anforderungen mit Großbuchstaben in eine kanonische Form mit Kleinbuchstaben. - - [helmet](https://github.com/helmetjs/helmet): Modul zur Sicherung Ihrer Anwendungen durch Festlegung verschiedener HTTP-Header. - - [join-io](https://github.com/coderaiser/join-io "join-io"): Modul für die Verknüpfung von Dateien während der Verarbeitung, um die Anzahl der Anforderungen zu reduzieren. - - [method-override](https://github.com/expressjs/method-override): Bisher: `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan): Bisher: `logger` - - [passport](https://github.com/jaredhanson/passport): Express-Middlewaremodul für die Authentifizierung. - - [response-time](https://github.com/expressjs/response-time): Bisher: `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon): Bisher: `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index): Bisher: `express.directory` - - [serve-static](https://github.com/expressjs/serve-static): Modul für statischen Inhalt. - - [static-expiry](https://github.com/paulwalker/connect-static-expiry): URLs mit elektronischem Fingerabdruck oder Caching-Headern für statische Assets einschließlich Unterstützung für eine oder mehrere externe Domänen. - - [vhost](https://github.com/expressjs/vhost): Bisher: `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers): Express-Middlewaremodul, das allgemeine Helper-Methoden für Ansichten bereitstellt. - - [sriracha-admin](https://github.com/hdngr/siracha): Express-Middlewaremodul, das eine Administratorsite für Mongoose dynamisch generiert. +| [express-slash](https://github.com/ericf/express-slash): Express-Middlewaremodul für Benutzer, die hohen Wert auf abschließende Schrägstriche legen. | Beschreibung | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Einige Middlewaremodule, die bisher zu Connect gehörten, werden vom Connect/Express-Team nicht mehr unterstützt. Diese Module werden durch ein alternatives oder besseres Modul ersetzt. Verwenden Sie eine der folgenden Alternativen: +## Informationen zu weiteren Middlewaremodulen siehe: - - express.cookieParser - - [cookies](https://github.com/jed/cookies) und [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -Informationen zu weiteren Middlewaremodulen siehe: +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| [express-slash](https://github.com/ericf/express-slash): Express-Middlewaremodul für Benutzer, die hohen Wert auf abschließende Schrägstriche legen. | Beschreibung | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet): Modul zur Sicherung Ihrer Anwendungen durch Festlegung verschiedener HTTP-Header. | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport): Express-Middlewaremodul für die Authentifizierung. | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/de/resources/middleware/body-parser.md b/de/resources/middleware/body-parser.md new file mode 100644 index 0000000000..20ec662bac --- /dev/null +++ b/de/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: de +redirect_from: " " +module: body-parser +--- diff --git a/de/resources/middleware/compression.md b/de/resources/middleware/compression.md new file mode 100644 index 0000000000..6d4d1daff9 --- /dev/null +++ b/de/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: de +redirect_from: " " +module: compression +--- diff --git a/de/resources/middleware/connect-rid.md b/de/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..f761c4493d --- /dev/null +++ b/de/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: de +redirect_from: " " +module: connect-rid +--- diff --git a/de/resources/middleware/cookie-parser.md b/de/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..336bc801af --- /dev/null +++ b/de/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: de +redirect_from: " " +module: cookie-parser +--- diff --git a/de/resources/middleware/cookie-session.md b/de/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..490c855185 --- /dev/null +++ b/de/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: de +redirect_from: " " +module: cookie-session +--- diff --git a/de/resources/middleware/cors.md b/de/resources/middleware/cors.md new file mode 100644 index 0000000000..11782ff9ac --- /dev/null +++ b/de/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: de +redirect_from: " " +module: cors +--- diff --git a/de/resources/middleware/errorhandler.md b/de/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..d6e4cf35e9 --- /dev/null +++ b/de/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: de +redirect_from: " " +module: errorhandler +--- diff --git a/de/resources/middleware/method-override.md b/de/resources/middleware/method-override.md new file mode 100644 index 0000000000..022aef76af --- /dev/null +++ b/de/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: de +redirect_from: " " +module: method-override +--- diff --git a/de/resources/middleware/morgan.md b/de/resources/middleware/morgan.md new file mode 100644 index 0000000000..1532eec13c --- /dev/null +++ b/de/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: de +redirect_from: " " +module: morgan +--- diff --git a/de/resources/middleware/multer.md b/de/resources/middleware/multer.md new file mode 100644 index 0000000000..9e2f04a64c --- /dev/null +++ b/de/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: de +redirect_from: " " +module: multer +--- diff --git a/de/resources/middleware/response-time.md b/de/resources/middleware/response-time.md new file mode 100644 index 0000000000..ca89fcc293 --- /dev/null +++ b/de/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: de +redirect_from: " " +module: response-time +--- diff --git a/de/resources/middleware/serve-favicon.md b/de/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..cef0168702 --- /dev/null +++ b/de/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: de +redirect_from: " " +module: serve-favicon +--- diff --git a/de/resources/middleware/serve-index.md b/de/resources/middleware/serve-index.md new file mode 100644 index 0000000000..edeb954799 --- /dev/null +++ b/de/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: de +redirect_from: " " +module: serve-index +--- diff --git a/de/resources/middleware/serve-static.md b/de/resources/middleware/serve-static.md new file mode 100644 index 0000000000..e084feefec --- /dev/null +++ b/de/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: de +redirect_from: " " +module: serve-static +--- diff --git a/de/resources/middleware/session.md b/de/resources/middleware/session.md new file mode 100644 index 0000000000..d94dc4f988 --- /dev/null +++ b/de/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: de +redirect_from: " " +module: session +--- diff --git a/de/resources/middleware/timeout.md b/de/resources/middleware/timeout.md new file mode 100644 index 0000000000..e201a56db8 --- /dev/null +++ b/de/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: de +redirect_from: " " +module: timeout +--- diff --git a/de/resources/middleware/vhost.md b/de/resources/middleware/vhost.md new file mode 100644 index 0000000000..b3df125d8e --- /dev/null +++ b/de/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: de +redirect_from: " " +module: vhost +--- diff --git a/de/resources/utils.md b/de/resources/utils.md new file mode 100644 index 0000000000..02f14abb88 --- /dev/null +++ b/de/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: de +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | Beschreibung | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/de/starter/basic-routing.md b/de/starter/basic-routing.md old mode 100755 new mode 100644 index b50d355504..c61da3dbc3 --- a/de/starter/basic-routing.md +++ b/de/starter/basic-routing.md @@ -4,20 +4,22 @@ title: Basisrouting in Express 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. menu: starter lang: de +redirect_from: " " --- # Basisrouting -Per *Routing* wird bestimmt, wie eine Antwort auf eine Clientanforderung an einem bestimmten Endpunkt antwortet. Dies ist eine URI (oder ein Pfad) und eine bestimmte HTTP-Anforderungsmethode (GET, POST usw.). +Per _Routing_ wird bestimmt, wie eine Antwort auf eine Clientanforderung an einem bestimmten Endpunkt antwortet. Dies ist eine URI (oder ein Pfad) und eine bestimmte HTTP-Anforderungsmethode (GET, POST usw.). Jede Weiterleitung (Route) kann eine oder mehrere Handlerfunktionen haben, die ausgeführt werden, wenn die Weiterleitung abgeglichen wird. Weiterleitungsdefinitionen haben die folgende Struktur: + ```js app.METHOD(PATH, HANDLER) ``` -Bedeutung: +Where: - `app` ist eine Instanz von `express`. - `METHOD` ist eine [HTTP-Anforderungsmethode](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol). @@ -63,3 +65,5 @@ app.delete('/user', (req, res) => { ``` Details zum Thema Routing finden Sie in der entsprechenden [Routinganleitung](/{{ page.lang }}/guide/routing.html). + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/de/starter/examples.md b/de/starter/examples.md new file mode 100644 index 0000000000..659c801018 --- /dev/null +++ b/de/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: de +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/de/starter/faq.md b/de/starter/faq.md old mode 100755 new mode 100644 index 9cbd67ba54..63260dd76b --- a/de/starter/faq.md +++ b/de/starter/faq.md @@ -4,6 +4,7 @@ title: Häufig gestellte Fragen zu Express description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: de +redirect_from: " " --- # Häufig gestellte Fragen @@ -14,14 +15,13 @@ Auf diese Frage gibt es keine verbindliche Antwort. Die Antwort hängt vom Umfan Weiterleitungen und andere anwendungsspezifische Logik können in einer beliebigen Anzahl von Dateien und in jeder von Ihnen bevorzugten Verzeichnisstruktur vorkommen. Die folgenden Beispiele sollen als Entscheidungshilfe dienen: - -* [Weiterleitungslisten](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [Weiterleitungszuordnung](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [Controller im MVC-Stil](https://github.com/expressjs/express/tree/master/examples/mvc) +- [Weiterleitungslisten](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [Weiterleitungszuordnung](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [Controller im MVC-Stil](https://github.com/expressjs/express/tree/master/examples/mvc) Darüber hinaus gibt es Erweiterungen anderer Anbieter für Express, die zur Vereinfachung einiger dieser Muster beitragen: -* [Weiterleitung mit "express-resource"](https://github.com/expressjs/express-resource) +- [Weiterleitung mit "express-resource"](https://github.com/expressjs/express-resource) ## Wie definiere ich Modelle? @@ -31,12 +31,15 @@ Express hat keine Vorstellungen von einer Datenbank. Dieses Konzept bleibt Node- ## Wie kann ich Benutzer authentifizieren? -Die Authentifizierung ist ein weiterer meinungsstarker Bereich, in den Express nicht eingreift. Sie können ein Authentifizierungsschema nach Ihren Vorstellungen verwenden. Ein einfaches Benutzername/Kennwort-Schema können Sie in [diesem Beispiel](https://github.com/expressjs/express/tree/master/examples/auth) sehen. - +Die Authentifizierung ist ein weiterer meinungsstarker Bereich, in den Express nicht eingreift. Sie können ein Authentifizierungsschema nach Ihren Vorstellungen verwenden. +Ein einfaches Benutzername/Kennwort-Schema können Sie in [diesem Beispiel](https://github.com/expressjs/express/tree/master/examples/auth) sehen. ## Welche Template-Engines unterstützt Express? -Express unterstützt jede Template-Engine, die der `(path, locals, callback)`-Signatur entspricht. Informationen zur Normalisierung von Template-Engine-Schnittstellen und -Caching siehe das Projekt [consolidate.js](https://github.com/visionmedia/consolidate.js). Nicht aufgelistete Template-Engines können trotzdem die Express-Signatur unterstützen. +Express unterstützt jede Template-Engine, die der `(path, locals, callback)`-Signatur entspricht. +Informationen zur Normalisierung von Template-Engine-Schnittstellen und -Caching siehe das Projekt [consolidate.js](https://github.com/visionmedia/consolidate.js). Nicht aufgelistete Template-Engines können trotzdem die Express-Signatur unterstützen. + +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). ## Wie handhabe ich 404-Antworten? @@ -44,10 +47,13 @@ In Express sind 404-Antworten nicht das Ergebnis eines Fehlers, sodass diese Ant ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## Wie richte ich eine Fehlerbehandlungsroutine ein? Middleware für die Fehlerbehandlung wird in derselben Weise definiert wie andere Middleware; außer dass sie vier anstatt drei Argumente aufweist. Dies gilt speziell bei der Signatur `(err, req, res, next)`: @@ -63,4 +69,13 @@ Weitere Informationen siehe [Fehlerbehandlung](/{{ page.lang }}/guide/error-hand ## Wie gebe ich normales HTML-Format aus? -Das ist nicht Ihre Aufgabe! Sie müssen kein HTML-Format mit der Funktion `res.render()` ausgeben. Verwenden Sie die Funktion `res.sendFile()`, wenn Sie es mit einer bestimmten Datei zu tun haben. Wenn Sie viele Assets aus einem Verzeichnis bedienen müssen, verwenden Sie die Middlewarefunktion `express.static()`. +Das ist nicht Ihre Aufgabe! Sie müssen kein HTML-Format mit der Funktion `res.render()` ausgeben. +Verwenden Sie die Funktion `res.sendFile()`, wenn Sie es mit einer bestimmten Datei zu tun haben. +Wenn Sie viele Assets aus einem Verzeichnis bedienen müssen, verwenden Sie die Middlewarefunktion `express.static()`. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/de/starter/generator.md b/de/starter/generator.md old mode 100755 new mode 100644 index ddc9e004c5..c4b332395f --- a/de/starter/generator.md +++ b/de/starter/generator.md @@ -4,16 +4,24 @@ title: Express-Anwendungsgenerator description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: de +redirect_from: " " --- # Express-Anwendungsgenerator Mit dem Application Generator Tool `express` können Sie innerhalb kürzester Zeit ein Anwendungsgerüst erstellen. -Installieren Sie `express` mit dem folgenden Befehl: +You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash -$ npm install express-generator -g +$ npx express-generator +``` + +For earlier Node versions, install the application generator as a global npm package and then launch it: + +```bash +$ npm install -g express-generator +$ express ``` Zeigen Sie die Befehlsoptionen mit der Option `-h` an: @@ -21,7 +29,7 @@ Zeigen Sie die Befehlsoptionen mit der Option `-h` an: ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -32,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -Im folgenden Beispiel wird eine Express-Anwendung mit dem Namen _myapp_ im aktuellen Arbeitsverzeichnis erstellt: +Im folgenden Beispiel wird eine Express-Anwendung mit dem Namen _myapp_ im aktuellen Arbeitsverzeichnis erstellt: The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -69,18 +77,24 @@ $ cd myapp $ npm install ``` -Führen Sie unter MacOS oder Linux die Anwendung mit diesem Befehl aus: +Verwenden Sie unter Windows diesen Befehl: ```bash $ DEBUG=myapp:* npm start ``` -Verwenden Sie unter Windows diesen Befehl: +Führen Sie unter MacOS oder Linux die Anwendung mit diesem Befehl aus: ```bash > set DEBUG=myapp:* & npm start ``` +On Windows PowerShell, use this command: + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + Laden Sie dann `http://localhost:3000/` in Ihren Browser, um auf die Anwendung zuzugreifen. Die erstellte Anwendung hat die folgende Verzeichnisstruktur: @@ -110,3 +124,5 @@ Die erstellte Anwendung hat die folgende Verzeichnisstruktur:
Die vom Generator erstellte Anwendungsstruktur ist nur eine der vielen Möglichkeiten, Express-Anwendungen zu strukturieren. Sie können diese Struktur verwenden oder sie an Ihre Anforderungen anpassen.
+ +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/de/starter/hello-world.md b/de/starter/hello-world.md old mode 100755 new mode 100644 index cfeff70e13..f2b85513cb --- a/de/starter/hello-world.md +++ b/de/starter/hello-world.md @@ -4,6 +4,7 @@ title: Beispiel "Hello World" in Express description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: de +redirect_from: " " --- # Beispiel "Hello World" @@ -12,10 +13,6 @@ lang: de Dies ist wohl die einfachste Express-Anwendung, die Sie erstellen können. Es handelt sich um eine Anwendung mit nur einer Datei und — *nicht* das, was Sie mit dem [Express Generator](/{{ page.lang }}/starter/generator.html) erhalten würden. Mit dem Generator würde das Gerüst für eine vollständige Anwendung mit zahlreichen JavaScript-Dateien, Jade-Vorlagen und Unterverzeichnissen für verschiedene Zwecke erstellt werden.
-Erstellen Sie zunächst ein Verzeichnis namens `myapp`, wechseln Sie in das Verzeichnis und führen Sie `npm init` aus. Installieren Sie dann `express` als Abhängigkeit, wie im [Installationshandbuch](/{{ page.lang }}/starter/installing.html) beschrieben. - -Erstellen Sie im Verzeichnis `myapp` eine Datei namens `app.js` und fügen Sie den folgenden Code hinzu: - ```js const express = require('express') const app = express() @@ -30,11 +27,15 @@ app.listen(port, () => { }) ``` -Die Anwendung startet einen Server und ist an Port 3000 empfangsbereit für Verbindungen. Die Anwendung antwortet mit "Hello World!" auf Anforderungen zur Stamm-URL (`/`) oder zu *route*. Bei jedem anderen Pfad lautet die Antwort **404 Not Found**. +Die Anwendung startet einen Server und ist an Port 3000 empfangsbereit für Verbindungen. Die Anwendung antwortet mit "Hello World!" auf Anforderungen zur Stamm-URL (`/`) oder zu _route_. Bei jedem anderen Pfad lautet die Antwort **404 Not Found**. -
-`req` (Anforderung) und `res` (Antwort) sind genau dieselben Objekte, die Node bereitstellt. Sie können also `req.pipe()`, `req.on('data', callback)` und alle anderen Tasks, die Sie ausführen wollen, ohne Express ausführen. -
+### Running Locally + +Erstellen Sie zunächst ein Verzeichnis namens `myapp`, wechseln Sie in das Verzeichnis und führen Sie `npm init` aus. Installieren Sie dann `express` als Abhängigkeit, wie im [Installationshandbuch](/{{ page.lang }}/starter/installing.html) beschrieben. + +Erstellen Sie im Verzeichnis `myapp` eine Datei namens `app.js` und fügen Sie den folgenden Code hinzu: + +
`req` (Anforderung) und `res` (Antwort) sind genau dieselben Objekte, die Node bereitstellt. Sie können also `req.pipe()`, `req.on('data', callback)` und alle anderen Tasks, die Sie ausführen wollen, ohne Express ausführen.
Führen Sie die Anwendung mit dem folgenden Befehl aus: @@ -44,3 +45,4 @@ $ node app.js Laden Sie dann [http://localhost:3000/](http://localhost:3000/) in einen Browser, um die Ausgabe zu sehen. +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/de/starter/installing.md b/de/starter/installing.md old mode 100755 new mode 100644 index c2356700c2..b6bd8407f6 --- a/de/starter/installing.md +++ b/de/starter/installing.md @@ -4,26 +4,32 @@ title: Express installieren description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: de +redirect_from: " " --- # Installation Angenommen, Sie haben [Node.js](https://nodejs.org/) bereits installiert. Erstellen Sie ein Verzeichnis für Ihre Anwendung und definieren Sie dieses Verzeichnis als Ihr Arbeitsverzeichnis. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp ``` -Erstellen Sie mit dem Befehl `npm init` eine Datei namens `package.json` für Ihre Anwendung. Weitere Informationen zur Funktionsweise von `package.json` finden Sie in den [Angaben zur Handhabung der npm-Datei package.json](https://docs.npmjs.com/files/package.json). +Erstellen Sie mit dem Befehl `npm init` eine Datei namens `package.json` für Ihre Anwendung. +Weitere Informationen zur Funktionsweise von `package.json` finden Sie in den [Angaben zur Handhabung der npm-Datei package.json](https://docs.npmjs.com/files/package.json). ```bash $ npm init ``` -Dieser Befehl fordert Sie zur Eingabe verschiedener Angaben wie Name und Version Ihrer Anwendung auf. Für den Moment reicht es, die Eingabetaste zu drücken und die Standardwerte für die meisten Angaben zu akzeptieren. Es gilt jedoch folgende Ausnahme: +Dieser Befehl fordert Sie zur Eingabe verschiedener Angaben wie Name und Version Ihrer Anwendung auf. +For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception: -```bash +``` entry point: (index.js) ``` @@ -32,15 +38,17 @@ Geben Sie `app.js` oder einen Namen Ihrer Vorstellung als Namen für die Hauptda Installieren Sie jetzt Express im Verzeichnis `myapp` und speichern Sie es in der Abhängigkeitsliste. Beispiel: ```bash -$ npm install express --save +$ npm install express ``` Wenn Sie Express vorübergehend installieren und nicht zur Abhängigkeitsliste hinzufügen wollen, geben Sie die Option `--save` nicht an: ```bash -$ npm install express +$ npm install express --no-save ```
Node-Module, die mit der Option `--save` installiert werden, werden zur `Abhängigkeitsliste` in der Datei `package.json` hinzugefügt. Danach werden bei der Ausführung von `npm install` im Verzeichnis `app` automatisch alle Module in der Abhängigkeitsliste installiert.
+ +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/de/starter/static-files.md b/de/starter/static-files.md old mode 100755 new mode 100644 index c9c674bf32..cfc96142f2 --- a/de/starter/static-files.md +++ b/de/starter/static-files.md @@ -4,13 +4,23 @@ title: Statische Dateien in Express bereitstellen description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: de +redirect_from: " " --- # Statische Dateien in Express bereitstellen Wenn Sie statische Dateien wie Bilder, CSS-Dateien und JavaScript-Dateien bereitstellen wollen, verwenden Sie die in Express integrierte Middlewarefunktion `express.static`. -Übergeben Sie den Namen des Verzeichnisses mit den statischen Assets an die Middlewarefunktion `express.static`, um direkt mit dem Bereitstellen der Dateien zu beginnen. Beispiel: Verwenden Sie den folgenden Code, um Bilder, CSS-Dateien und JavaScript-Dateien in einem Verzeichnis namens `public` bereitzustellen: +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](/{{page.lang}}/4x/api.html#express.static). + +Beispiel: Verwenden Sie den folgenden Code, um Bilder, CSS-Dateien und JavaScript-Dateien in einem Verzeichnis namens `public` bereitzustellen: ```js app.use(express.static('public')) @@ -26,8 +36,7 @@ http://localhost:3000/images/bg.png http://localhost:3000/hello.html ``` -
-Express sucht nach den Dateien, die sich auf das Verzeichnis mit den statischen Assets beziehen. Der Name dieses Verzeichnisses ist also nicht Teil der URL.
+
Express sucht nach den Dateien, die sich auf das Verzeichnis mit den statischen Assets beziehen. Der Name dieses Verzeichnisses ist also nicht Teil der URL.
Wenn Sie mehrere Verzeichnisse mit statischen Assets verwenden wollen, rufen Sie die Middlewarefunktion `express.static` mehrmals auf: @@ -38,6 +47,11 @@ app.use(express.static('files')) Express sucht in der Reihenfolge nach den Dateien, in der sie die Verzeichnisse mit den statischen Assets über die Middlewarefunktion `express.static` festgelegt haben. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + Wenn Sie ein Präfix für einen virtuellen Pfad (in dem der Pfad nicht wirklich im Dateisystem existiert) für Dateien festlegen wollen, die über die Funktion `express.static` bereitgestellt werden, [müssen Sie einen Mountpfad](/{{ page.lang }}/4x/api.html#app.use) für das Verzeichnis mit den statischen Assets wie unten gezeigt angeben: ```js @@ -60,3 +74,7 @@ Der Pfad, den Sie für die Funktion `express.static` angeben, ist jedoch relativ const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/de/support/index.md b/de/support/index.md index 1f1c15b326..3b8f83c223 100644 --- a/de/support/index.md +++ b/de/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: de --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/es/3x/api.md b/es/3x/api.md old mode 100755 new mode 100644 index 2f66699741..4a4087260f --- a/es/3x/api.md +++ b/es/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - Referencia de API -lang: es -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. +lang: en +redirect_from: " " --- +
**Express 3.x YA NO SE MANTIENE** - Los problemas de rendimiento y seguridad conocidos y desconocidos en 3.x no se han solucionado desde la última actualización (1 de agosto de 2015). Se recomienda especialmente utilizar la última versión de Express. -
- -

API de 3.x

+Los problemas de rendimiento y seguridad conocidos y desconocidos en 3.x no se han solucionado desde la última actualización (1 de agosto de 2015). Se recomienda especialmente utilizar la última versión de Express. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
- - {% include api/en/3x/res.md %} +

API de 3.x

- - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %} diff --git a/es/4x/api.md b/es/4x/api.md old mode 100755 new mode 100644 index bc90b2e805..a8662e41be --- a/es/4x/api.md +++ b/es/4x/api.md @@ -2,27 +2,26 @@ layout: api version: 4x title: Express 4.x - Referencia de API -lang: es -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. +lang: en +redirect_from: " " --- +

API de 4.x

- - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
diff --git a/es/5x/api.md b/es/5x/api.md index 2b4353924c..bcf7dc62cd 100644 --- a/es/5x/api.md +++ b/es/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - Referencia de API -lang: es -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. +lang: en +redirect_from: " " ---

5.x API

-{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/es/advanced/best-practice-performance.md b/es/advanced/best-practice-performance.md old mode 100755 new mode 100644 index cfeba1a566..227feddb69 --- a/es/advanced/best-practice-performance.md +++ b/es/advanced/best-practice-performance.md @@ -1,53 +1,49 @@ --- layout: page title: Mejores prácticas de rendimiento cuando se utiliza Express en producción +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced -lang: es -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +lang: en +redirect_from: " " --- -# Mejores prácticas de producción: rendimiento y fiabilidad - -## Visión general +# Production best practices: performance and reliability En este artículo se describen las mejores prácticas de rendimiento y fiabilidad para las aplicaciones Express desplegadas en producción. Este tema entra claramente dentro del área de "DevOps", que abarca operaciones y desarrollos tradicionales. Por lo tanto, la información se divide en dos partes: -- Cosas que hacer en el código (la parte de desarrollo): - - [Utilizar la compresión de gzip](#utilizar-la-compresión-de-gzip) - - [No utilizar funciones síncronas](#no-utilizar-funciones-síncronas) - - [Realizar un registro correcto](#realizar-un-registro-correcto) - - [Manejar las excepciones correctamente](#manejar-las-excepciones-correctamente) -- Cosas que hacer en el entorno / configuración (la parte de operaciones): - - - [Establecer NODE_ENV en "production"](#establecer-node_env-en-production) - - [Asegurarse de que la aplicación se reinicia automáticamente](#asegurarse-de-que-la-aplicación-se-reinicia-automáticamente) - - [Ejecutar la aplicación en un clúster](#ejecutar-la-aplicación-en-un-clúster) - - [Almacenar en la caché los resultados de la solicitud](#almacenar-en-la-caché-los-resultados-de-la-solicitud) - - [Utilizar un equilibrador de carga](#utilizar-un-equilibrador-de-carga) - - [Utilizar un proxy inverso](#utilizar-un-proxy-inverso) - - +- Cosas que hacer en el código (la parte de desarrollo): + - [Utilizar la compresión de gzip](#utilizar-la-compresión-de-gzip) + - [No utilizar funciones síncronas](#no-utilizar-funciones-síncronas) + - [Realizar un registro correcto](#realizar-un-registro-correcto) + - [Manejar las excepciones correctamente](#manejar-las-excepciones-correctamente) +- Cosas que hacer en el entorno / configuración (la parte de operaciones): + - [Establecer NODE_ENV en "production"](#establecer-node_env-en-production) + - [Asegurarse de que la aplicación se reinicia automáticamente](#asegurarse-de-que-la-aplicación-se-reinicia-automáticamente) + - [Ejecutar la aplicación en un clúster](#ejecutar-la-aplicación-en-un-clúster) + - [Almacenar en la caché los resultados de la solicitud](#almacenar-en-la-caché-los-resultados-de-la-solicitud) + - [Utilizar un equilibrador de carga](#utilizar-un-equilibrador-de-carga) + - [Utilizar un proxy inverso](#utilizar-un-proxy-inverso) ## Cosas que hacer en el código Estas son algunas de las cosas que puede hacer en el código para mejorar el rendimiento de la aplicación: -- [Utilizar la compresión de gzip](#utilizar-la-compresión-de-gzip) -- [No utilizar funciones síncronas](#no-utilizar-funciones-síncronas) -- [Realizar un registro correcto](#realizar-un-registro-correcto) -- [Manejar las excepciones correctamente](#manejar-las-excepciones-correctamente) +- [Utilizar la compresión de gzip](#utilizar-la-compresión-de-gzip) +- [No utilizar funciones síncronas](#no-utilizar-funciones-síncronas) +- [Realizar un registro correcto](#realizar-un-registro-correcto) +- [Manejar las excepciones correctamente](#manejar-las-excepciones-correctamente) ### Utilizar la compresión de gzip -La compresión de gzip puede disminuir significativamente el tamaño del cuerpo de respuesta y, por lo tanto, aumentar la velocidad de una aplicación web. Utilice el middleware de [compresión](https://www.npmjs.com/package/compression) para la compresión de gzip en la aplicación Express. Por ejemplo: +La compresión de gzip puede disminuir significativamente el tamaño del cuerpo de respuesta y, por lo tanto, aumentar la velocidad de una aplicación web. Utilice el middleware de [compresión](https://www.npmjs.com/package/compression) para la compresión de gzip en la aplicación Express. For example: ```js const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` @@ -59,21 +55,19 @@ Las funciones síncronas y los métodos impiden el avance del proceso de ejecuci Aunque Node y muchos módulos proporcionan versiones síncronas y asíncronas de las funciones, utilice siempre la versión asíncrona en producción. La única vez que está justificado utilizar una función síncrona es en el arranque inicial. -Si utiliza Node.js 4.0+ o io.js 2.1.0+, puede utilizar el distintivo de línea de mandatos `--trace-sync-io` para imprimir un aviso y un seguimiento de la pila siempre que la aplicación utilice una API síncrona. Desde luego, no deseará utilizarlo en producción, sólo para garantizar que el código está listo para producción. Consulte [Weekly update for io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0) para obtener 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. Desde luego, no deseará utilizarlo en producción, sólo para garantizar que el código está listo para producción. Consulte [Weekly update for io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0) para obtener más información. ### Realizar un registro correcto -En general, hay dos motivos para realizar un registro desde la aplicación: a efectos de depuración o para registrar la actividad de la aplicación (básicamente, todo lo demás). El uso de `console.log()` o `console.err()` para imprimir mensajes de registro en el terminal es una práctica común en el desarrollo. No obstante, [estas funciones son síncronas](https://nodejs.org/api/console.html#console_console_1) cuando el destino es un terminal o un archivo, por lo que no son adecuadas para producción, a menos que canalice la salida a otro programa. +En general, hay dos motivos para realizar un registro desde la aplicación: a efectos de depuración o para registrar la actividad de la aplicación (básicamente, todo lo demás). El uso de `console.log()` o `console.err()` para imprimir mensajes de registro en el terminal es una práctica común en el desarrollo. 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. -#### A efectos de depuración +#### For debugging Si realiza el registro a efectos de depuración, en lugar de utilizar `console.log()`, utilice un módulo de depuración especial como [debug](https://www.npmjs.com/package/debug). Este módulo permite utilizar la variable de entorno DEBUG para controlar qué mensajes de depuración se envían a `console.err()`, si se envía alguno. Para mantener la aplicación básicamente asíncrona, deberá canalizar `console.err()` a otro programa. Pero en este caso, realmente no va a depurar en producción, ¿no? #### Para la actividad de la aplicación -Si está registrando la actividad de la aplicación (por ejemplo, realizando un seguimiento del tráfico o las llamadas de API), en lugar de utilizar `console.log()`, utilice una biblioteca de registro como [Winston](https://www.npmjs.com/package/winston) o [Bunyan](https://www.npmjs.com/package/bunyan). Para ver una comparación detallada de estas dos bibliotecas, consulte el post del blog StrongLoop [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/). - - +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 las excepciones correctamente @@ -81,32 +75,19 @@ Las aplicaciones Node se bloquean cuando encuentran una excepción no capturada. Para asegurarse de manejar todas las excepciones, siga estas técnicas: -- [Utilizar try-catch](#try-catch) -- [Utilizar promesas](#utilizar-promesas) +- [Utilizar try-catch](#try-catch) +- [Utilizar promesas](#utilizar-promesas) Antes de profundizar en estos temas, deberá tener unos conocimientos básicos del manejo de errores de Node/Express: el uso de devoluciones de llamada error-first y la propagación de errores en el middleware. Node utiliza un convenio de "devolución de llamada error-first" para devolver los errores de las funciones asíncronas, donde el primer parámetro en la función de devolución de llamada es el objeto de error, seguido de los datos de resultados en los parámetros posteriores. Para indicar que no hay ningún error, pase null como el primer parámetro. La función de devolución de llamada debe seguir por lo tanto el convenio de devolución de llamada error-first para manejar correctamente el error. En Express, la práctica recomendada es utilizar la función next() para propagar los errores a través de la cadena de middleware. Para obtener más información sobre los aspectos básicos del manejo de errores, consulte: -- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -- [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (blog StrongLoop) - -#### Qué no debe hacer - -Algo que _no_ debe hacer es escuchar el suceso `uncaughtException`, que se emite cuando una excepción se reproduce hacia atrás en el bucle de sucesos. La adición de un escucha de sucesos para `uncaughtException` cambiará el comportamiento predeterminado del proceso que se encuentra con la excepción; el proceso continuará ejecutándose a pesar de la excepción. Esto puede parecer una buena forma de evitar el bloqueo de la aplicación, pero continuar ejecutando la aplicación después de una excepción no capturada es una práctica peligrosa y no se recomienda, ya que el estado del proceso se vuelve imprevisible y poco fiable. - -Asimismo, el uso de `uncaughtException` se reconoce oficialmente como un mecanismo [arduo](https://nodejs.org/api/process.html#process_event_uncaughtexception) y hay una [propuesta](https://github.com/nodejs/node-v0.x-archive/issues/2582) para eliminarlo del núcleo. Por lo tanto, la escucha `uncaughtException` no es una buena idea. Es por esto por lo que se recomiendan varios procesos y supervisores; el bloqueo y el reinicio es a menudo la forma más fiable de recuperarse de un error. - -Tampoco se recomienda el uso de [dominios](https://nodejs.org/api/domain.html). Generalmente no soluciona el problema y es un módulo en desuso. - - +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### Utilizar try-catch Try-catch es una construcción de lenguaje JavaScript que puede utilizar para capturar excepciones en código síncrono. Por ejemplo, utilice try-catch para manejar los errores de análisis de JSON, como se muestra a continuación. -Utilice una herramienta como [JSHint](http://jshint.com/) o [JSLint](http://www.jslint.com/) para buscar excepciones implícitas como [errores de referencia o variables sin definir](http://www.jshint.com/docs/options/#undef). - A continuación, se muestra un ejemplo de uso de try-catch para manejar una posible excepción de bloqueo de proceso. Esta función de middleware acepta un parámetro de campo de consulta denominado "params" que es un objeto JSON. @@ -127,100 +108,86 @@ app.get('/search', (req, res) => { No obstante, try-catch sólo funciona para el código síncrono. Como la plataforma de Node es principalmente asíncrona (particularmente en un entorno de producción), try-catch no capturará muchas excepciones. - +#### Use promises -#### Utilizar promesas - -Las promesas manejarán todas las excepciones (explícitas e implícitas) en los bloques de códigos asíncronos que utilicen `then()`. Sólo tiene que añadir `.catch(next)` al final de las cadenas de promesas. Por ejemplo: +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -Ahora todos los errores, asíncronos y síncronos, se propagarán al middleware de errores. - -No obstante, hay dos advertencias: - -1. Todo el código asíncrono debe devolver promesas (excepto los emisores). Si una determinada biblioteca no devuelve promesas, convierta el objeto base utilizando una función de ayuda como [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html). -2. Los emisores de sucesos (como las secuencias) todavía pueden provocar excepciones no capturadas. Por lo tanto, asegúrese de que está manejando el suceso de error correctamente; por ejemplo: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -La función `wrap()` es un envoltorio que toma las promesas rechazadas y llama a `next()` con el error como primer argumento. Para más detalles, vea [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/). +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. -Para más información acerca del manejo de errores utilizando promesas, vea [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/). +#### Qué no debe hacer -## Cosas que hacer en el entorno / configuración +Algo que _no_ debe hacer es escuchar el suceso `uncaughtException`, que se emite cuando una excepción se reproduce hacia atrás en el bucle de sucesos. La adición de un escucha de sucesos para `uncaughtException` cambiará el comportamiento predeterminado del proceso que se encuentra con la excepción; el proceso continuará ejecutándose a pesar de la excepción. Esto puede parecer una buena forma de evitar el bloqueo de la aplicación, pero continuar ejecutando la aplicación después de una excepción no capturada es una práctica peligrosa y no se recomienda, ya que el estado del proceso se vuelve imprevisible y poco fiable. -Estas son algunas de las cosas que puede hacer en el entorno del sistema para mejorar el rendimiento de la aplicación: +Asimismo, el uso de `uncaughtException` se reconoce oficialmente como un mecanismo [arduo](https://nodejs.org/api/process.html#process_event_uncaughtexception) y hay una [propuesta](https://github.com/nodejs/node-v0.x-archive/issues/2582) para eliminarlo del núcleo. Por lo tanto, la escucha `uncaughtException` no es una buena idea. Es por esto por lo que se recomiendan varios procesos y supervisores; el bloqueo y el reinicio es a menudo la forma más fiable de recuperarse de un error. -- [Establecer NODE_ENV en "production"](#establecer-node_env-en-production) -- [Asegurarse de que la aplicación se reinicia automáticamente](#asegurarse-de-que-la-aplicación-se-reinicia-automáticamente) -- [Ejecutar la aplicación en un clúster](#ejecutar-la-aplicación-en-un-clúster) -- [Almacenar en la caché los resultados de la solicitud](#almacenar-en-la-caché-los-resultados-de-la-solicitud) -- [Utilizar un equilibrador de carga](#utilizar-un-equilibrador-de-carga) -- [Utilizar un proxy inverso](#utilizar-un-proxy-inverso) +Tampoco se recomienda el uso de [dominios](https://nodejs.org/api/domain.html). Generalmente no soluciona el problema y es un módulo en desuso. -### Establecer NODE_ENV en "production" +## Things to do in your environment / setup -La variable de entorno NODE_ENV especifica el entorno en el que se ejecuta una aplicación (normalmente, desarrollo o producción). Una de las cosas más sencillas que puede hacer para mejorar el rendimiento es establecer NODE_ENV en "production". +{#in-environment} -Si establece NODE_ENV en "production", Express: +Estas son algunas de las cosas que puede hacer en el entorno del sistema para mejorar el rendimiento de la aplicación: -- Almacena en la caché las plantillas de vistas. -- Almacena en la caché los archivos CSS generados en las extensiones CSS. -- Genera menos mensajes de error detallados. +- [Establecer NODE_ENV en "production"](#establecer-node_env-en-production) +- [Asegurarse de que la aplicación se reinicia automáticamente](#asegurarse-de-que-la-aplicación-se-reinicia-automáticamente) +- [Ejecutar la aplicación en un clúster](#ejecutar-la-aplicación-en-un-clúster) +- [Almacenar en la caché los resultados de la solicitud](#almacenar-en-la-caché-los-resultados-de-la-solicitud) +- [Utilizar un equilibrador de carga](#utilizar-un-equilibrador-de-carga) +- [Utilizar un proxy inverso](#utilizar-un-proxy-inverso) -Las [pruebas indican](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) que sólo esta acción puede mejorar hasta tres veces el rendimiento de la aplicación. +### Establecer NODE_ENV en "production" -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 una variable de entorno supone una reducción de rendimiento, por lo que debe hacerse moderadamente. +La variable de entorno NODE_ENV especifica el entorno en el que se ejecuta una aplicación (normalmente, desarrollo o producción). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. -En el desarrollo, normalmente establece las variables de entorno en el shell interactivo, por ejemplo, utilizando `export` o su archivo `.bash_profile`. Sin embargo, en general, no debe hacerlo en un servidor de producción; en su lugar, utilice el sistema init de su sistema operativo (systemd o Upstart). En la siguiente sección se proporcionan más detalles sobre el uso del sistema init en general, pero el establecimiento de NODE_ENV es tan importante (y fácil de hacer) para el rendimiento, que se resalta aquí. +Si establece NODE_ENV en "production", Express: -Con Upstart, utilice la palabra clave `env` en el archivo de trabajo. Por ejemplo: +- Almacena en la caché las plantillas de vistas. +- Almacena en la caché los archivos CSS generados en las extensiones CSS. +- Genera menos mensajes de error detallados. -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` +[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! -Para obtener más información, consulte [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables). +If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Tenga en cuenta que comprobar el valor de una variable de entorno supone una reducción de rendimiento, por lo que debe hacerse moderadamente. -Con systemd, utilice la directiva `Environment` en el archivo unit. Por ejemplo: +En el desarrollo, normalmente establece las variables de entorno en el shell interactivo, por ejemplo, utilizando `export` o su archivo `.bash_profile`. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). En la siguiente sección se proporcionan más detalles sobre el uso del sistema init en general, pero el establecimiento de NODE_ENV es tan importante (y fácil de hacer) para el rendimiento, que se resalta aquí. + +Con systemd, utilice la directiva `Environment` en el archivo unit. For example: ```sh # /etc/systemd/system/myservice.service Environment=NODE_ENV=production ``` -Para obtener más información, consulte [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html). - -Si está utilizando StrongLoop Process Manager, también puede [establecer la variable de entorno cuando instala StrongLoop PM como un servicio](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables). +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Asegurarse de que la aplicación se reinicia automáticamente En la producción, no desea que la aplicación esté nunca fuera de línea. Esto significa que debe asegurarse de que se reinicia si la aplicación o el servidor se bloquean. Aunque espera que no se produzca ninguno de estos sucesos, si somos realistas, debe tener en cuenta ambas eventualidades de la siguiente manera: -- Utilizando un gestor de procesos para reiniciar la aplicación (y Node) cuando se bloquea. -- Utilizando el sistema init que proporciona su sistema operativo para reiniciar el gestor de procesos cuando se bloquea el sistema operativo. También puede utilizar el sistema init sin un gestor de procesos. +- Utilizando un gestor de procesos para reiniciar la aplicación (y Node) cuando se bloquea. +- Utilizando el sistema init que proporciona su sistema operativo para reiniciar el gestor de procesos cuando se bloquea el sistema operativo. También puede utilizar el sistema init sin un gestor de procesos. Las aplicaciones Node se bloquean si encuentran una excepción no capturada. Lo primero que debe hacer es asegurarse de que se realizan las pruebas correctas en la aplicación y que se manejan todas las excepciones (consulte [Manejar correctamente las excepciones](#exceptions) para obtener detalles). No obstante, para estar libre de errores, aplique un mecanismo para garantizar que cuando se bloquee la aplicación, se reinicie automáticamente. @@ -230,54 +197,35 @@ En el desarrollo, la aplicación se inicia simplemente desde la línea de mandat Además de reiniciar la aplicación cuando se bloquea, un gestor de procesos permite: -- Obtener información útil sobre el rendimiento en tiempo de ejecución y el consumo de recursos. -- Modificar dinámicamente los valores para mejorar el rendimiento. -- Controlar la agrupación en clúster (StrongLoop PM y pm2). +- Obtener información útil sobre el rendimiento en tiempo de ejecución y el consumo de recursos. +- Modificar dinámicamente los valores para mejorar el rendimiento. +- Control clustering (pm2). -Los gestores de procesos más conocidos para Node son los siguientes: - -- [StrongLoop Process Manager](http://strong-pm.io/) -- [PM2](https://github.com/Unitech/pm2) -- [Forever](https://www.npmjs.com/package/forever) - -Para ver una comparación característica a característica de los tres gestores de procesos, consulte [http://strong-pm.io/compare/](http://strong-pm.io/compare/). - -El uso de cualquiera de estos gestores de procesos bastará para mantener activa la aplicación, aunque se bloquee cada cierto tiempo. - -No obstante, StrongLoop PM tiene muchas características especialmente indicadas para el despliegue de producción. Puede utilizarlo y las herramientas relacionadas de StrongLoop para: - -- Crear y empaquetar la aplicación localmente y, a continuación, desplegarla de forma segura en el sistema de producción. -- Reiniciar automáticamente la aplicación si se bloque por cualquier motivo. -- Gestionar los clústeres de forma remota. -- Ver perfiles de CPU e instantáneas de almacenamiento dinámico para optimizar el rendimiento y diagnosticar fugas de memoria. -- Ver medidas de rendimiento para la aplicación. -- Escalar fácilmente a varios hosts con control integrado para el equilibrador de carga Nginx. - -Como se explica a continuación, cuando instala StrongLoop PM como un servicio de sistema operativo utilizando el sistema init, se reinicia automáticamente cuando se reinicia el sistema. De esta forma, mantiene activos siempre los clústeres y los procesos de aplicaciones. +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. #### Utilizar un sistema init -La siguiente capa de fiabilidad es garantizar que la aplicación se reinicie cuando se reinicie el servidor. Los sistemas pueden bloquearse por una amplia variedad de motivos. Para garantizar que la aplicación se reinicie si se bloquea el servidor, utilice el sistema init incorporado en su sistema operativo. Los dos principales sistemas init que se utilizan hoy día son [systemd](https://wiki.debian.org/systemd) y [Upstart](http://upstart.ubuntu.com/). +La siguiente capa de fiabilidad es garantizar que la aplicación se reinicie cuando se reinicie el servidor. Los sistemas pueden bloquearse por una amplia variedad de motivos. Para garantizar que la aplicación se reinicie si se bloquea el servidor, utilice el sistema init incorporado en su sistema operativo. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Hay dos formas de utilizar los sistemas init con la aplicación Express: -- Ejecutar la aplicación en un gestor de procesos e instalar el gestor de procesos como un servicio con el sistema init. El gestor de procesos reiniciará la aplicación cuando esta se bloquee y el sistema init reiniciará el gestor de procesos cuando se reinicie el sistema operativo. Este es el enfoque recomendado. -- Ejecutar la aplicación (y Node) directamente con el sistema init. Esta opción parece más simple, pero no tiene las ventajas adicionales de utilizar el gestor de procesos. +- Ejecutar la aplicación en un gestor de procesos e instalar el gestor de procesos como un servicio con el sistema init. El gestor de procesos reiniciará la aplicación cuando esta se bloquee y el sistema init reiniciará el gestor de procesos cuando se reinicie el sistema operativo. This is the recommended approach. +- Ejecutar la aplicación (y Node) directamente con el sistema init. Esta opción parece más simple, pero no tiene las ventajas adicionales de utilizar el gestor de procesos. ##### Systemd Systemd es un administrador de servicios y sistemas Linux. La mayoría de las principales distribuciones Linux han adoptado systemd como su sistema init predeterminado. -Un archivo de configuración de servicio de systemd se denomina un _archivo unit_, con un nombre de archivo terminado en .service. A continuación, se muestra un archivo unit de ejemplo para gestionar directamente una aplicación Node (sustituya el texto en negrita por los valores de su sistema y su aplicación): +Un archivo de configuración de servicio de systemd se denomina un _archivo unit_, con un nombre de archivo terminado en .service. A continuación, se muestra un archivo unit de ejemplo para gestionar directamente una aplicación Node (sustituya el texto en negrita por los valores de su sistema y su aplicación): Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -302,97 +250,11 @@ WantedBy=multi-user.target Para obtener más información sobre systemd, consulte [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). -##### StrongLoop PM como un servicio systemd - -Puede instalar fácilmente StrongLoop Process Manager como un servicio systemd. A continuación, cuando se reinicie el servidor, se reiniciará automáticamente StrongLoop PM, que a su vez reiniciará todas las aplicaciones que esté gestionando. - -Para instalar StrongLoop PM como un servicio systemd: - -```bash -$ sudo sl-pm-install --systemd -``` - -A continuación, inicie el servicio con: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -Para obtener más información, consulte [Setting up a production host (documentación de StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10). - -##### Upstart - -Upstart es una herramienta del sistema disponible en muchas distribuciones Linux para iniciar tareas y servicios durante el arranque del sistema, detenerlos durante la conclusión y supervisarlos. Puede configurar la aplicación Express o el gestor de procesos como un servicio y, a continuación, Upstart lo reiniciará automáticamente cuando se bloquee. - -Un servicio de Upstart se define en un archivo de configuración de trabajo (también denominado un "trabajo") con un nombre de archivo terminado en `.conf`. El siguiente ejemplo muestra cómo crear un trabajo denominado "myapp" para una aplicación denominada "myapp" con el archivo principal ubicado en `/projects/myapp/index.js`. - -Cree un archivo denominado `myapp.conf` en `/etc/init/` con el siguiente contenido (sustituya el texto en negrita por los valores de su sistema y su aplicación): - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -NOTA: este script requiere Upstart 1.4 o posterior, soportado en Ubuntu 12.04-14.10. - -Como el trabajo se configura para ejecutarse cuando se inicia el sistema, la aplicación se iniciará junto con el sistema operativo, y se reiniciará automáticamente si la aplicación se bloquea o el sistema se cuelga. - -Aparte reiniciar automáticamente la aplicación, Upstart permite utilizar estos mandatos: - -- `start myapp` – Iniciar la aplicación -- `restart myapp` – Reiniciar la aplicación -- `stop myapp` – Detener la aplicación - -Para obtener más información sobre Upstart, consulte [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook). - -##### StrongLoop PM como un servicio Upstart - -Puede instalar fácilmente StrongLoop Process Manager como un servicio Upstart. A continuación, cuando se reinicie el servidor, se reiniciará automáticamente StrongLoop PM, que a su vez reiniciará todas las aplicaciones que esté gestionando. - -Para instalar StrongLoop PM como un servicio Upstart 1.4: - -```bash -$ sudo sl-pm-install -``` - -A continuación, ejecute el servicio con: - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -NOTA: en los sistemas que no dan soporte a Upstart 1.4, los mandatos son ligeramente diferentes. Consulte [Setting up a production host (documentación de StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) para obtener más información. - ### Ejecutar la aplicación en un clúster En un sistema multinúcleo, puede multiplicar el rendimiento de una aplicación Node iniciando un clúster de procesos. Un clúster ejecuta varias instancias de la aplicación, idealmente una instancia en cada núcleo de CPU, lo que permite distribuir la carga y las tareas entre las instancias. - +![Balancing between application instances using the cluster API](/images/clustering.png) IMPORTANTE: como las instancias de aplicación se ejecutan como procesos independientes, no comparten el mismo espacio de memoria. Es decir, los objetos son locales para cada instancia de la aplicación. Por lo tanto, no puede mantener el estado en el código de aplicación. No obstante, puede utilizar un almacén de datos en memoria como [Redis](http://redis.io/) para almacenar los datos y los estados relacionados con la sesión. Esta advertencia se aplica básicamente a todas las formas de escalado horizontal, ya sean clústeres con varios procesos o varios servidores físicos. @@ -400,43 +262,52 @@ En las aplicaciones en clúster, los procesos de trabajador pueden bloquearse in #### Mediante el módulo de clúster de Node -La agrupación en clústeres es posible gracias al [módulo de clúster](https://nodejs.org/docs/latest/api/cluster.html) de Node. Esto permite al proceso maestro generar procesos de trabajador y distribuir las conexiones entrantes entre los trabajadores. No obstante, en lugar de utilizar este módulo directamente, es mucho mejor utilizar una de las muchas herramientas que lo hacen automáticamente, por ejemplo, [node-pm](https://www.npmjs.com/package/node-pm) o [cluster-service](https://www.npmjs.com/package/cluster-service). +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). Esto permite al proceso maestro generar procesos de trabajador y distribuir las conexiones entrantes entre los trabajadores. -#### Mediante StrongLoop PM +#### Using PM2 -Si despliega la aplicación en StrongLoop Process Manager (PM), puede aprovechar la agrupación en clúster _sin_ modificar el código de aplicación. +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 StrongLoop Process Manager (PM) ejecuta una aplicación, la ejecuta automáticamente en un clúster con un número de trabajadores igual al número de núcleos de CPU en el sistema. Puede cambiar manualmente el número de procesos de trabajador en el clúster utilizando la herramienta de línea de mandatos slc 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. -Por ejemplo, suponiendo que ha desplegado la aplicación en prod.foo.com y que StrongLoop PM escucha en el puerto 8701 (el valor predeterminado), para establecer el tamaño de clúster en ocho utilizando slc: +To enable cluster mode, start your application like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -Para obtener más información sobre la agrupación en clúster con StrongLoop PM, consulte [Clustering](https://docs.strongloop.com/display/SLC/Clustering) en la documentación de StrongLoop. +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 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ 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. ### Almacenar en la caché los resultados de la solicitud Otra estrategia para mejorar el rendimiento en la producción es almacenar en la caché el resultado de las solicitudes, para que la aplicación no repita la operación de dar servicio a la misma solicitud repetidamente. -Utilice un servidor de almacenamiento en memoria caché como [Varnish](https://www.varnish-cache.org/) o [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (consulte también [Nginx Caching](https://serversforhackers.com/nginx-caching/)) para mejorar significativamente la velocidad y el rendimiento de la aplicación. +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. ### Utilizar un equilibrador de carga Independientemente de lo optimizada que esté una aplicación, una única instancia sólo puede manejar una cantidad limitada de carga y tráfico. Una forma de escalar una aplicación es ejecutar varias instancias de la misma y distribuir el tráfico utilizando un equilibrador de carga. La configuración de un equilibrador de carga puede mejorar el rendimiento y la velocidad de la aplicación, lo que permite escalarla más que con una única instancia. -Un equilibrador de carga normalmente es un proxy inverso que orquesta el tráfico hacia y desde los servidores y las instancias de aplicación. Puede configurar fácilmente un equilibrador de carga para la aplicación utilizando [Nginx](http://nginx.org/en/docs/http/load_balancing.html) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +Un equilibrador de carga normalmente es un proxy inverso que orquesta el tráfico hacia y desde los servidores y las instancias de aplicación. 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 equilibrio de carga, deberá asegurarse de que las solicitudes asociadas con un determinado ID de sesión se conecten al proceso que las ha originado. Esto se conoce como _afinidad de sesiones_ o _sesiones adhesivas_, y puede solucionarse con la recomendación anterior de utilizar un almacén de datos como, por ejemplo, Redis para los datos de sesión (dependiendo de la aplicación). Para obtener más información, consulte [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). -#### Mediante StrongLoop PM con un equilibrador de carga Nginx - -[StrongLoop Process Manager](http://strong-pm.io/) se integra con un Nginx Controller, lo que simplifica las configuraciones de entornos de producción de varios hosts. Para obtener más información, consulte [Scaling to multiple servers](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers) (documentación de StrongLoop). - - ### Utilizar un proxy inverso Un proxy inverso se coloca delante de una aplicación web y realiza operaciones de soporte en las solicitudes, aparte de dirigir las solicitudes a la aplicación. Puede manejar las páginas de errores, la compresión, el almacenamiento en memoria caché, el servicio de archivos y el equilibrio de carga, entre otros. -La entrega de tareas que no necesitan saber el estado de la aplicación a un proxy inverso permite a Express realizar tareas de aplicación especializadas. Por este motivo, se recomienda ejecutar Express detrás de un proxy inverso como [Nginx](https://www.nginx.com/) o [HAProxy](http://www.haproxy.org/) en la producción. +La entrega de tareas que no necesitan saber el estado de la aplicación a un proxy inverso permite a Express realizar tareas de aplicación especializadas. 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. diff --git a/es/advanced/best-practice-security.md b/es/advanced/best-practice-security.md old mode 100755 new mode 100644 index b227e4d41f..c6fe0781da --- a/es/advanced/best-practice-security.md +++ b/es/advanced/best-practice-security.md @@ -1,37 +1,50 @@ --- layout: page title: Mejores prácticas de seguridad para Express en producción +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced -lang: es -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +lang: en +redirect_from: " " --- -# Mejores prácticas de producción: seguridad +# Production Best Practices: Security -## Visión general +## Overview -El término *"producción"* hace referencia a la etapa del ciclo de vida del software donde una aplicación o una API tiene disponibilidad general para sus consumidores o usuarios finales. Por su parte, en la etapa de *"desarrollo"*, todavía estás escribiendo y probando activamente el código, y la aplicación no está abierta para el acceso externo. Los correspondientes entornos del sistema se conocen como los entornos de *producción* y *desarrollo*, respectivamente. +El término _"producción"_ hace referencia a la etapa del ciclo de vida del software donde una aplicación o una API tiene disponibilidad general para sus consumidores o usuarios finales. Por su parte, en la etapa de _"desarrollo"_, todavía estás escribiendo y probando activamente el código, y la aplicación no está abierta para el acceso externo. Los correspondientes entornos del sistema se conocen como los entornos de _producción_ y _desarrollo_, respectivamente. Los entornos de desarrollo y producción se configuran normalmente de forma diferente y tiene requisitos también muy diferentes. Lo que funciona en el desarrollo puede que no sea aceptable en la producción. Por ejemplo, en un entorno de desarrollo, puede que desee el registro detallado de errores a efecto de depuración, mientras que el mismo comportamiento puede suponer un problema de seguridad en un entorno de producción. De la misma forma, en el desarrollo, no es necesario preocuparse por la escalabilidad, la fiabilidad y el rendimiento, mientras que estos son clave en la producción. -{% include admonitions/note.html content="Si crees haber encontrado una vulnerabilidad de seguridad en Express, por favor mira nuestras [Políticas de Seguridad y Procedimientos](/en/resources/contributing.html#security-policies-and-procedures). -" %} +{% capture security-note %} -Las mejores prácticas de seguridad para aplicaciones Express en producción incluyen: +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). -- [No utilizar versiones en desuso o vulnerables de Express](#no-utilizar-versiones-en-desuso-o-vulnerables-de-express) -- [Utilizar TLS](#utilizar-tls) -- [Utilizar Helmet](#utilizar-helmet) -- [Utilizar cookies de forma segura](#utilizar-cookies-de-forma-segura) -- [Prevenir ataques de fuerza bruta a la autenticación](#prevenir-ataques-de-fuerza-bruta-a-la-autenticación) -- [Asegurarse de que las dependencias sean seguras](#asegurarse-de-que-las-dependencias-sean-seguras) -- [Evitar otras vulnerabilidades conocidas](#evitar-otras-vulnerabilidades-conocidas) -- [Consideraciones adicionales](#consideraciones-adicionales) +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + +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) + - [Utilizar TLS](#utilizar-tls) + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [Utilizar Helmet](#utilizar-helmet) + - [Reduce fingerprinting](#reduce-fingerprinting) + - [Utilizar cookies de forma segura](#utilizar-cookies-de-forma-segura) + - [noCache](https://github.com/helmetjs/nocache) establece cabeceras `Cache-Control` y Pragma para inhabilitar el almacenamiento en memoria caché del lado de cliente. + - [ieNoOpen](https://github.com/helmetjs/ienoopen) establece `X-Download-Options` para IE8+. + - [Prevenir ataques de fuerza bruta a la autenticación](#prevenir-ataques-de-fuerza-bruta-a-la-autenticación) + - [Asegurarse de que las dependencias sean seguras](#asegurarse-de-que-las-dependencias-sean-seguras) + - [Evitar otras vulnerabilidades conocidas](#evitar-otras-vulnerabilidades-conocidas) + - [Consideraciones adicionales](#consideraciones-adicionales) ## No utilizar versiones en desuso o vulnerables de Express -Express 2.x y 3.x ya no se mantienen. Los problemas de seguridad y rendimiento en estas versiones no se solucionarán. No las utilice. Si no ha cambiado todavía a la versión 4, siga la [guía de migración](/{{ page.lang }}/guide/migrating-4.html). +Express 2.x y 3.x ya no se mantienen. Los problemas de seguridad y rendimiento en estas versiones no se solucionarán. No las utilice. Si no ha cambiado todavía a la versión 4, siga la [guía de migración](/{{ page.lang }}/guide/migrating-4.html). Asimismo, asegúrese de que no está utilizando ninguna de las versiones vulnerables de Express que se listan en la [página Actualizaciones de seguridad](/{{ page.lang }}/advanced/security-updates.html). Si las utiliza, actualícese a uno de los releases estables, preferiblemente el más reciente. @@ -39,45 +52,83 @@ Asimismo, asegúrese de que no está utilizando ninguna de las versiones vulnera Si la aplicación maneja o transmite datos confidenciales, utilice [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) para proteger la conexión y los datos. Esta tecnología cifra los datos antes de enviarlos desde el cliente al servidor, lo que evita algunos de los ataques de pirateo más comunes (y sencillos). Aunque las solicitudes Ajax y POST no sean obvias visiblemente y parezca que están "ocultas" en los navegadores, su tráfico de red es vulnerable para los [rastreos de paquetes](https://en.wikipedia.org/wiki/Packet_analyzer) y los [ataques de intermediarios](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). -Es posible que esté familiarizado con el cifrado SSL (Secure Socket Layer). [TLS es simplemente el siguiente paso después de SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). Es decir, si antes utilizaba SSL, se recomienda actualizar a TLS. En general, se recomienda Nginx para manejar TLS. Encontrará una buena referencia para configurar TLS en Nginx (y otros servidores) en [la wiki de Mozilla Recommended Server Configurations](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). +Es posible que esté familiarizado con el cifrado SSL (Secure Socket Layer). [TLS es simplemente el siguiente paso después de SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). Es decir, si antes utilizaba SSL, se recomienda actualizar a TLS. En general, se recomienda Nginx para manejar TLS. Encontrará una buena referencia para configurar TLS en Nginx (y otros servidores) en [la wiki de Mozilla Recommended Server Configurations](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). Asimismo, una herramienta muy útil para obtener un certificado de TLS gratis es [Let's Encrypt](https://letsencrypt.org/about/), una entidad emisora de certificados (CA) abierta, automatizada y gratuita proporcionada por [Internet Security Research Group (ISRG)](https://letsencrypt.org/isrg/). +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## Utilizar Helmet [Helmet](https://www.npmjs.com/package/helmet) ayuda a proteger la aplicación de algunas vulnerabilidades web conocidas mediante el establecimiento correcto de cabeceras HTTP. -Helmet es realmente una colección de nueve funciones de middleware más paquetes que establecen cabeceras HTTP relacionadas con la seguridad: +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: + +- `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 +- `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 +- `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 -* [csp](https://github.com/helmetjs/csp) establece la cabecera `Content-Security-Policy` para evitar ataques de scripts entre sitios y otras inyecciones entre sitios. -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) elimina la cabecera `X-Powered-By`. -* [hsts](https://github.com/helmetjs/hsts) establece la cabecera `Strict-Transport-Security` que fuerza conexiones seguras (HTTP sobre SSL/TLS) con el servidor. -* [ieNoOpen](https://github.com/helmetjs/ienoopen) establece `X-Download-Options` para IE8+. -* [noCache](https://github.com/helmetjs/nocache) establece cabeceras `Cache-Control` y Pragma para inhabilitar el almacenamiento en memoria caché del lado de cliente. -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) establece `X-Content-Type-Options` para evitar que los navegadores rastreen mediante MIME una respuesta del tipo de contenido declarado. -* [frameguard](https://github.com/helmetjs/frameguard) establece la cabecera `X-Frame-Options` para proporcionar protección contra el [clickjacking](https://www.owasp.org/index.php/Clickjacking). -* [xssFilter](https://github.com/helmetjs/x-xss-protection) establece `X-XSS-Protection` para habilitar el filtro de scripts entre sitios (XSS) en los navegadores web más recientes. +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Instale Helmet como cualquier otro módulo: ```bash -$ npm install --save helmet +$ npm install helmet ``` A continuación, utilícelo en el código: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### Como mínimo, inhabilitar la cabecera X-Powered-By +## Reduce fingerprinting -Si no desea utilizar Helmet, como mínimo, inhabilite la cabecera `X-Powered-By`. Los atacantes pueden utilizar esta cabecera (que está habilitada de forma predeterminada) para detectar las aplicaciones que ejecutan Express e iniciar ataques con destinos específicos. +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. Por lo tanto, se recomienda desactivar la cabecera con el método `app.disable()`: @@ -85,24 +136,54 @@ Por lo tanto, se recomienda desactivar la cabecera con el método `app.disable() app.disable('x-powered-by') ``` -Si utiliza `helmet.js`, lo hace automáticamente. +{% capture powered-advisory %} -## Utilizar cookies de forma segura +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` + +## Establecer las opciones de seguridad de las cookies Para garantizar que las cookies no abran la aplicación para ataques, no utilice el nombre de cookie de sesión predeterminado y establezca las opciones de seguridad de las cookies correctamente. Hay dos módulos de sesión de cookies de middleware principales: -* [express-session](https://www.npmjs.com/package/express-session), que sustituye el middleware `express.session` incorporado en Express 3.x. -* [cookie-session](https://www.npmjs.com/package/cookie-session), que sustituye el middleware `express.cookieSession` incorporado en Express 3.x. +- [express-session](https://www.npmjs.com/package/express-session), que sustituye el middleware `express.session` incorporado en Express 3.x. +- [cookie-session](https://www.npmjs.com/package/cookie-session), que sustituye el middleware `express.cookieSession` incorporado en Express 3.x. -La principal diferencia entre los dos módulos es cómo guardan los datos de sesión de las cookies. El middleware [express-session](https://www.npmjs.com/package/express-session) almacena los datos de sesión en el servidor; sólo guarda el ID de sesión en la propia cookie, no los datos de sesión. De forma predeterminada, utiliza el almacenamiento en memoria y no está diseñado para un entorno de producción. En la producción, deberá configurar un almacenamiento de sesión escalable; consulte la lista de [almacenes de sesión compatibles](https://github.com/expressjs/session#compatible-session-stores). +La principal diferencia entre los dos módulos es cómo guardan los datos de sesión de las cookies. El middleware [express-session](https://www.npmjs.com/package/express-session) almacena los datos de sesión en el servidor; sólo guarda el ID de sesión en la propia cookie, no los datos de sesión. De forma predeterminada, utiliza el almacenamiento en memoria y no está diseñado para un entorno de producción. En la producción, deberá configurar un almacenamiento de sesión escalable; consulte la lista de [almacenes de sesión compatibles](https://github.com/expressjs/session#compatible-session-stores). -Por su parte, el middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implementa un almacenamiento basado en cookies: serializa la sesión completa en la cookie, en lugar de sólo una clave de sesión. Utilícelo sólo cuando los datos de sesión sean relativamente pequeños y fácilmente codificables como valores primitivos (en lugar de objetos). Aunque se supone que los navegadores pueden dar soporte a 4096 bytes por cookie como mínimo, para no exceder el límite, no supere un tamaño de 4093 bytes por dominio. Asimismo, asegúrese de que los datos de la cookie estén visibles para el cliente, para que si se deben proteger u ocultar por cualquier motivo, se utilice mejor la opción express-session. +Por su parte, el middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implementa un almacenamiento basado en cookies: serializa la sesión completa en la cookie, en lugar de sólo una clave de sesión. Utilícelo sólo cuando los datos de sesión sean relativamente pequeños y fácilmente codificables como valores primitivos (en lugar de objetos). Aunque se supone que los navegadores pueden dar soporte a 4096 bytes por cookie como mínimo, para no exceder el límite, no supere un tamaño de 4093 bytes por dominio. Asimismo, asegúrese de que los datos de la cookie estén visibles para el cliente, para que si se deben proteger u ocultar por cualquier motivo, se utilice mejor la opción express-session. ### No utilizar el nombre de cookie de sesión predeterminado -Si utiliza el nombre de cookie de sesión predeterminado, la aplicación puede quedar abierta a los ataques. El problema de seguridad que supone es similar a `X-Powered-By`: un posible atacante puede utilizarlo para firmar digitalmente el servidor y dirigir los ataques en consecuencia. +Si utiliza el nombre de cookie de sesión predeterminado, la aplicación puede quedar abierta a los ataques. El problema de seguridad que supone es similar a `X-Powered-By`: un posible atacante puede utilizarlo para firmar digitalmente el servidor y dirigir los ataques en consecuencia. Para evitar este problema, utilice nombres de cookie genéricos, por ejemplo, con el middleware [express-session](https://www.npmjs.com/package/express-session): @@ -112,19 +193,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` -### Establecer las opciones de seguridad de las cookies +### Utilizar cookies de forma segura Establezca las siguientes opciones de cookies para mejorar la seguridad: -* `secure` - Garantiza que el navegador sólo envíe la cookie a través de HTTPS. -* `httpOnly` - Garantiza que la cookie sólo se envíe a través de HTTP(S), no a través de JavaScript de cliente, para la protección contra ataques de scripts entre sitios. -* `domain` - Indica el dominio de la cookie; utilícelo para compararlo con el dominio del servidor donde se está solicitando el URL. Si coinciden, compruebe el atributo de vía de acceso a continuación. -* `path` - Indica la vía de acceso de la cookie; utilícela para compararla con la vía de acceso de la solicitud. Si esta y el dominio coinciden, envíe la cookie en la solicitud. -* `expires` - Se utiliza para establecer la fecha de caducidad de las cookies persistentes. +- `secure` - Garantiza que el navegador sólo envíe la cookie a través de HTTPS. +- `httpOnly` - Garantiza que la cookie sólo se envíe a través de HTTP(S), no a través de JavaScript de cliente, para la protección contra ataques de scripts entre sitios. +- `domain` - Indica el dominio de la cookie; utilícelo para compararlo con el dominio del servidor donde se está solicitando el URL. Si coinciden, compruebe el atributo de vía de acceso a continuación. +- `path` - Indica la vía de acceso de la cookie; utilícela para compararla con la vía de acceso de la solicitud. Si esta y el dominio coinciden, envíe la cookie en la solicitud. +- `expires` - Se utiliza para establecer la fecha de caducidad de las cookies persistentes. A continuación, se muestra un ejemplo de uso del middleware [cookie-session](https://www.npmjs.com/package/cookie-session): @@ -144,8 +224,7 @@ app.use(session({ path: 'foo/bar', expires: expiryDate } -}) -) +})) ``` ## Prevenir ataques de fuerza bruta a la autenticación @@ -161,9 +240,9 @@ El paquete [rate-limiter-flexible](https://github.com/animir/node-rate-limiter-f ## Asegurarse de que las dependencias sean seguras -El uso de npm para gestionar las dependencias de la aplicación es muy útil y cómodo. No obstante, los paquetes que utiliza pueden contener vulnerabilidades de seguridad críticas que también pueden afectar a la aplicación. La seguridad de la aplicación sólo es tan fuerte como el "enlace más débil" de las dependencias. +El uso de npm para gestionar las dependencias de la aplicación es muy útil y cómodo. No obstante, los paquetes que utiliza pueden contener vulnerabilidades de seguridad críticas que también pueden afectar a la aplicación. La seguridad de la aplicación sólo es tan fuerte como el "enlace más débil" de las dependencias. -Desde npm@6, npm revisa automáticamente cada solicitud de instalación. También puedes utilizar 'npm audit' para analizar tu árbol de dependencias. +Since npm@6, npm automatically reviews every install request. También puedes utilizar 'npm audit' para analizar tu árbol de dependencias. ```bash $ npm audit @@ -184,19 +263,20 @@ Usa este comando para comprobar tu aplicación contra vulnerabilidades: $ snyk test ``` -## Evitar otras vulnerabilidades conocidas +### Avoid other known vulnerabilities -Esté atento a las advertencias de [Node Security Project](https://npmjs.com/advisories) que puedan afectar a Express u otros módulos que utilice la aplicación. En general, Node Security Project es un excelente recurso de herramientas e información sobre la seguridad de Node. +Esté atento a las advertencias de [Node Security Project](https://npmjs.com/advisories) que puedan afectar a Express u otros módulos que utilice la aplicación. En general, Node Security Project es un excelente recurso de herramientas e información sobre la seguridad de Node. Por último, las aplicaciones de Express, como cualquier otra aplicación web, son vulnerables a una amplia variedad de ataques basados en web. Familiarícese con las [vulnerabilidades web](https://www.owasp.org/www-project-top-ten/) conocidas y tome precauciones para evitarlas. -## Consideraciones adicionales +## Additional considerations + +A continuación, se muestran algunas recomendaciones para la excelente lista de comprobación [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Consulte el post de este blog para ver todos los detalles de estas recomendaciones: -A continuación, se muestran algunas recomendaciones para la excelente lista de comprobación [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Consulte el post de este blog para ver todos los detalles de estas recomendaciones: +- Filtre y sanee siempre la entrada de usuario para protegerse contra los ataques de scripts entre sitios (XSS) e inyección de mandatos. +- Defiéndase contra los ataques de inyección de SQL utilizando consultas parametrizadas o sentencias preparadas. +- Utilice la herramienta [sqlmap](http://sqlmap.org/) de código abierto para detectar vulnerabilidades de inyección de SQL en la aplicación. +- Utilice las herramientas [nmap](https://nmap.org/) y [sslyze](https://github.com/nabla-c0d3/sslyze) para probar la configuración de los cifrados SSL, las claves y la renegociación, así como la validez del certificado. +- Utilice [safe-regex](https://www.npmjs.com/package/safe-regex) para asegurarse de que las expresiones regulares no sean susceptibles de ataques de [denegación de servicio de expresiones regulares](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). -* Implemente el límite de velocidad para evitar ataques de fuerza bruta contra la autenticación. Una forma de hacerlo es utilizar [StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) para forzar una política de limitación de velocidad. También puede utilizar middleware como [express-limiter](https://www.npmjs.com/package/express-limiter), aunque para ello deberá modificar el código de alguna forma. -* Filtre y sanee siempre la entrada de usuario para protegerse contra los ataques de scripts entre sitios (XSS) e inyección de mandatos. -* Defiéndase contra los ataques de inyección de SQL utilizando consultas parametrizadas o sentencias preparadas. -* Utilice la herramienta [sqlmap](http://sqlmap.org/) de código abierto para detectar vulnerabilidades de inyección de SQL en la aplicación. -* Utilice las herramientas [nmap](https://nmap.org/) y [sslyze](https://github.com/nabla-c0d3/sslyze) para probar la configuración de los cifrados SSL, las claves y la renegociación, así como la validez del certificado. -* Utilice [safe-regex](https://www.npmjs.com/package/safe-regex) para asegurarse de que las expresiones regulares no sean susceptibles de ataques de [denegación de servicio de expresiones regulares](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). +[helmet]: \ No newline at end of file diff --git a/es/advanced/developing-template-engines.md b/es/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 47d893d54e..ebe7b364cc --- a/es/advanced/developing-template-engines.md +++ b/es/advanced/developing-template-engines.md @@ -1,10 +1,10 @@ --- layout: page title: Desarrollo de motores de plantilla para 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. menu: advanced -lang: es -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. +lang: en +redirect_from: " " --- # Desarrollo de motores de plantilla para Express @@ -17,9 +17,10 @@ El siguiente código es un ejemplo de implementación de un motor de plantilla m const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) @@ -34,6 +35,7 @@ La aplicación ahora podrá representar archivos `.ntl`. Cree un archivo denomin #title# #message# ``` + A continuación, cree la ruta siguiente en la aplicación. ```js @@ -41,4 +43,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -Cuando realice una solicitud a la página de inicio, `index.ntl` se representará como HTML. + +Cuando realice una solicitud a la página de inicio, `index.ntl` se representará como HTML. \ No newline at end of file diff --git a/es/advanced/healthcheck-graceful-shutdown.md b/es/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..3e233fb436 --- /dev/null +++ b/es/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: en +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/es/advanced/security-updates.md b/es/advanced/security-updates.md old mode 100755 new mode 100644 index bcabee2cc6..bc60b5a245 --- a/es/advanced/security-updates.md +++ b/es/advanced/security-updates.md @@ -1,47 +1,88 @@ --- layout: page title: Actualizaciones de seguridad de Express +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced -lang: es -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +lang: en +redirect_from: " " --- # Actualizaciones de seguridad
-Las vulnerabilidades de Node.js afectan directamente a Express. Por lo tanto, [vigile las vulnerabilidades de Node.js](https://nodejs.org +Node.js vulnerabilities directly affect Express. Por lo tanto, [vigile las vulnerabilidades de Node.js](https://nodejs.org /en/blog/vulnerability/) y asegúrese de utilizar la versión estable más reciente de Node.js.
En la lista siguiente se muestran las vulnerabilidades de Express que se han solucionado en la actualización de versión especificada. +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * Se ha solucionado la vulnerabilidad de divulgación de vía de acceso raíz en `express.static`, `res.sendfile` y `res.sendFile` - * 4.10.7 - * Se ha solucionado la vulnerabilidad de Open Redirect en `express.static` ([anuncio](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 4.8.8 - * Se han solucionado las vulnerabilidades de cruce de directorios en `express.static` ([anuncio](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 puede tener fugas de `fd` en determinadas situaciones que afectan a `express.static` y `res.sendfile`. Las solicitudes maliciosas pueden provocar la fuga de `fd` y, en última instancia, generar errores `EMFILE` y anular la capacidad de respuesta del servidor. - * 4.8.0 - * Las matrices dispersas que tienen índices extremadamente altos en la serie de consulta pueden hacer que el proceso se quede sin memoria y se bloquee el servidor. - * Los objetos de serie de consulta extremadamente anidados pueden hacer que se bloquee el proceso y anular la capacidad de respuesta del servidor temporalmente. +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - Se ha solucionado la vulnerabilidad de divulgación de vía de acceso raíz en `express.static`, `res.sendfile` y `res.sendFile` +- 4.10.7 + - Se ha solucionado la vulnerabilidad de Open Redirect en `express.static` ([anuncio](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 4.8.8 + - Se han solucionado las vulnerabilidades de cruce de directorios en `express.static` ([anuncio](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 puede tener fugas de `fd` en determinadas situaciones que afectan a `express.static` y `res.sendfile`. Las solicitudes maliciosas pueden provocar la fuga de `fd` y, en última instancia, generar errores `EMFILE` y anular la capacidad de respuesta del servidor. +- 4.8.0 + - Las matrices dispersas que tienen índices extremadamente altos en la serie de consulta pueden hacer que el proceso se quede sin memoria y se bloquee el servidor. + - Los objetos de serie de consulta extremadamente anidados pueden hacer que se bloquee el proceso y anular la capacidad de respuesta del servidor temporalmente. ## 3.x - * 3.19.1 - * Se ha solucionado la vulnerabilidad de divulgación de vía de acceso raíz en `express.static`, `res.sendfile` y `res.sendFile` - * 3.19.0 - * Se ha solucionado la vulnerabilidad de Open Redirect en `express.static` ([anuncio](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 3.16.10 - * Se han solucionado las vulnerabilidades de cruce de directorios en `express.static`. - * 3.16.6 - * Node.js 0.10 puede tener fugas de `fd` en determinadas situaciones que afectan a `express.static` y `res.sendfile`. Las solicitudes maliciosas pueden provocar la fuga de `fd` y, en última instancia, generar errores `EMFILE` y anular la capacidad de respuesta del servidor. - * 3.16.0 - * Las matrices dispersas que tienen índices extremadamente altos en la serie de consulta pueden hacer que el proceso se quede sin memoria y se bloquee el servidor. - * Los objetos de serie de consulta extremadamente anidados pueden hacer que se bloquee el proceso y anular la capacidad de respuesta del servidor temporalmente. - * 3.3.0 - * La respuesta 404 de un intento de alteración temporal de método no soportado era susceptible de ataques de scripts entre sitios. +
+ **Express 3.x YA NO SE MANTIENE** + +Los problemas de rendimiento y seguridad conocidos y desconocidos en 3.x no se han solucionado desde la última actualización (1 de agosto de 2015). Se recomienda especialmente utilizar la última versión de Express. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
+ +- 3.19.1 + - Se ha solucionado la vulnerabilidad de divulgación de vía de acceso raíz en `express.static`, `res.sendfile` y `res.sendFile` +- 3.19.0 + - Se ha solucionado la vulnerabilidad de Open Redirect en `express.static` ([anuncio](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 3.16.10 + - Se han solucionado las vulnerabilidades de cruce de directorios en `express.static`. +- 3.16.6 + - Node.js 0.10 puede tener fugas de `fd` en determinadas situaciones que afectan a `express.static` y `res.sendfile`. Las solicitudes maliciosas pueden provocar la fuga de `fd` y, en última instancia, generar errores `EMFILE` y anular la capacidad de respuesta del servidor. +- 3.16.0 + - Las matrices dispersas que tienen índices extremadamente altos en la serie de consulta pueden hacer que el proceso se quede sin memoria y se bloquee el servidor. + - Los objetos de serie de consulta extremadamente anidados pueden hacer que se bloquee el proceso y anular la capacidad de respuesta del servidor temporalmente. +- 3.3.0 + - La respuesta 404 de un intento de alteración temporal de método no soportado era susceptible de ataques de scripts entre sitios. \ No newline at end of file diff --git a/es/api.md b/es/api.md old mode 100755 new mode 100644 index 639a07c26f..a34e0dcbc9 --- a/es/api.md +++ b/es/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - Referencia de API -lang: es -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +version: 5x +title: Express 5.x - Referencia de API +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. +lang: en +redirect_from: " " --- -
- -

API de 4.x

- - - {% include api/en/4x/express.md %} +
+

5.x API

+ {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
diff --git a/es/changelog/index.md b/es/changelog/index.md new file mode 100644 index 0000000000..d64a7855b7 --- /dev/null +++ b/es/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: en +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
+ +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
    +
  • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
    +
  • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
    +
  • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
    +
  • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
  • + +
  • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
  • + +
  • + Starting with this version, Express supports Node.js 18.x. +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
  • + +
  • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
  • + +
  • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
  • + +
  • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
  • + +
  • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
    +
  • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
    +
  • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
  • + +
  • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
  • + +
  • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
  • + +
  • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
  • + +
  • + Starting with this version, Express supports Node.js 14.x. +
  • + +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
    +
  • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
    +
  • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
  • + +
  • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
  • + +
  • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
  • + +
  • + Starting with this version, Express supports Node.js 10.x and 12.x. +
  • + +
  • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
  • + +
  • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
    +
  • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
    +
  • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
  • + +
  • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
  • + +
  • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
    +
  • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
    +
  • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
    +
  • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
  • + +
  • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
  • + +
  • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
  • + +
  • + Starting with this version, Express supports Node.js 8.x. +
  • + +
  • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
  • + +
  • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
  • + +
  • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
  • + +
  • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
  • + +
  • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
    +
  • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
  • + +
  • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
  • + +
  • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
    +
  • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
    +
  • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
  • + +
  • + Fix error when `res.set` cannot add charset to `Content-Type`. +
  • + +
  • + Fix missing `` in HTML document. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
    +
  • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
    +
  • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
    +
  • + Starting with this version, Express supports Node.js 7.x. +
  • + +
  • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
  • + +
  • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
  • + +
  • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
    +
  • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
    +
  • + Starting with this version, Express supports Node.js 6.x. +
  • + +
  • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
  • + +
  • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
  • + +
  • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
  • + +
  • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
  • + +
  • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
  • + +
  • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
  • + +
  • + IP address resolution with proxies has been greatly improved. +
  • + +
  • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
  • +
+ +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
diff --git a/es/guide/behind-proxies.md b/es/guide/behind-proxies.md old mode 100755 new mode 100644 index b76847f03c..7e20f8ae65 --- a/es/guide/behind-proxies.md +++ b/es/guide/behind-proxies.md @@ -1,22 +1,24 @@ --- layout: page title: Express detrás de 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. menu: guide -lang: es -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. +lang: en +redirect_from: " " --- # Express detrás de proxies -Cuando ejecute una aplicación Express detrás de un proxy, establezca (utilizando [app.set()](/{{ page.lang }}/4x/api.html#app.set)) la variable de aplicación `trust proxy` en uno de los valores de la siguiente tabla. +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.
-Aunque la aplicación no dejará de ejecutarse si no se establece la variable de aplicación `trust proxy`, registrará incorrectamente la dirección IP del proxy como la dirección IP del cliente, a menos que se configure `trust proxy`. +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.
+The application setting `trust proxy` may be set to one of the values listed in the following table. + - + @@ -24,16 +26,20 @@ Aunque la aplicación no dejará de ejecutarse si no se establece la variable de Si es `true`, la dirección IP del cliente se entiende como la entrada más a la izquierda en la cabecera `X-Forwarded-*`. Si es `false`, la aplicación se entiende como orientada directamente a Internet, y la dirección IP del cliente se obtiene de `req.connection.remoteAddress`. Este es el valor predeterminado. + +
+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. +
- + - + - +
TipoValor
TypeValue
Booleano
Direcciones IPIP addresses -Una dirección IP, una subred o una matriz de direcciones IP y subredes de confianza. La siguiente lista muestra los nombres de subred preconfigurados: +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: -* 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` +- 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` Puede establecer direcciones IP de varias formas: @@ -44,20 +50,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -Cuando se especifican, las direcciones IP o las subredes se excluyen del proceso de determinación de direcciones, y la dirección IP no de confianza más próxima al servidor de aplicaciones se establece como la dirección IP del cliente. +Cuando se especifican, las direcciones IP o las subredes se excluyen del proceso de determinación de direcciones, y la dirección IP no de confianza más próxima al servidor de aplicaciones se establece como la dirección IP del cliente. 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. +
NúmeroNumber -Confíe en la porción `n` entre el origen y el destino del servidor proxy accesible externamente como el cliente. +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. + +
+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. +
FunciónFunction -Implementación de confianza personalizada. Utilícela sólo si sabe lo que está haciendo. - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -65,12 +75,13 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
-Si establece un valor de `trust proxy` distinto de `false`, se producen tres cambios importantes: +Enabling `trust proxy` will have the following impact:
  • El valor de [req.hostname](/{{ page.lang }}/api.html#req.hostname) se obtiene del valor definido en la cabecera `X-Forwarded-Host`, que puede estar establecido por el cliente o el proxy. @@ -81,4 +92,4 @@ Si establece un valor de `trust proxy` distinto de `false`, se producen tres cam
-El valor `trust proxy` se implementa utilizando el paquete [proxy-addr](https://www.npmjs.com/package/proxy-addr). Para obtener más información, consulte su documentación. +El valor `trust proxy` se implementa utilizando el paquete [proxy-addr](https://www.npmjs.com/package/proxy-addr). For more information, see its documentation. diff --git a/es/guide/database-integration.md b/es/guide/database-integration.md old mode 100755 new mode 100644 index e819fba7c2..f8bc437f65 --- a/es/guide/database-integration.md +++ b/es/guide/database-integration.md @@ -1,221 +1,281 @@ --- layout: page title: Integración de la base de datos de Express +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide -lang: es -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +lang: en +redirect_from: " " --- # Integración de la base de datos La adición de la funcionalidad de conectar bases de datos a las aplicaciones Express se consigue simplemente cargando el controlador de Node.js adecuado para la base de datos en la aplicación. En este documento se describe brevemente cómo añadir y utilizar algunos de los módulos de Node.js más conocidos para los sistemas de base de datos en la aplicación Express: -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
-Estos son algunos de los muchos controladores de base de datos que hay disponibles. Para ver otras opciones, realice búsquedas en el sitio [npm](https://www.npmjs.com/). +Estos son algunos de los muchos controladores de base de datos que hay disponibles. Para ver otras opciones, realice búsquedas en el sitio [npm](https://www.npmjs.com/).
- - ## Cassandra **Módulo**: [cassandra-driver](https://github.com/datastax/nodejs-driver) **Instalación** +### + ```bash $ npm install cassandra-driver ``` -**Ejemplo** +### -
-
-var cassandra = require('cassandra-driver');
-var client = new cassandra.Client({ contactPoints: ['localhost']});
+```js
+const cassandra = require('cassandra-driver')
+const client = new cassandra.Client({ contactPoints: ['localhost'] })
 
-client.execute('select key from system.local', function(err, result) {
-  if (err) throw err;
-  console.log(result.rows[0]);
-});
-
-
+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) + +### + +```bash +$ npm install couchbase +``` + +### + +```js +const couchbase = require('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) **Instalación** +### + ```bash $ npm install nano ``` -**Ejemplo** +### -
-
-var nano = require('nano')('http://localhost:5984');
-nano.db.create('books');
-var books = nano.db.use('books');
-
-//Insert a book document in the books database
-books.insert({name: 'The Art of war'}, null, function(err, body) {
-  if (!err){
-    console.log(body);
-  }
-});
+```js
+const nano = require('nano')('http://localhost:5984')
+nano.db.create('books')
+const books = nano.db.use('books')
 
-//Get a list of all books
-books.list(function(err, body){
-  console.log(body.rows);
-});
-
-
+// Insert a book document in the books database +books.insert({ name: 'The Art of war' }, null, (err, body) => { + if (err) { + console.log(err) + } else { + console.log(body) + } +}) - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **Módulo**: [levelup](https://github.com/rvagg/node-levelup) **Instalación** +### + ```bash $ npm install level levelup leveldown ``` -**Ejemplo** - -
-
-var levelup = require('levelup');
-var db = levelup('./mydb');
+### 
 
-db.put('name', 'LevelUP', function (err) {
+```js
+const levelup = require('levelup')
+const db = levelup('./mydb')
 
-  if (err) return console.log('Ooops!', err);
-  db.get('name', function (err, value) {
-    if (err) return console.log('Ooops!', err);
-    console.log('name=' + value);
-  });
+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/) **Instalación** +### + ```bash $ npm install mysql ``` -**Ejemplo** +### -
-
-var mysql      = require('mysql');
-var connection = mysql.createConnection({
-  host     : 'localhost',
-  user     : 'dbuser',
-  password : 's3kreee7'
-});
+```js
+const mysql = require('mysql')
+const connection = mysql.createConnection({
+  host: 'localhost',
+  user: 'dbuser',
+  password: 's3kreee7',
+  database: 'my_db'
+})
 
-connection.connect();
+connection.connect()
 
-connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
-  if (err) throw err;
-  console.log('The solution is: ', rows[0].solution);
-});
+connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
+  if (err) throw err
 
-connection.end();
-
-
+ console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **Módulo**: [mongodb](https://github.com/mongodb/node-mongodb-native) **Instalación** +### + ```bash $ npm install mongodb ``` -**Ejemplo** +### Example (v2.\*) -
-
-var MongoClient = require('mongodb').MongoClient;
+```js
+const MongoClient = require('mongodb').MongoClient
 
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
-  if (err) {
-    throw err;
-  }
-  db.collection('mammals').find().toArray(function(err, result) {
-    if (err) {
-      throw err;
-    }
-    console.log(result);
-  });
-});
-
-
+MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err -Si desea un controlador de modelo de objeto para MongoDB, consulte [Mongoose](https://github.com/LearnBoost/mongoose). + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +### + +```js +const MongoClient = require('mongodb').MongoClient - +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err + + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +Si desea un controlador de modelo de objeto para MongoDB, consulte [Mongoose](https://github.com/LearnBoost/mongoose). ## Neo4j -**Módulo**: [apoc](https://github.com/hacksparrow/apoc) -**Instalación** + +var apoc = require('apoc');apoc.query('match (n) return n').exec().then( +function (response) { +console.log(response); +}, +function (fail) { +console.log(fail); +} +); + +### ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**Ejemplo** +### -
-
-var apoc = require('apoc');
-
-apoc.query('match (n) return n').exec().then(
-  function (response) {
-    console.log(response);
-  },
-  function (fail) {
-    console.log(fail);
-  }
-);
-
-
+```js +const neo4j = require('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 -**Módulo**: [oracledb](https://github.com/oracle/node-oracledb) +**Module**: [oracledb](https://github.com/oracle/node-oracledb) -### Instalación +### NOTA: [Vea los requisitos previos de instalación](https://github.com/oracle/node-oracledb#-installation). @@ -223,7 +283,7 @@ NOTA: [Vea los requisitos previos de instalación](https://github.com/oracle/nod $ npm install oracledb ``` -### Ejemplo +### ```js const oracledb = require('oracledb') @@ -257,130 +317,182 @@ async function getEmployee (empId) { getEmployee(101) ``` - - - ## PostgreSQL **Módulo**: [pg-promise](https://github.com/vitaly-t/pg-promise) **Instalación** +### + ```bash $ npm install pg-promise ``` -**Ejemplo** - -
-
-var pgp = require("pg-promise")(/*options*/);
-var db = pgp("postgres://username:password@host:port/database");
+### 
 
-db.one("SELECT $1 AS value", 123)
-    .then(function (data) {
-        console.log("DATA:", data.value);
-    })
-    .catch(function (error) {
-        console.log("ERROR:", error);
-    });
-
-
- - +```js +const pgp = require('pg-promise')(/* options */) +const db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **Módulo**: [redis](https://github.com/mranney/node_redis) **Instalación** +### + ```bash $ npm install redis ``` -**Ejemplo** +### -
-
-var client = require('redis').createClient();
+```js
+const redis = require('redis')
+const client = redis.createClient()
 
-client.on('error', function (err) {
-  console.log('Error ' + err);
-});
+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.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', function (err, replies) {
+client.hkeys('hash key', (err, replies) => {
+  console.log(`${replies.length} replies:`)
 
-  console.log(replies.length + ' replies:');
-  replies.forEach(function (reply, i) {
-    console.log('    ' + i + ': ' + reply);
-  });
+  replies.forEach((reply, i) => {
+    console.log(`    ${i}: ${reply}`)
+  })
 
-  client.quit();
+  client.quit()
+})
+```
+
+## SQL Server
 
-});
-
-
+**Module**: [tedious](https://github.com/tediousjs/tedious) - +### + +```bash +$ npm install tedious +``` + +### + +```js +const Connection = require('tedious').Connection +const Request = require('tedious').Request + +const config = { + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } +} + +const connection = new Connection(config) + +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **Módulo**: [sqlite3](https://github.com/mapbox/node-sqlite3) **Instalación** +### + ```bash $ npm install sqlite3 ``` -**Ejemplo** - -
-
-var sqlite3 = require('sqlite3').verbose();
-var db = new sqlite3.Database(':memory:');
+### 
 
-db.serialize(function() {
+```js
+const sqlite3 = require('sqlite3').verbose()
+const db = new sqlite3.Database(':memory:')
 
-  db.run('CREATE TABLE lorem (info TEXT)');
-  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
+db.serialize(() => {
+  db.run('CREATE TABLE lorem (info TEXT)')
+  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
 
-  for (var i = 0; i < 10; i++) {
-    stmt.run('Ipsum ' + i);
+  for (let i = 0; i < 10; i++) {
+    stmt.run(`Ipsum ${i}`)
   }
 
-  stmt.finalize();
-
-  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
-    console.log(row.id + ': ' + row.info);
-  });
-});
+  stmt.finalize()
 
-db.close();
-
-
+ db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) + }) +}) - +db.close() +``` ## ElasticSearch **Módulo**: [elasticsearch](https://github.com/elastic/elasticsearch-js) **Instalación** +### + ```bash $ npm install elasticsearch ``` -**Ejemplo** +### -
-
-var elasticsearch = require('elasticsearch');
-var client = elasticsearch.Client({
+```js
+const elasticsearch = require('elasticsearch')
+const client = elasticsearch.Client({
   host: 'localhost:9200'
-});
+})
 
 client.search({
   index: 'books',
@@ -393,10 +505,9 @@ client.search({
       }
     }
   }
-}).then(function(response) {
-  var hits = response.hits.hits;
-}, function(error) {
-  console.trace(error.message);
-});
-
-
+}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/es/guide/debugging.md b/es/guide/debugging.md old mode 100755 new mode 100644 index 4b4d627258..4194bf6cd1 --- a/es/guide/debugging.md +++ b/es/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Depuración de Express +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide -lang: es -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +lang: en +redirect_from: " " --- # Depuración de Express @@ -18,7 +18,7 @@ $ DEBUG=express:* node index.js En Windows, utilice el mandato correspondiente. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` La ejecución de este mandato en la aplicación predeterminada generada por el [generador de Express](/{{ page.lang }}/starter/generator.html) imprime la siguiente salida: @@ -59,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -89,7 +89,7 @@ Cuando se realiza una solicitud a la aplicación, verá los registros especifica Para ver sólo los registros de la implementación de direccionador, establezca el valor de `DEBUG` en `express:router`. De la misma forma, para ver sólo los registros de la implementación de aplicación, establezca el valor de `DEBUG` en `express:application`, etc. -## Aplicaciones generadas por `express` +## Applications generated by `express` Una aplicación generada por el mandato `express` utiliza el módulo `debug`, y el ámbito de su espacio de nombres de depuración se establece en el nombre de la aplicación. @@ -104,3 +104,27 @@ Puede especificar más de un espacio de nombres de depuración asignando una lis ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/es/guide/error-handling.md b/es/guide/error-handling.md old mode 100755 new mode 100644 index 034c9e7476..6b8abb8123 --- a/es/guide/error-handling.md +++ b/es/guide/error-handling.md @@ -1,15 +1,189 @@ --- layout: page title: Manejo de errores de Express +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide -lang: es -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +lang: en +redirect_from: " " --- -# Manejo de errores +# Error Handling -Defina las funciones de middleware de manejo de errores de la misma forma que otras funciones de middleware, excepto que las funciones de manejo de errores tienen cuatro argumentos en lugar de tres: `(err, req, res, next)`. Por ejemplo: +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + +Defina las funciones de middleware de manejo de errores de la misma forma que otras funciones de middleware, excepto que las funciones de manejo de errores tienen cuatro argumentos en lugar de tres: `(err, req, res, next)`. For example: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +Si tiene un manejador de rutas con varias funciones de devolución de llamada, puede utilizar el parámetro `route` para omitir el siguiente manejador de rutas. +For example: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +Si pasa cualquier valor a la función `next()` (excepto la serie `'route'`), Express considera que la solicitud actual tiene un error y omitirá las restantes funciones de middleware y direccionamiento que no son de manejo de errores. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. For example: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. For example: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +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('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## El manejador de errores predeterminado + +Express se suministra con un manejador de errores incorporado, que se encarga de los errores que aparecen en la aplicación. Esta función de middleware de manejo de errores predeterminada se añade al final de la pila de funciones de middleware. + +Si pasa un error a `next()` y no lo maneja en el manejador de errores, lo manejará el manejador de errores incorporado; el error se escribirá en el cliente con el seguimiento de la pila. El seguimiento de la pila no se incluye en el entorno de producción. + +
+Establezca la variable de entorno `NODE_ENV` en `production`, para ejecutar la aplicación en modalidad de producción. +
+ +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. + +Si invoca `next()` con un error después de haber empezado a escribir la respuesta (por ejemplo, si encuentra un error mientras se envía la respuesta en modalidad continua al cliente), el manejador de errores predeterminado de Express cierra la conexión y falla la solicitud. + +Por lo tanto, cuando añade un manejador de errores personalizado, se recomienda delegar en los mecanismos de manejo de errores predeterminados de Express, cuando las cabeceras ya se han enviado al cliente: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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: ```js app.use((err, req, res, next) => { @@ -24,7 +198,10 @@ El middleware de manejo de errores se define al final, después de otras llamada const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -39,7 +216,10 @@ A efectos de la organización (y de infraestructura de nivel superior), puede de const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -57,6 +237,8 @@ function logErrors (err, req, res, next) { También en este ejemplo, `clientErrorHandler` se define de la siguiente manera; en este caso, el error se pasa de forma explícita al siguiente: +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) { if (req.xhr) { @@ -66,6 +248,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + La función que detecta todos los errores de `errorHandler` puede implementarse de la siguiente manera: ```js @@ -75,17 +258,16 @@ function errorHandler (err, req, res, next) { } ``` -Si pasa cualquier valor a la función `next()` (excepto la serie `'route'`), Express considera que la solicitud actual tiene un error y omitirá las restantes funciones de middleware y direccionamiento que no son de manejo de errores. Si desea manejar ese error de alguna manera, deberá crear una ruta de manejo de errores como se describe en la siguiente sección. - -Si tiene un manejador de rutas con varias funciones de devolución de llamada, puede utilizar el parámetro `route` para omitir el siguiente manejador de rutas. Por ejemplo: +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: ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -94,32 +276,9 @@ app.get('/a_route_behind_paywall', }) }) ``` + En este ejemplo, se omitirá el manejador `getPaidContent`, pero los restantes manejadores en `app` para `/a_route_behind_paywall` continuarán ejecutándose.
Las llamadas a `next()` y `next(err)` indican que el manejador actual está completo y en qué estado. `next(err)` omitirá los demás manejadores de la cadena, excepto los que se hayan configurado para manejar errores como se ha descrito anteriormente.
- -## El manejador de errores predeterminado - -Express se suministra con un manejador de errores incorporado, que se encarga de los errores que aparecen en la aplicación. Esta función de middleware de manejo de errores predeterminada se añade al final de la pila de funciones de middleware. - -Si pasa un error a `next()` y no lo maneja en el manejador de errores, lo manejará el manejador de errores incorporado; el error se escribirá en el cliente con el seguimiento de la pila. El seguimiento de la pila no se incluye en el entorno de producción. - -
-Establezca la variable de entorno `NODE_ENV` en `production`, para ejecutar la aplicación en modalidad de producción. -
- -Si invoca `next()` con un error después de haber empezado a escribir la respuesta (por ejemplo, si encuentra un error mientras se envía la respuesta en modalidad continua al cliente), el manejador de errores predeterminado de Express cierra la conexión y falla la solicitud. - -Por lo tanto, cuando añade un manejador de errores personalizado, se recomienda delegar en los mecanismos de manejo de errores predeterminados de Express, cuando las cabeceras ya se han enviado al cliente: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/es/guide/migrating-4.md b/es/guide/migrating-4.md old mode 100755 new mode 100644 index 1eee5aca04..c48ad90428 --- a/es/guide/migrating-4.md +++ b/es/guide/migrating-4.md @@ -1,15 +1,15 @@ --- layout: page title: Migración a 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. menu: guide -lang: es -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. +lang: en +redirect_from: " " --- # Migración a Express 4 -

Visión general

+

Overview

Express 4 es un cambio que rompe el código existente de Express 3, etc. Esto implica que una aplicación Express 3 existente no funcionará si actualiza la versión de Express en sus dependencias. @@ -18,7 +18,7 @@ En este artículo se describen:

Los cambios en Express 4

@@ -26,7 +26,7 @@ En este artículo se describen: Se han realizado varios cambios importantes en Express 4:
    -
  • Cambios en el sistema principal y de middleware de Express. Las dependencias de Connect y el middleware incorporado se han eliminado, por lo que debe añadir el middleware manualmente. +
  • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
  • Cambios en el sistema de direccionamiento.
  • Otros cambios.
  • @@ -34,8 +34,8 @@ Se han realizado varios cambios importantes en Express 4: Vea también: -* [Nuevas características en 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) -* [Migración de 3.x a 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) +- [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)

    Cambios en el sistema principal y de middleware de Express @@ -53,7 +53,7 @@ middleware necesario para ejecutar la aplicación. Sólo tiene que seguir estos En la tabla siguiente se lista el middleware de Express 3 y su contrapartida en Express 4. - + @@ -85,23 +85,24 @@ En la tabla siguiente se lista el middleware de Express 3 y su contrapartida en -
    Express 3Express 4
    Express 3Express 4
    express.bodyParser body-parser + multer
    serve-index
    express.static serve-static
    +

Esta es la [lista completa](https://github.com/senchalabs/connect#middleware) de middleware de Express 4. En la mayoría de los casos, sólo tiene que sustituir el middleware de la versión 3 antigua por su contrapartida de Express 4. Para obtener detalles, consulte la documentación del módulo en GitHub. -

app.use acepta parámetros

+

app.use accepts parameters

En la versión 4, puede utilizar un parámetro de variable para definir la vía de acceso donde se cargan las funciones de middleware y, a continuación, leer el valor del parámetro en el manejador de rutas. -Por ejemplo: +For example: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

El sistema de direccionamiento

@@ -111,10 +112,11 @@ Ahora las aplicaciones cargan implícitamente el middleware de direccionamiento, La forma en que define las rutas no varía, pero el sistema de direccionamiento tiene dos nuevas características que permiten organizar las rutas: {: .doclist } -* Un nuevo método, `app.route()`, para crear manejadores de rutas encadenables para una vía de acceso de ruta. -* Una nueva clase, `express.Router`, para crear manejadores de rutas montables modulares. -

Método app.route()

+- Un nuevo método, `app.route()`, para crear manejadores de rutas encadenables para una vía de acceso de ruta. +- Una nueva clase, `express.Router`, para crear manejadores de rutas montables modulares. + +

app.route() method

El nuevo método `app.route()` permite crear manejadores de rutas encadenables para una vía de acceso de ruta. Como la vía de acceso se especifica en una única ubicación, la creación de rutas modulares es muy útil, al igual que la reducción de redundancia y errores tipográficos. Para obtener más información sobre las rutas, consulte la [`documentación` de Router()](/{{ page.lang }}/4x/api.html#router). @@ -122,18 +124,18 @@ A continuación, se muestra un ejemplo de manejadores de rutas encadenados que s ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` -

Clase express.Router

+

express.Router class

La otra característica que permite organizar las rutas es una nueva clase, `express.Router`, que puede utilizar para crear manejadores de rutas montables modulares. Una instancia `Router` es un sistema de middleware y direccionamiento completo; por este motivo, a menudo se conoce como una "miniaplicación". @@ -146,16 +148,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -167,7 +169,7 @@ A continuación, cargue el módulo de direccionador en la aplicación: ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -175,15 +177,15 @@ app.use('/birds', birds) La aplicación ahora podrá manejar solicitudes a las vías de acceso `/birds` y `/birds/about`, e invocará el middleware `timeLog` que es específico de la ruta.

-Otros cambios +Other changes

En la tabla siguiente se muestran otros cambios pequeños pero importantes en Express 4: - - - + + + @@ -195,7 +197,7 @@ Node.js 0.8.x. `http.createServer()` @@ -288,12 +290,12 @@ Se ha eliminado. La funcionalidad está ahora limitada a establecer el valor de cookie básico. Utilice `res.cookie()` para obtener la funcionalidad adicional. -
ObjetoDescripción
ObjectDescription
Node.js -El módulo `http` ya no es necesario, a menos que necesite trabajar directamente con él (socket.io/SPDY/HTTPS). La aplicación puede iniciarse utilizando la función `app.listen()`. +The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). La aplicación puede iniciarse utilizando la función `app.listen()`.
+

Migración de aplicación de ejemplo

A continuación, se muestra un ejemplo de migración de una aplicación Express 3 a Express 4. -Los archivos de interés son `app.js` y `package.json`. +The files of interest are `app.js` and `package.json`.

Aplicación versión 3 @@ -301,7 +303,7 @@ Aplicación versión 3

app.js

-Considere una aplicación Express v.3 con el siguiente archivo `app.js`: +Consider an Express v.3 application with the following `app.js` file: ```js var express = require('express') @@ -332,7 +334,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -369,12 +371,12 @@ $ npm install serve-favicon morgan method-override express-session body-parser m Realice los cambios siguientes en `app.js`: 1. Las funciones de middleware de Express incorporadas `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` y - `express.errorHandler` ya no están disponibles en el objeto `express`. Debe instalar sus alternativas manualmente y cargarlas en la aplicación. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` y + `express.errorHandler` ya no están disponibles en el objeto `express`. Debe instalar sus alternativas manualmente y cargarlas en la aplicación. 2. Ya no es necesario cargar la función `app.router`. - No es un objeto de aplicación Express 4 válido, por lo que debe eliminar el código `app.use(app.router);`. + No es un objeto de aplicación Express 4 válido, por lo que debe eliminar el código `app.use(app.router);`. 3. Asegúrese de que las funciones de middleware se cargan en el orden correcto: cargue `errorHandler` después de cargar las rutas de aplicación. @@ -397,7 +399,7 @@ La ejecución del mandato `npm` anterior actualizará `package.json` de la sigui "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -462,14 +464,14 @@ server.listen(app.get('port'), () => { A menos que necesite trabajar directamente con el módulo `http` (socket.io/SPDY/HTTPS), no es necesario cargarlo y la aplicación puede iniciarse simplemente de la siguiente manera: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ```
-

Ejecutar la aplicación

+

Run the app

El proceso de migración está completo y la aplicación es ahora una aplicación Express 4. Para confirmarlo, inicie la aplicación utilizando el siguiente mandato: @@ -509,11 +511,12 @@ Ahora el mandato `express` en el sistema se actualiza al generador de Express 4. Las opciones de mandato y el uso continúan prácticamente iguales, con las siguientes excepciones: {: .doclist } -* Se ha eliminado la opción `--sessions`. -* Se ha eliminado la opción `--jshtml`. -* Se ha añadido la opción `--hogan` para dar soporte a [Hogan.js](http://twitter.github.io/hogan.js/). -

Ejemplo

+- Removed the `--sessions` option. +- Removed the `--jshtml` option. +- Se ha añadido la opción `--hogan` para dar soporte a [Hogan.js](http://twitter.github.io/hogan.js/). + +

Ejecute el siguiente mandato para crear una aplicación Express 4: @@ -544,7 +547,7 @@ suprima la línea `module.exports = app;` al final del archivo `app.js` y pegue ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -557,4 +560,4 @@ var debug = require('debug')('app4') A continuación, cambie `"start": "node ./bin/www"` en el archivo `package.json` por `"start": "node app.js"`. -Ahora ha devuelto la funcionalidad de `./bin/www` a `app.js`. Este cambio no se recomienda, pero el ejercicio permite entender cómo funciona el archivo `./bin/www` y por qué el archivo `app.js` ya no se inicia solo. +Ahora ha devuelto la funcionalidad de `./bin/www` a `app.js`. Este cambio no se recomienda, pero el ejercicio permite entender cómo funciona el archivo `./bin/www` y por qué el archivo `app.js` ya no se inicia solo. diff --git a/es/guide/migrating-5.md b/es/guide/migrating-5.md old mode 100755 new mode 100644 index c364b49b9c..e98bd7df15 --- a/es/guide/migrating-5.md +++ b/es/guide/migrating-5.md @@ -1,32 +1,45 @@ --- layout: page title: Migración a Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide -lang: es -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +lang: en +redirect_from: " " --- # Migración a Express 5 -

Visión general

+

Overview

-Express 5.0 continúa en la etapa del release alfa, pero hay una vista previa de los cambios que habrá en el release y cómo migrar la aplicación Express 4 a Express 5. +Express 5 no es muy diferente de Express 4: los cambios en la API no son tan significativos como los de la migración de 3.0 a 4.0. Aunque la API básica permanece igual, continúa habiendo cambios que rompen el código existente; es decir, un programa de Express 4 existente no funcionará si lo actualiza para que utilice Express 5. -Express 5 no es muy diferente de Express 4: los cambios en la API no son tan significativos como los de la migración de 3.0 a 4.0. Aunque la API básica permanece igual, continúa habiendo cambios que rompen el código existente; es decir, un programa de Express 4 existente no funcionará si lo actualiza para que utilice Express 5. +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -Para instalar el release alpha más reciente y obtener una vista previa de Express 5, especifique el siguiente mandato en el directorio raíz de la aplicación: - -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` A continuación, puede ejecutar las pruebas automatizadas para ver qué falla y solucionar los problemas según las actualizaciones siguientes. Después de solucionar los errores de las pruebas, ejecute la aplicación para ver qué errores se producen. Verá rápidamente si la aplicación utiliza métodos o propiedades que no están soportados. -

Cambios en Express 5

+## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` + +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). -A continuación, se muestra la lista de cambios (a partir del release alpha 2) que le afectarán como usuario de Express. -Consulte la [Pull request](https://github.com/expressjs/express/pull/2237) para ver una lista de todas las características planificadas. +

Changes in Express 5

**Métodos y propiedades eliminados** @@ -38,26 +51,40 @@ Consulte la [Pull request](https://github.com/expressjs/express/pull/2237) para
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
  • -**Modificados** +**Mejoras** -**Mejoras** +**Modificados** -

    Métodos y propiedades eliminados

    +### Removed methods and properties Si utiliza cualquiera de estos métodos o propiedades en la aplicación, se bloqueará. Por lo tanto, deberá cambiar la aplicación después de actualizar a la versión 5. @@ -65,21 +92,75 @@ Si utiliza cualquiera de estos métodos o propiedades en la aplicación, se bloq Express 5 ya no da soporte a la función `app.del()`. Si utiliza esta función, se genera un error. Para registrar las rutas HTTP DELETE, utilice la función `app.delete()` en su lugar. -Inicialmente, se utilizaba `del` en lugar de `delete`, porque `delete` es una palabra clave reservada en JavaScript. No obstante, a partir de ECMAScript 6, `delete` y otras palabras clave reservadas pueden utilizarse correctamente como nombres de propiedad. Puede leer aquí la discusión que llevó a descartar la función `app.del`. +Inicialmente, se utilizaba `del` en lugar de `delete`, porque `delete` es una palabra clave reservada en JavaScript. No obstante, a partir de ECMAScript 6, `delete` y otras palabras clave reservadas pueden utilizarse correctamente como nombres de propiedad. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

    app.param(fn)

    La firma `app.param(fn)` se utilizaba para modificar el comportamiento de la función `app.param(name, fn)`. Está en desuso desde v4.11.0 y Express 5 ya no le da soporte. -

    Nombres de métodos pluralizados

    +

    Pluralized method names

    -Los siguientes nombres de métodos se han pluralizado. En Express 4, el uso de los métodos antiguos daba como resultado un aviso de obsolescencia. Express 5 ya no les da soporte: +Los siguientes nombres de métodos se han pluralizado. En Express 4, el uso de los métodos antiguos daba como resultado un aviso de obsolescencia. Express 5 ya no les da soporte: + +`req.acceptsLanguage()` se ha sustituido por `req.acceptsLanguages()`. `req.acceptsCharset()` se ha sustituido por `req.acceptsCharsets()`. `req.acceptsEncoding()` se ha sustituido por `req.acceptsEncodings()`. -`req.acceptsLanguage()` se ha sustituido por `req.acceptsLanguages()`. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    Dos puntos (:) delanteros en el nombre de app.param(name, fn)

    @@ -91,43 +172,334 @@ Esto no afectará al código si sigue la documentación de Express 4 de [app.par Este método potencialmente confuso y peligroso de recuperar datos de formulario se ha eliminado. No necesitará buscar específicamente el nombre de parámetro enviado en el objeto `req.params`, `req.body` o `req.query`. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

    res.json(obj, status)

    Express 5 ya no da soporte a la firma `res.json(obj, status)`. En su lugar, establezca el estado y encadénelo al método `res.json()` de la siguiente manera: `res.status(status).json(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

    res.jsonp(obj, status)

    Express 5 ya no da soporte a la firma `res.jsonp(obj, status)`. En su lugar, establezca el estado y encadénelo al método `res.jsonp()` de la siguiente manera: `res.status(status).jsonp(obj)`. -

    res.send(body, status)

    +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    Express 5 ya no da soporte a la firma `res.send(obj, status)`. En su lugar, establezca el estado y encadénelo al método `res.send()` de la siguiente manera: `res.status(status).send(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

    res.send(body, status)

    + +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

    res.send(status)

    -Express 5 ya no da soporte a la firma res.send(status), donde *`status`* es un número. En su lugar, utilice la función `res.sendStatus(statusCode)`, que establece el código de estado de la cabecera de respuesta HTTP y envía la versión de texto del código: "Not Found", "Internal Server Error", etc. +Express 5 ya no da soporte a la firma res.send(status), donde _`status`_ es un número. En su lugar, utilice la función `res.sendStatus(statusCode)`, que establece el código de estado de la cabecera de respuesta HTTP y envía la versión de texto del código: "Not Found", "Internal Server Error", etc. Si necesita enviar un número utilizando la función `res.send()`, escríbalo entre comillas para convertirlo en una serie, para que Express no lo interprete como un intento de utilizar la firma antigua no soportada. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +``` +

    res.sendfile()

    La función `res.sendfile()` se ha sustituido por una versión de la función `res.sendFile()` con cada palabra en mayúscula en Express 5. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. Está en desuso desde v4.11.0 y Express 5 ya no le da soporte. + +

    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. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    Modificados

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. For example: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +For example: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    El objeto `app.router`, que se ha eliminado en Express 4, ha vuelto en Express 5. En la nueva versión, este objeto es sólo una referencia al direccionador de Express base, a diferencia de en Express 3, donde una aplicación debía cargarlo explícitamente. +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

    req.host

    -En Express 4, la función `req.host` fragmentaba incorrectamente el número de puerto si estaba presente. En Express 5, el número de puerto se mantiene. +En Express 4, la función `req.host` fragmentaba incorrectamente el número de puerto si estaba presente. In Express 5, the port number is maintained.

    req.query

    -De Express 4.7 y Express 5 en adelante, la opción de analizador de consultas puede aceptar `false` para inhabilitar el análisis de series de consulta si desea utilizar su propia función para la lógica de análisis de series de consulta. +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". -

    Mejoras

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### Improvements

    res.render()

    Este método ahora impone un comportamiento asíncrono para todos los motores de vistas, lo que evita los errores provocados por los motores de vistas que tenían una implementación síncrona e incumplían la interfaz recomendada. + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/es/guide/overriding-express-api.md b/es/guide/overriding-express-api.md new file mode 100644 index 0000000000..0ff0e90f4f --- /dev/null +++ b/es/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: en +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/es/guide/routing.md b/es/guide/routing.md old mode 100755 new mode 100644 index 2d9168bf96..cd48f5428f --- a/es/guide/routing.md +++ b/es/guide/routing.md @@ -1,18 +1,29 @@ --- layout: page title: Direccionamiento de Express +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide -lang: es -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +lang: en +redirect_from: " " --- # Direccionamiento -*Direccionamiento* hace referencia a la definición de puntos finales de aplicación (URI) y cómo responden a las solicitudes de cliente. +_Direccionamiento_ hace referencia a la definición de puntos finales de aplicación (URI) y cómo responden a las solicitudes de cliente. Para ver una introducción al direccionamiento, consulte [Direccionamiento básico](/{{ page.lang }}/starter/basic-routing.html). -El siguiente código es un ejemplo de una ruta muy básica. +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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. + +The following code is an example of a very basic route. ```js const express = require('express') @@ -24,9 +35,9 @@ app.get('/', (req, res) => { }) ``` -

    Métodos de ruta

    +

    Route methods

    -Un método de ruta se deriva de uno de los métodos HTTP y se adjunta a una instancia de la clase `express`. +A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class. El siguiente código es un ejemplo de las rutas que se definen para los métodos GET y POST a la raíz de la aplicación. @@ -42,15 +53,10 @@ app.post('/', (req, res) => { }) ``` -Express da soporte a los siguientes métodos de direccionamiento que se corresponden con los métodos HTTP: `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search` y `connect`. - -
    -Para direccionar los métodos que se convierten en nombres de variable JavaScript no válidos, utilice la notación entre corchetes. Por ejemplo, `app['m-search']('/', function ...` -
    - -Hay un método de direccionamiento especial, `app.all()`, que no se deriva de ningún método HTTP. Este método se utiliza para cargar funciones de middleware en una vía de acceso para todos los métodos de solicitud. +Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -En el siguiente ejemplo, el manejador se ejecutará para las solicitudes a "/secret", tanto si utiliza GET, POST, PUT, DELETE, como cualquier otro método de solicitud HTTP soportado en el [módulo http](https://nodejs.org/api/http.html#http_http_methods). +Hay un método de direccionamiento especial, `app.all()`, que no se deriva de ningún método HTTP. Este método se utiliza para cargar funciones de middleware en una vía de acceso para todos los métodos de solicitud. En el siguiente ejemplo, el manejador se ejecutará para las solicitudes a "/secret", tanto si utiliza GET, POST, PUT, DELETE, como cualquier otro método de solicitud HTTP soportado en el [módulo http](https://nodejs.org/api/http.html#http_http_methods). ```js app.all('/secret', (req, res, next) => { @@ -63,15 +69,32 @@ app.all('/secret', (req, res, next) => { Las vías de acceso de ruta, en combinación con un método de solicitud, definen los puntos finales en los que pueden realizarse las solicitudes. Las vías de acceso de ruta pueden ser series, patrones de serie o expresiones regulares. -
    - Express utiliza [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) para correlacionar las vías de acceso de ruta; consulte la documentación de path-to-regexp para ver todas las posibilidades para definir vías de acceso de ruta. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) es una herramienta muy útil para probar rutas básicas de Express, aunque no da soporte a la coincidencia de patrones. -
    +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
    -Las series de consulta no forman parte de la vía de acceso de ruta. -
    +{% include admonitions/caution.html content=caution-character %} + +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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 Route Tester](http://forbeslindesay.github.io/express-route-tester/) es una herramienta muy útil para probar rutas básicas de Express, aunque no da soporte a la coincidencia de patrones. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. -Estos son algunos ejemplos de vías de acceso de ruta basadas en series. +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Route paths based on strings Esta vía de acceso de ruta coincidirá con las solicitudes a la ruta raíz, `/`. @@ -97,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -Estos son algunos ejemplos de vías de acceso de ruta basadas en patrones de serie. +### Route paths based on string patterns + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} Esta vía de acceso de ruta coincidirá con `acd` y `abcd`. @@ -131,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
    -Los caracteres ?, +, * y () son subconjuntos de sus contrapartidas de expresiones regulares. El guión (-) y el punto (.) se interpretan literalmente en las vías de acceso basadas en series. -
    - -Ejemplos de vías de acceso de ruta basadas en expresiones regulares: +### Ejemplos de vías de acceso de ruta basadas en expresiones regulares: Esta vía de acceso de ruta coincidirá con cualquier valor con una "a" en el nombre de la ruta. @@ -153,13 +176,78 @@ app.get(/.*fly$/, (req, res) => { }) ``` -

    Manejadores de rutas

    +

    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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
    +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} + +

    Route handlers

    Puede proporcionar varias funciones de devolución de llamada que se comportan como [middleware](/{{ page.lang }}/guide/using-middleware.html) para manejar una solicitud. La única excepción es que estas devoluciones de llamada pueden invocar `next('route')` para omitir el resto de las devoluciones de llamada de ruta. Puede utilizar este mecanismo para imponer condiciones previas en una ruta y, a continuación, pasar el control a las rutas posteriores si no hay motivo para continuar con la ruta actual. Los manejadores de rutas pueden tener la forma de una función, una matriz de funciones o combinaciones de ambas, como se muestra en los siguientes ejemplos. -Una función de devolución de llamada individual puede manejar una ruta. Por ejemplo: +Una función de devolución de llamada individual puede manejar una ruta. For example: ```js app.get('/example/a', (req, res) => { @@ -167,7 +255,7 @@ app.get('/example/a', (req, res) => { }) ``` -Más de una función de devolución de llamada puede manejar una ruta (asegúrese de especificar el objeto `next`). Por ejemplo: +Más de una función de devolución de llamada puede manejar una ruta (asegúrese de especificar el objeto `next`). For example: ```js app.get('/example/b', (req, res, next) => { @@ -177,7 +265,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -Una matriz de funciones de devolución de llamada puede manejar una ruta. Por ejemplo: + +Una matriz de funciones de devolución de llamada puede manejar una ruta. For example: ```js const cb0 = function (req, res, next) { @@ -197,7 +286,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -Una combinación de funciones independientes y matrices de funciones puede manejar una ruta. Por ejemplo: +Una combinación de funciones independientes y matrices de funciones puede manejar una ruta. For example: ```js const cb0 = function (req, res, next) { @@ -218,21 +307,21 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => { }) ``` -

    Métodos de respuesta

    +

    Response methods

    Los métodos en el objeto de respuesta (`res`) de la tabla siguiente pueden enviar una respuesta al cliente y terminar el ciclo de solicitud/respuestas. Si ninguno de estos métodos se invoca desde un manejador de rutas, la solicitud de cliente se dejará colgada. -| Método | Descripción -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Solicita un archivo para descargarlo. -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Finaliza el proceso de respuesta. -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envía una respuesta JSON. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Envía una respuesta JSON con soporte JSONP. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redirecciona una solicitud. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Representa una plantilla de vista. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envía una respuesta de varios tipos. -| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | Envía un archivo como una secuencia de octetos. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Establece el código de estado de la respuesta y envía su representación de serie como el cuerpo de respuesta. +| Method | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Solicita un archivo para descargarlo. | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Finaliza el proceso de respuesta. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envía una respuesta JSON. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Send a JSON response with JSONP support. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redirecciona una solicitud. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Representa una plantilla de vista. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envía una respuesta de varios tipos. | +| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | Envía un archivo como una secuencia de octetos. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Establece el código de estado de la respuesta y envía su representación de serie como el cuerpo de respuesta. |

    app.route()

    @@ -267,10 +356,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -288,9 +379,15 @@ A continuación, cargue el módulo de direccionador en la aplicación: ```js const birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` La aplicación ahora podrá manejar solicitudes a `/birds` y `/birds/about`, así como invocar la función de middleware `timeLog` que es específica de la ruta. + +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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/es/guide/using-middleware.md b/es/guide/using-middleware.md old mode 100755 new mode 100644 index e8ed03a1ce..879552c6ff --- a/es/guide/using-middleware.md +++ b/es/guide/using-middleware.md @@ -1,45 +1,46 @@ --- layout: page title: Utilización del middleware de Express +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide -lang: es -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +lang: en +redirect_from: " " --- # Utilización del middleware Express es una infraestructura web de direccionamiento y middleware que tiene una funcionalidad mínima propia: una aplicación Express es fundamentalmente una serie de llamadas a funciones de middleware. -Las funciones de *middleware* son funciones que tienen acceso al [objeto de solicitud](/{{ page.lang }}/4x/api.html#req) (`req`), al [objeto de respuesta](/{{ page.lang }}/4x/api.html#res) (`res`) y a la siguiente función de middleware en el ciclo de solicitud/respuestas de la aplicación. La siguiente función de middleware se denota normalmente con una variable denominada `next`. +Las funciones de _middleware_ son funciones que tienen acceso al [objeto de solicitud](/{{ page.lang }}/4x/api.html#req) (`req`), al [objeto de respuesta](/{{ page.lang }}/4x/api.html#res) (`res`) y a la siguiente función de middleware en el ciclo de solicitud/respuestas de la aplicación. La siguiente función de middleware se denota normalmente con una variable denominada `next`. Las funciones de middleware pueden realizar las siguientes tareas: -* Ejecutar cualquier código. -* Realizar cambios en la solicitud y los objetos de respuesta. -* Finalizar el ciclo de solicitud/respuestas. -* Invocar la siguiente función de middleware en la pila. +- Execute any code. +- Realizar cambios en la solicitud y los objetos de respuesta. +- Finalizar el ciclo de solicitud/respuestas. +- Invocar la siguiente función de middleware en la pila. -Si la función de middleware actual no finaliza el ciclo de solicitud/respuestas, debe invocar `next()` para pasar el control a la siguiente función de middleware. De lo contrario, la solicitud quedará colgada. +Si la función de middleware actual no finaliza el ciclo de solicitud/respuestas, debe invocar `next()` para pasar el control a la siguiente función de middleware. Otherwise, the request will be left hanging. -Una aplicación Express puede utilizar los siguientes tipos de middleware: +An Express application can use the following types of middleware: - - [Middleware de nivel de aplicación](#middleware.application) - - [Middleware de nivel de direccionador](#middleware.router) - - [Middleware de manejo de errores](#middleware.error-handling) - - [Middleware incorporado](#middleware.built-in) - - [Middleware de terceros](#middleware.third-party) +- [Application-level middleware](#middleware.application) +- [Middleware de nivel de direccionador](#middleware.router) +- [Error-handling middleware](#middleware.error-handling) +- [Built-in middleware](#middleware.built-in) +- [Third-party middleware](#middleware.third-party) Puede cargar middleware de nivel de aplicación y de nivel de direccionador con una vía de acceso de montaje opcional. También puede cargar una serie de funciones de middleware a la vez, lo que crea una subpila del sistema de middleware en un punto de montaje. -

    Middleware de nivel de aplicación

    +

    Application-level middleware

    Enlace el middleware de nivel de aplicación a una instancia del [objeto de aplicación](/{{ page.lang }}/4x/api.html#app) utilizando las funciones `app.use()` y `app.METHOD()`, donde `METHOD` es el método HTTP de la solicitud que maneja la función de middleware (por ejemplo, GET, PUT o POST) en minúsculas. -Este ejemplo muestra una función de middleware sin ninguna vía de acceso de montaje. La función se ejecuta cada vez que la aplicación recibe una solicitud. +Este ejemplo muestra una función de middleware sin ninguna vía de acceso de montaje. The function is executed every time the app receives a request. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -92,12 +93,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` Para omitir el resto de las funciones de middleware de una pila de middleware de direccionador, invoque `next('route')` para pasar el control a la siguiente ruta. -**NOTA**: `next('route')` sólo funcionará en las funciones de middleware que se hayan cargado utilizando las funciones `app.METHOD()` o `router.METHOD()`. + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} Este ejemplo muestra una subpila de middleware que maneja solicitudes GET a la vía de acceso `/user/:id`. @@ -106,15 +114,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +A continuación, se muestra un ejemplo de uso de la función de middleware `express.static` con un objeto de opciones elaboradas: + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -125,11 +154,13 @@ El middleware de nivel de direccionador funciona de la misma manera que el middl ```js const router = express.Router() ``` + Cargue el middleware de nivel de direccionador utilizando las funciones `router.use()` y `router.METHOD()`. El siguiente código de ejemplo replica el sistema de middleware que se ha mostrado anteriormente para el middleware de nivel de aplicación, utilizando el middleware de nivel de direccionador: ```js +const express = require('express') const app = express() const router = express.Router() @@ -153,7 +184,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -168,10 +199,36 @@ router.get('/user/:id', (req, res, next) => { // mount the router on the app app.use('/', router) ``` -

    Middleware de manejo de errores

    + +Para obtener más detalles sobre la función `serve-static` y sus opciones, consulte la documentación de [serve-static](https://github.com/expressjs/serve-static). + +Este ejemplo muestra una subpila de middleware que maneja solicitudes GET a la vía de acceso `/user/:id`. + +```js +const express = require('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

    -El middleware de manejo de errores siempre utiliza *cuatro* argumentos. Debe proporcionar cuatro argumentos para identificarlo como una función de middleware de manejo de errores. Aunque no necesite utilizar el objeto `next`, debe especificarlo para mantener la firma. De lo contrario, el objeto `next` se interpretará como middleware normal y no podrá manejar errores. +El middleware de manejo de errores siempre utiliza *cuatro* argumentos. Debe proporcionar cuatro argumentos para identificarlo como una función de middleware de manejo de errores. Aunque no necesite utilizar el objeto `next`, debe especificarlo para mantener la firma. De lo contrario, el objeto `next` se interpretará como middleware normal y no podrá manejar errores.
    Defina las funciones de middleware de manejo de errores de la misma forma que otras funciones de middleware, excepto con cuatro argumentos en lugar de tres, específicamente con la firma `(err, req, res, next)`: @@ -185,58 +242,17 @@ app.use((err, req, res, next) => { Para obtener detalles sobre el middleware de manejo de errores, consulte: [Manejo de errores](/{{ page.lang }}/guide/error-handling.html). -

    Middleware incorporado

    +

    Built-in middleware

    Desde la versión 4.x, Express ya no depende de [Connect](https://github.com/senchalabs/connect). Excepto `express.static`, todas las funciones de middleware que se incluían previamente con Express están ahora en módulos diferentes. Consulte [la lista de funciones de middleware](https://github.com/senchalabs/connect#middleware). -

    express.static(root, [options])

    - -La única función de middleware incorporado en Express es `express.static`. Esta función se basa en [serve-static](https://github.com/expressjs/serve-static) y es responsable del servicio de activos estáticos de una aplicación Express. +La única función de middleware incorporado en Express es `express.static`. -El argumento `root` especifica el directorio raíz desde el que se realiza el servicio de activos estáticos. - -El objeto `options` opcional puede tener las siguientes propiedades: - -| Propiedad | Descripción | Tipo | Valor predeterminado | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Opción para el servicio de dotfiles. Los valores posibles son "allow", "deny" e "ignore" | Serie | "ignore" | -| `etag` | Habilitar o inhabilitar la generación de etag | Booleano | `true` | -| `extensions` | Establece las reservas de extensiones de archivos. | Matriz | `[]` | -| `index` | Envía el archivo de índices de directorios. Establézcalo en `false` para inhabilitar la indexación de directorios. | Mixto | "index.html" | - `lastModified` | Establezca la cabecera `Last-Modified` en la última fecha de modificación del archivo en el sistema operativo. Los valores posibles son `true` o `false`. | Booleano | `true` | -| `maxAge` | Establezca la propiedad max-age de la cabecera Cache-Control en milisegundos o una serie en [formato ms](https://www.npmjs.org/package/ms) | Número | 0 | -| `redirect` | Redireccionar a la "/" final cuando el nombre de vía de acceso es un directorio. | Booleano | `true` | -| `setHeaders` | Función para establecer las cabeceras HTTP que se sirven con el archivo. | Función | | - -A continuación, se muestra un ejemplo de uso de la función de middleware `express.static` con un objeto de opciones elaboradas: - -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -Puede tener más de un directorio estático para cada aplicación: - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` - -Para obtener más detalles sobre la función `serve-static` y sus opciones, consulte la documentación de [serve-static](https://github.com/expressjs/serve-static). +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+** -

    Middleware de terceros

    +

    Third-party middleware

    Utilice el middleware de terceros para añadir funcionalidad a las aplicaciones Express. diff --git a/es/guide/using-template-engines.md b/es/guide/using-template-engines.md old mode 100755 new mode 100644 index b8b76464e6..80f8a8f511 --- a/es/guide/using-template-engines.md +++ b/es/guide/using-template-engines.md @@ -1,35 +1,46 @@ --- layout: page title: Utilización de motores de plantilla con Express +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide -lang: es -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +lang: en +redirect_from: " " --- # Utilización de motores de plantilla con Express -Para que Express pueda representar archivos de plantilla, deben establecerse los siguientes valores de aplicación: +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. -* `views`, el directorio donde se encuentran los archivos de plantilla. Ejemplo: `app.set('views', './views')` -* `view engine`, el motor de plantilla que se utiliza. Ejemplo: `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, el directorio donde se encuentran los archivos de plantilla. Ejemplo: `app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, el motor de plantilla que se utiliza. Ejemplo: `app.set('view engine', 'pug')` A continuación, instale el paquete npm de motor de plantilla correspondiente: ```bash $ npm install pug --save -```bash +```
    -Los motores de plantilla compatibles con Express como, por ejemplo, Pug exportan una función denominada `__express(filePath, options, callback)`, que es invocada por la función `res.render()` para representar el código de plantilla. +Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`, +which `res.render()` calls to render the template code. + +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. -Algunos motores de plantilla no siguen esta convención. La biblioteca [Consolidate.js](https://www.npmjs.org/package/consolidate) sigue esta convención correlacionando todos los motores de plantilla de Node.js más conocidos, por lo que funciona de forma ininterrumpida en Express.
    -Una vez establecida la propiedad view engine, no tiene que especificar el motor ni cargar el módulo de motor de plantilla en la aplicación; Express carga el módulo internamente, como se muestra a continuación (para el ejemplo anterior). +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: ```js -app.set('view engine', 'pug'); +app.set('view engine', 'pug') ``` Cree un archivo de plantilla Pug denominado `index.pug` en el directorio `views`, con el siguiente contenido: @@ -52,4 +63,4 @@ app.get('/', (req, res) => { Cuando realice una solicitud a la página de inicio, el archivo `index.pug` se representará como HTML. -Para obtener más información sobre cómo funcionan los motores de plantilla en Express, consulte: ["Desarrollo de motores de plantilla para Express"](/{{ page.lang }}/advanced/developing-template-engines.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/es/guide/writing-middleware.md b/es/guide/writing-middleware.md old mode 100755 new mode 100644 index eb6762201a..f54191a926 --- a/es/guide/writing-middleware.md +++ b/es/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: Escritura de middleware para su uso en aplicaciones Express +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide -lang: es -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +lang: en +redirect_from: " " --- # Escritura de middleware para su uso en aplicaciones Express -

    Visión general

    +

    Overview

    -Las funciones de *middleware* son funciones que tienen acceso al [objeto de solicitud](/{{ page.lang }}/4x/api.html#req) (`req`), al [objeto de respuesta](/{{ page.lang }}/4x/api.html#res) (`res`) y a la siguiente función de middleware en el ciclo de solicitud/respuestas de la aplicación. La siguiente función de middleware se denota normalmente con una variable denominada `next`. +Las funciones de _middleware_ son funciones que tienen acceso al [objeto de solicitud](/{{ page.lang }}/4x/api.html#req) (`req`), al [objeto de respuesta](/{{ page.lang }}/4x/api.html#res) (`res`) y a la siguiente función de middleware en el ciclo de solicitud/respuestas de la aplicación. La siguiente función de middleware se denota normalmente con una variable denominada `next`. Las funciones de middleware pueden realizar las siguientes tareas: -* Ejecutar cualquier código. -* Realizar cambios en la solicitud y los objetos de respuesta. -* Finalizar el ciclo de solicitud/respuestas. -* Invocar el siguiente middleware en la pila. +- Execute any code. +- Realizar cambios en la solicitud y los objetos de respuesta. +- Finalizar el ciclo de solicitud/respuestas. +- Invocar el siguiente middleware en la pila. -Si la función de middleware actual no finaliza el ciclo de solicitud/respuestas, debe invocar `next()` para pasar el control a la siguiente función de middleware. De lo contrario, la solicitud quedará colgada. +Si la función de middleware actual no finaliza el ciclo de solicitud/respuestas, debe invocar `next()` para pasar el control a la siguiente función de middleware. Otherwise, the request will be left hanging. El siguiente ejemplo muestra los elementos de una llamada a función de middleware: -
    Vía de acceso (ruta) para la que se aplica la función de middleware.
    @@ -41,9 +41,16 @@ El siguiente ejemplo muestra los elementos de una llamada a función de middlewa
    Argumento de solicitud HTTP a la función de middleware, denominado "req" por convención.
    -
    +
    Elements of a middleware function call -
    Método HTTP para el que se aplica la función de middleware.
    +
    Método HTTP para el que se aplica la función de middleware.
    + + +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. + +

    A continuación, se muestra un ejemplo de una aplicación Express simple, "Hello World", para la que definirá dos funciones de middleware: +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 const express = require('express') @@ -56,8 +63,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    Desarrollo

    - +

    Middleware function myLogger

    Este es un ejemplo simple de una función de middleware denominada "myLogger". Esta función simplemente imprime "LOGGED" cuando una solicitud de la aplicación pasa por ella. La función de middleware se asigna a una variable denominada `myLogger`. ```js @@ -68,8 +74,9 @@ const myLogger = function (req, res, next) { ```
    -Observe la llamada anterior a `next()`. La llamada a esta función invoca la siguiente función de middleware en la aplicación. -La función `next()` no forma parte de la API de Express o Node.js, pero es el tercer argumento que se pasa a la función de middleware. La función `next()` puede tener cualquier nombre, pero por convención siempre se denomina "next". Para evitar confusiones, utilice siempre esta convención. +Observe la llamada anterior a `next()`. La llamada a esta función invoca la siguiente función de middleware en la aplicación. +La función `next()` no forma parte de la API de Express o Node.js, pero es el tercer argumento que se pasa a la función de middleware. La función `next()` puede tener cualquier nombre, pero por convención siempre se denomina "next". +Para evitar confusiones, utilice siempre esta convención.
    Para cargar la función de middleware, llame a `app.use()`, especificando la función de middleware. @@ -93,7 +100,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -Cada vez que la aplicación recibe una solicitud, imprime el mensaje "LOGGED" en el terminal. +Every time the app receives a request, it prints the message "LOGGED" to the terminal. El orden de carga del middleware es importante: las funciones de middleware que se cargan primero también se ejecutan primero. @@ -101,6 +108,8 @@ Si `myLogger` se carga después de la ruta a la vía de acceso raíz, la solicit La función de middleware `myLogger` simplemente imprime un mensaje y, a continuación, pasa la solicitud a la siguiente función de middleware de la pila llamando a la función `next()`. +

    Middleware function requestTime

    + El siguiente ejemplo añade una propiedad denominada `requestTime` al objeto de solicitud. Llamaremos a esta función de middleware "requestTime". ```js @@ -110,7 +119,7 @@ const requestTime = function (req, res, next) { } ``` -La aplicación ahora utiliza la función de middleware `requestTime`. Asimismo, la función de devolución de llamada de la ruta de vía de acceso raíz utiliza la propiedad que la función de middleware añade a `req` (el objeto de solicitud). +The app now uses the `requestTime` middleware function. Asimismo, la función de devolución de llamada de la ruta de vía de acceso raíz utiliza la propiedad que la función de middleware añade a `req` (el objeto de solicitud). ```js const express = require('express') @@ -131,8 +140,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + Cuando realiza una solicitud a la raíz de la aplicación, la aplicación ahora muestra la indicación de fecha y hora de la solicitud en el navegador. +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + Como tiene acceso al objeto de solicitud, el objeto de respuesta, la siguiente función de middleware de la pila y toda la API de Node.js, las posibilidades con las funciones de middleware son ilimitadas. Para obtener más información sobre el middleware de Express, consulte: [Utilización del middleware de Express](/{{ page.lang }}/guide/using-middleware.html). + +

    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 +module.exports = 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') + +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. diff --git a/es/resources/community.md b/es/resources/community.md old mode 100755 new mode 100644 index 677f5320f9..0097794b68 --- a/es/resources/community.md +++ b/es/resources/community.md @@ -1,15 +1,15 @@ --- layout: page title: Comunidad de Express +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources -lang: es -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +lang: en +redirect_from: " " --- # Comunidad -## Comité Técnico +## Technical committee El comité técnico de Express se reúne en línea cada dos semanas (según sea necesario) para discutir el desarrollo y el mantenimiento de Express, entre otros problemas relevantes para el proyecto Express. Cada reunión se anuncia normalmente en un [problema de expressjs/discussions](https://github.com/expressjs/discussions/issues) con un enlace para unirse o ver la reunión, que está abierta a todos los observadores. @@ -36,7 +36,7 @@ Los miembros del comité técnico de Express son: - [@niftylettuce](https://github.com/niftylettuce) - niftylettuce - [@troygoode](https://github.com/troygoode) - Troy Goode -## Express está hecho de muchos módulos +## Express is made of many modules Nuestra vibrante comunidad ha creado una larga variedad de extensiones, [módulos intermedios](/{{ page.lang }}/resources/middleware.html) y frameworks de nivel superior. @@ -47,11 +47,11 @@ Además, la comunidad de Express mantiene módulos en estas dos organizaciones d Para mantenerse al tanto de lo que está sucediendo en toda la comunidad, consulte [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). -## Problemas +## Issues Si ha encontrado lo que cree que es un error, o simplemente quiere hacer una solicitud de función, abre un ticket en la [cola de problemas](https://github.com/expressjs/express/issues). -## Ejemplos +## Examples Mire docenas de [ejemplos](https://github.com/expressjs/express/tree/master/examples) de aplicaciones Express en el repositorio que cubren todo, desde el diseño y la autenticación de API hasta la integración del motor de plantillas. @@ -59,17 +59,15 @@ Mire docenas de [ejemplos](https://github.com/expressjs/express/tree/master/exam La sección de [Discusiones de GitHub](https://github.com/expressjs/discussions) es un excelente espacio para participar en conversaciones sobre el desarrollo y mantenimiento de Express, así como para compartir ideas y debatir temas relacionados con su uso. - -# Marca de Express.js +# Branding of Express.js ## Logo de Express.js -Express es un proyecto de la Fundación OpenJS. Por favor, revise la [política de marcas registradas](https://trademark-policy.openjsf.org/) para obtener información sobre el uso permitido de los logotipos y marcas de Express.js. +Express is a project of the OpenJS Foundation. Por favor, revise la [política de marcas registradas](https://trademark-policy.openjsf.org/) para obtener información sobre el uso permitido de los logotipos y marcas de Express.js.
    -

    Logo de Marca

    - +

    Logo de Marca

    Express.js mark - Express.js mark + Express.js mark
    - +
    \ No newline at end of file diff --git a/es/resources/contributing.md b/es/resources/contributing.md new file mode 100644 index 0000000000..47d992d045 --- /dev/null +++ b/es/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contribuir a Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: en +redirect_from: " " +--- + +# Contribuir a Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/es/resources/glossary.md b/es/resources/glossary.md old mode 100755 new mode 100644 index d9c07759fa..8e7916e2bb --- a/es/resources/glossary.md +++ b/es/resources/glossary.md @@ -1,33 +1,25 @@ --- layout: page title: Glosario de Express +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. menu: resources -lang: es -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. +lang: en +redirect_from: " " --- # Glosario -### API - -Interfaz de programación de aplicaciones. Explique la abreviatura la primera vez que la utilice. - -### aplicación +### application En general, uno o varios programas diseñados para realizar operaciones para un determinado propósito. En el contexto de Express, un programa que utiliza la API de Express que se ejecuta en la plataforma Node.js. También puede hacer referencia a un [objeto de aplicación](/{{ page.lang }}/api.html#express). -### código abierto - -Consulte [Open source software en la Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). - -### direccionador +### API -Consulte [direccionador](/{{ page.lang }}/4x/api.html#router) en la referencia de API. +Application programming interface. Explique la abreviatura la primera vez que la utilice. ### Express -Una infraestructura web rápida, minimalista y flexible para las aplicaciones Node.js. En general, se prefiere "Express" a "Express.js", aunque esta también se acepta. +Una infraestructura web rápida, minimalista y flexible para las aplicaciones Node.js. En general, se prefiere "Express" a "Express.js", aunque esta también se acepta. ### libuv @@ -35,24 +27,40 @@ Una biblioteca de soporte multiplataforma que se centra en la E/S asíncrona, de ### middleware -Una función invocada por la capa de direccionamiento de Express antes del manejador de la última solicitud, por lo que se sitúa en medio de una solicitud sin formato y la última ruta prevista. Algunos puntos delicados de terminología relacionados con el middleware: +Una función invocada por la capa de direccionamiento de Express antes del manejador de la última solicitud, por lo que se sitúa en medio de una solicitud sin formato y la última ruta prevista. Algunos puntos delicados de terminología relacionados con el middleware: - * `var foo = require('middleware')` significa que *requiere* o *utiliza* un módulo Node.js. A continuación, la sentencia `var mw = foo()` normalmente devuelve el middleware. - * `app.use(mw)` significa que *se añade el middleware a la pila de procesos global*. - * `app.get('/foo', mw, function (req, res) { ... })` significa que *se añade el middleware a la pila de procesos "GET /foo"*. +- `var foo = require('middleware')` significa que _requiere_ o _utiliza_ un módulo Node.js. A continuación, la sentencia `var mw = foo()` normalmente devuelve el middleware. +- `app.use(mw)` significa que _se añade el middleware a la pila de procesos global_. +- `app.get('/foo', mw, function (req, res) { ... })` significa que _se añade el middleware a la pila de procesos "GET /foo"_. ### Node.js -Una plataforma de software que se utiliza para crear aplicaciones de red escalables. Node.js utiliza JavaScript como lenguaje de script y consigue un elevado rendimiento mediante E/S sin bloqueo y un bucle de sucesos de una sola hebra. Consulte [nodejs.org](http://nodejs.org/). **Nota de uso**: inicialmente, "Node.js", posteriormente "Node". +Una plataforma de software que se utiliza para crear aplicaciones de red escalables. Node.js utiliza JavaScript como lenguaje de script y consigue un elevado rendimiento mediante E/S sin bloqueo y un bucle de sucesos de una sola hebra. Consulte [nodejs.org](http://nodejs.org/). **Nota de uso**: inicialmente, "Node.js", posteriormente "Node". + +### Consulte [Open source software en la Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). -### respuesta +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). -Una respuesta HTTP. Un servidor devuelve un mensaje de respuesta HTTP al cliente. La respuesta contiene información de estado de finalización sobre la solicitud y también puede contener contenido de la solicitud en el cuerpo del mensaje. +{% capture english-rules %} -### ruta +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. -Parte de un URL que identifica un recurso. Por ejemplo, en `http://foo.com/products/id`, "/products/id" es la ruta. +{% endcapture %} -### solicitud +{% include admonitions/note.html content=english-rules %} -Una solicitud HTTP. Un cliente envía un mensaje de solicitud HTTP a un servidor, que devuelve una respuesta. La solicitud debe utilizar uno de los [métodos de solicitud](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) como, por ejemplo, GET, POST, etc. +### request + +Una solicitud HTTP. Un cliente envía un mensaje de solicitud HTTP a un servidor, que devuelve una respuesta. La solicitud debe utilizar uno de los [métodos de solicitud](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) como, por ejemplo, GET, POST, etc. + +### response + +An HTTP response. A server returns an HTTP response message to the client. La respuesta contiene información de estado de finalización sobre la solicitud y también puede contener contenido de la solicitud en el cuerpo del mensaje. + +### route + +Parte de un URL que identifica un recurso. For example, in `http://foo.com/products/id`, "/products/id" is the route. + +### router + +Consulte [direccionador](/{{ page.lang }}/4x/api.html#router) en la referencia de API. diff --git a/es/resources/middleware.md b/es/resources/middleware.md old mode 100755 new mode 100644 index b9635cd84b..e7565ea7c4 --- a/es/resources/middleware.md +++ b/es/resources/middleware.md @@ -1,65 +1,44 @@ --- -layout: page +layout: middleware title: Middleware de Express +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. menu: resources -lang: es -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. +lang: en +redirect_from: " " +module: mw-home --- -# Middleware de terceros +## Middleware de Express Estos son algunos módulos de middleware de Express: - - [body-parser](https://github.com/expressjs/body-parser): anteriormente `express.bodyParser`, `json` y `urlencoded`. - Vea también: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression): anteriormente `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): módulos de middleware de Connect/Express para el servicio óptimo de imágenes. Cambia las imágenes a `.webp` o `.jxr`, si es posible. - - [connect-timeout](https://github.com/expressjs/timeout): anteriormente `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser): anteriormente `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session): anteriormente `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler): anteriormente `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug): herramienta de desarrollo discreta que añade a la aplicación un separador con información sobre las variables de plantilla (locals), la sesión actual, datos de solicitud útiles, etc. - - [express-partial-response](https://github.com/nemtsov/express-partial-response): módulo de middleware de Express middleware para filtrar partes de las respuestas JSON basándose en la serie de consulta `fields`; utiliza la respuesta parcial de la API de Google. - - [express-session](https://github.com/expressjs/session): anteriormente `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): módulo de middleware de Express para utilizar una CDN (Red de entrega de contenido) para los activos estáticos, con soporte de varios hosts (por ejemplo, cdn1.host.com, cdn2.host.com). - - [express-slash](https://github.com/ericf/express-slash): módulo de middleware de Express para aquellos que son estrictos sobre las barras inclinadas finales. - - [express-stormpath](https://github.com/stormpath/stormpath-express): módulo de middleware de Express para el almacenamiento de usuario, la autenticación, la autorización, SSO y la seguridad de datos. - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): módulo de middleware para redirigir las solicitudes que contienen mayúsculas a un formato en minúsculas canónico. - - [helmet](https://github.com/helmetjs/helmet): módulo para ayudar a proteger las aplicaciones estableciendo varias cabeceras HTTP. - - [join-io](https://github.com/coderaiser/join-io "join-io"): módulo para unir archivos sobre la marcha para reducir el recuento de solicitudes. - - [method-override](https://github.com/expressjs/method-override): anteriormente `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan): anteriormente `logger` - - [passport](https://github.com/jaredhanson/passport): módulo de middleware de Express para la autenticación. - - [response-time](https://github.com/expressjs/response-time): anteriormente `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon): anteriormente `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index): anteriormente `express.directory` - - [serve-static](https://github.com/expressjs/serve-static): módulo para el servicio de contenido estático. - - [static-expiry](https://github.com/paulwalker/connect-static-expiry): cabeceras de almacenamiento en memoria caché o URL de firma digital para activos estáticos, incluido el soporte para uno o varios dominios externos. - - [vhost](https://github.com/expressjs/vhost): anteriormente `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers): módulo de middleware de Express que proporciona métodos de ayudante comunes a las vistas. - - [sriracha-admin](https://github.com/hdngr/siracha): módulo de middleware de Express que genera dinámicamente un sitio de administración para Mongoose. +| [express-slash](https://github.com/ericf/express-slash): módulo de middleware de Express para aquellos que son estrictos sobre las barras inclinadas finales. | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Algunos módulos de middleware incluidos previamente con Connect ya no están soportados por el equipo de Connect/Express. Estos módulos se han sustituido por un módulo alternativo o deben reemplazarse por un módulo mejor. Utilice una de las siguientes alternativas: +## Para ver más módulo de middleware, consulte: - - express.cookieParser - - [cookies](https://github.com/jed/cookies) y [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -Para ver más módulo de middleware, consulte: +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| [express-slash](https://github.com/ericf/express-slash): módulo de middleware de Express para aquellos que son estrictos sobre las barras inclinadas finales. | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet): módulo para ayudar a proteger las aplicaciones estableciendo varias cabeceras HTTP. | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport): módulo de middleware de Express para la autenticación. | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/es/resources/middleware/body-parser.md b/es/resources/middleware/body-parser.md new file mode 100644 index 0000000000..d188f90ee8 --- /dev/null +++ b/es/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: en +redirect_from: " " +module: body-parser +--- diff --git a/es/resources/middleware/compression.md b/es/resources/middleware/compression.md new file mode 100644 index 0000000000..05f540b0d0 --- /dev/null +++ b/es/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: en +redirect_from: " " +module: compression +--- diff --git a/es/resources/middleware/connect-rid.md b/es/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..64bc400309 --- /dev/null +++ b/es/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: en +redirect_from: " " +module: connect-rid +--- diff --git a/es/resources/middleware/cookie-parser.md b/es/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..a75855fc91 --- /dev/null +++ b/es/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: en +redirect_from: " " +module: cookie-parser +--- diff --git a/es/resources/middleware/cookie-session.md b/es/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..8b68fa1911 --- /dev/null +++ b/es/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: en +redirect_from: " " +module: cookie-session +--- diff --git a/es/resources/middleware/cors.md b/es/resources/middleware/cors.md new file mode 100644 index 0000000000..be266ac8d4 --- /dev/null +++ b/es/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: en +redirect_from: " " +module: cors +--- diff --git a/es/resources/middleware/errorhandler.md b/es/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..b7da1e5f68 --- /dev/null +++ b/es/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: en +redirect_from: " " +module: errorhandler +--- diff --git a/es/resources/middleware/method-override.md b/es/resources/middleware/method-override.md new file mode 100644 index 0000000000..5938f1de7f --- /dev/null +++ b/es/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: en +redirect_from: " " +module: method-override +--- diff --git a/es/resources/middleware/morgan.md b/es/resources/middleware/morgan.md new file mode 100644 index 0000000000..7d09c8ba37 --- /dev/null +++ b/es/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: en +redirect_from: " " +module: morgan +--- diff --git a/es/resources/middleware/multer.md b/es/resources/middleware/multer.md new file mode 100644 index 0000000000..f837cafdb8 --- /dev/null +++ b/es/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: en +redirect_from: " " +module: multer +--- diff --git a/es/resources/middleware/response-time.md b/es/resources/middleware/response-time.md new file mode 100644 index 0000000000..ae48e3f005 --- /dev/null +++ b/es/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: en +redirect_from: " " +module: response-time +--- diff --git a/es/resources/middleware/serve-favicon.md b/es/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..57f5a450aa --- /dev/null +++ b/es/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: en +redirect_from: " " +module: serve-favicon +--- diff --git a/es/resources/middleware/serve-index.md b/es/resources/middleware/serve-index.md new file mode 100644 index 0000000000..a92b46dc95 --- /dev/null +++ b/es/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: en +redirect_from: " " +module: serve-index +--- diff --git a/es/resources/middleware/serve-static.md b/es/resources/middleware/serve-static.md new file mode 100644 index 0000000000..b17737af5f --- /dev/null +++ b/es/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: en +redirect_from: " " +module: serve-static +--- diff --git a/es/resources/middleware/session.md b/es/resources/middleware/session.md new file mode 100644 index 0000000000..05ec6133ac --- /dev/null +++ b/es/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: en +redirect_from: " " +module: session +--- diff --git a/es/resources/middleware/timeout.md b/es/resources/middleware/timeout.md new file mode 100644 index 0000000000..0aa926a7f3 --- /dev/null +++ b/es/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: en +redirect_from: " " +module: timeout +--- diff --git a/es/resources/middleware/vhost.md b/es/resources/middleware/vhost.md new file mode 100644 index 0000000000..08860472ec --- /dev/null +++ b/es/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: en +redirect_from: " " +module: vhost +--- diff --git a/es/resources/utils.md b/es/resources/utils.md new file mode 100644 index 0000000000..18f7c1aaf8 --- /dev/null +++ b/es/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: en +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| 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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/es/starter/basic-routing.md b/es/starter/basic-routing.md old mode 100755 new mode 100644 index 56c2c38aa3..f2baa49a65 --- a/es/starter/basic-routing.md +++ b/es/starter/basic-routing.md @@ -1,27 +1,27 @@ --- layout: page title: Direccionamiento básico de Express +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. menu: starter -lang: es -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. +lang: en +redirect_from: " " --- # Direccionamiento básico -El *direccionamiento* hace referencia a la determinación de cómo responde una aplicación a una solicitud de cliente en un determinado punto final, que es un URI (o una vía de acceso) y un método de solicitud HTTP específico (GET, POST, etc.). +El _direccionamiento_ hace referencia a la determinación de cómo responde una aplicación a una solicitud de cliente en un determinado punto final, que es un URI (o una vía de acceso) y un método de solicitud HTTP específico (GET, POST, etc.). Cada ruta puede tener una o varias funciones de manejador, que se excluyen cuando se correlaciona la ruta. -La definición de ruta tiene la siguiente estructura: +Route definition takes the following structure: + ```js app.METHOD(PATH, HANDLER) ``` -Donde: +Where: -- `app` es una instancia de `express`. +- `app` is an instance of `express`. - `METHOD` es un [método de solicitud HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol). - `PATH` es una vía de acceso en el servidor. - `HANDLER` es la función que se ejecuta cuando se correlaciona la ruta. @@ -65,3 +65,5 @@ app.delete('/user', (req, res) => { ``` Para obtener más detalles sobre el direccionamiento, consulte la [guía de direccionamiento](/{{ page.lang }}/guide/routing.html). + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/es/starter/examples.md b/es/starter/examples.md new file mode 100644 index 0000000000..0df4f7d85a --- /dev/null +++ b/es/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: en +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/es/starter/faq.md b/es/starter/faq.md old mode 100755 new mode 100644 index a46c4ebbae..e8e15d9199 --- a/es/starter/faq.md +++ b/es/starter/faq.md @@ -1,28 +1,27 @@ --- layout: page title: Preguntas más frecuentes sobre Express +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter -lang: es -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +lang: en +redirect_from: " " --- # Preguntas más frecuentes -## ¿Cómo debo estructurar mi aplicación? +## How should I structure my application? -No hay una respuesta definitiva a esta pregunta. La respuesta depende de la escala de la aplicación y del equipo implicado. Para ser lo más flexible posible, Express no realiza suposiciones en cuanto a la estructura. +There is no definitive answer to this question. La respuesta depende de la escala de la aplicación y del equipo implicado. Para ser lo más flexible posible, Express no realiza suposiciones en cuanto a la estructura. Las rutas y otra lógica específica de la aplicación puede residir en tantos archivos como desee, con la estructura de directorios que prefiera. Vea los siguientes ejemplos como inspiración: -* [Listas de rutas](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [Correlación de rutas](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [Controladores de estilo MVC](https://github.com/expressjs/express/tree/master/examples/mvc) +- [Listas de rutas](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [Correlación de rutas](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [Controladores de estilo MVC](https://github.com/expressjs/express/tree/master/examples/mvc) Asimismo, hay extensiones de terceros para Express, que simplifican algunos de estos patrones: -* [express-resource](https://github.com/expressjs/express-resource) +- [express-resource](https://github.com/expressjs/express-resource) ## ¿Cómo debo definir los modelos? @@ -32,25 +31,29 @@ Consulte [LoopBack](http://loopback.io) para ver una infraestructura basada en E ## ¿Cómo puedo autenticar los usuarios? -La autenticación es otra área rígida en la que no entra Express. Puede utilizar el esquema de autenticación que desee. +La autenticación es otra área rígida en la que no entra Express. Puede utilizar el esquema de autenticación que desee. Para ver un esquema simple de nombre de usuario/contraseña, consulte [este ejemplo](https://github.com/expressjs/express/tree/master/examples/auth). - ## ¿A qué motor de plantilla da soporte Express? Express da soporte a cualquier motor de plantilla que cumpla la firma `(path, locals, callback)`. Para normalizar las interfaces de motor de plantilla y el almacenamiento en memoria caché, consulte el proyecto [consolidate.js](https://github.com/visionmedia/consolidate.js) para ver el soporte. Otros motores de plantilla que no aparezcan en la lista también pueden dar soporte a la firma de Express. -## ¿Cómo puedo manejar las respuestas 404? +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). + +## How do I handle 404 responses? En Express, las respuestas 404 no son el resultado de un error, por lo que el middleware de manejador de errores no las capturará. Este comportamiento se debe a que una respuesta 404 simplemente indica la ausencia de trabajo adicional pendiente; es decir, Express ha ejecutado todas las rutas y funciones de middleware, y ha comprobado que ninguna de ellas responde. Lo único que debe hacer es añadir una función de middleware al final de la pila (debajo de las demás funciones) para manejar una respuesta 404: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## ¿Cómo configuro un manejador de errores? El middleware de manejo de errores se define de la misma forma que otro middleware, excepto con cuatro argumentos en lugar de tres; específicamente con la firma `(err, req, res, next)`: @@ -69,3 +72,10 @@ Para obtener más información, consulte [Manejo de errores](/{{ page.lang }}/gu De ninguna manera. No es necesario "representar" HTML con la función `res.render()`. Si tiene un archivo específico, utilice la función `res.sendFile()`. Para el servicio de muchos activos desde un directorio, utilice la función de middleware `express.static()`. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/es/starter/generator.md b/es/starter/generator.md old mode 100755 new mode 100644 index d6fb3afd0b..85dffda2c9 --- a/es/starter/generator.md +++ b/es/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Generador de aplicaciones Express +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter -lang: es -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +lang: en +redirect_from: " " --- # Generador de aplicaciones Express Utilice la herramienta de generador de aplicaciones, `express`, para crear rápidamente un esqueleto de aplicación. -Instale `express` con el siguiente mandato: +You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash -$ npm install express-generator -g +$ npx express-generator +``` + +For earlier Node versions, install the application generator as a global npm package and then launch it: + +```bash +$ npm install -g express-generator +$ express ``` Muestre las opciones de mandato con la opción `-h`: @@ -22,7 +29,7 @@ Muestre las opciones de mandato con la opción `-h`: ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,8 +40,8 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` @@ -82,9 +89,15 @@ En Windows, utilice este mandato: > set DEBUG=myapp:* & npm start ``` +On Windows PowerShell, use this command: + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + A continuación, cargue `http://localhost:3000/` en el navegador para acceder a la aplicación. -La aplicación generada tiene la siguiente estructura de directorios: +The generated app has the following directory structure: ```bash . @@ -111,3 +124,5 @@ La aplicación generada tiene la siguiente estructura de directorios:
    La estructura de la aplicación creada por el generador es sólo una de las muchas formas de estructurar las aplicaciones Express. Puede utilizar esta estructura o modificarla según sus necesidades.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/es/starter/hello-world.md b/es/starter/hello-world.md old mode 100755 new mode 100644 index 8786f259b1..6df6cf6912 --- a/es/starter/hello-world.md +++ b/es/starter/hello-world.md @@ -1,10 +1,10 @@ --- layout: page title: Ejemplo "Hello World" de Express +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter -lang: es -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +lang: en +redirect_from: " " --- # Ejemplo Hello world @@ -13,10 +13,6 @@ description: Get started with Express.js by building a simple 'Hello World' appl Esta es básicamente la aplicación Express más sencilla que puede crear. Es una aplicación de archivo simple — *no* lo que obtendrá si utiliza el [generador de Express](/{{ page.lang }}/starter/generator.html), que crea el andamiaje para una aplicación completa con varios archivos JavaScript, plantillas Jade y subdirectorios para distintos propósitos.
    -En primer lugar, cree un directorio denominado `myapp`, cámbielo y ejecute `npm init`. A continuación, instale `express` como una dependencia, según se describe en la [guía de instalación](/{{ page.lang }}/starter/installing.html). - -En el directorio `myapp`, cree un archivo denominado `app.js` y añada el código siguiente: - ```js const express = require('express') const app = express() @@ -31,7 +27,13 @@ app.listen(port, () => { }) ``` -La aplicación inicia un servidor y escucha las conexiones en el puerto 3000. La aplicación responde con "Hello World!" para las solicitudes al URL raíz (`/`) o a la *ruta* raíz. Para cada vía de acceso diferente, responderá con un error **404 Not Found**. +La aplicación inicia un servidor y escucha las conexiones en el puerto 3000. La aplicación responde con "Hello World!" para las solicitudes al URL raíz (`/`) o a la _ruta_ raíz. Para cada vía de acceso diferente, responderá con un error **404 Not Found**. + +### Running Locally + +En primer lugar, cree un directorio denominado `myapp`, cámbielo y ejecute `npm init`. A continuación, instale `express` como una dependencia, según se describe en la [guía de instalación](/{{ page.lang }}/starter/installing.html). + +En el directorio `myapp`, cree un archivo denominado `app.js` y añada el código siguiente:
    `req` (solicitud) y `res` (respuesta) son exactamente los mismos objetos que proporciona Node, por lo que puede invocar `req.pipe()`, `req.on('data', callback)` y cualquier otro objeto que invocaría sin estar Express implicado. @@ -45,3 +47,4 @@ $ node app.js A continuación, cargue [http://localhost:3000/](http://localhost:3000/) en un navegador para ver la salida. +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/es/starter/installing.md b/es/starter/installing.md old mode 100755 new mode 100644 index 43ea990dbb..eb2ca045ae --- a/es/starter/installing.md +++ b/es/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: Instalación de Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter -lang: es -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +lang: en +redirect_from: " " --- # Instalación Suponiendo que ya ha instalado [Node.js](https://nodejs.org/), cree un directorio para que contenga la aplicación y conviértalo en el directorio de trabajo. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -26,25 +29,26 @@ $ npm init Este mandato solicita varios elementos como, por ejemplo, el nombre y la versión de la aplicación. Por ahora, sólo tiene que pulsar INTRO para aceptar los valores predeterminados para la mayoría de ellos, con la siguiente excepción: -```bash +``` entry point: (index.js) ``` Especifique `app.js` o el nombre que desee para el archivo principal. Si desea que sea `index.js`, pulse INTRO para aceptar el nombre de archivo predeterminado recomendado. -A continuación, instale Express en el directorio `myapp` y guárdelo en la lista de dependencias. Por ejemplo: +A continuación, instale Express en el directorio `myapp` y guárdelo en la lista de dependencias. For example: ```bash -$ npm install express --save +$ npm install express ``` Para instalar Express temporalmente y no añadirlo a la lista de dependencias, omita la opción `--save`: ```bash -$ npm install express +$ npm install express --no-save ```
    -Los módulos de Node que se instalan con la opción `--save` se añaden a la lista `dependencies` en el archivo `package.json`. -Posteriormente, si ejecuta `npm install` en el directorio `app`, los módulos se instalarán automáticamente en la lista de dependencias. +Los módulos de Node que se instalan con la opción `--save` se añaden a la lista `dependencies` en el archivo `package.json`. Posteriormente, si ejecuta `npm install` en el directorio `app`, los módulos se instalarán automáticamente en la lista de dependencias.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/es/starter/static-files.md b/es/starter/static-files.md old mode 100755 new mode 100644 index 45ed04083a..827dbc6c76 --- a/es/starter/static-files.md +++ b/es/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: Servicio de archivos estáticos en Express +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter -lang: es -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +lang: en +redirect_from: " " --- # Servicio de archivos estáticos en Express Para el servicio de archivos estáticos como, por ejemplo, imágenes, archivos CSS y archivos JavaScript, utilice la función de middleware incorporado `express.static` de Express. -Pase el nombre del directorio que contiene los activos estáticos a la función de middleware `express.static` para empezar directamente el servicio de los archivos. Por ejemplo, utilice el siguiente código para el servicio de imágenes, archivos CSS y archivos JavaScript en un directorio denominado `public`: +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](/{{page.lang}}/4x/api.html#express.static). + +Por ejemplo, utilice el siguiente código para el servicio de imágenes, archivos CSS y archivos JavaScript en un directorio denominado `public`: ```js app.use(express.static('public')) @@ -40,6 +49,11 @@ app.use(express.static('files')) Express busca los archivos en el orden en el que se definen los directorios estáticos con la función de middleware `express.static`. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + Para crear un prefijo de vía de acceso virtual (donde la vía de acceso no existe realmente en el sistema de archivos) para los archivos a los que da servicio la función `express.static`, [especifique una vía de acceso de montaje](/{{ page.lang }}/4x/api.html#app.use) para el directorio estático, como se muestra a continuación: ```js @@ -62,3 +76,7 @@ No obstante, la vía de acceso que proporciona a la función `express.static` es const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/es/support/index.md b/es/support/index.md index 206af52617..018767928f 100644 --- a/es/support/index.md +++ b/es/support/index.md @@ -1,8 +1,9 @@ --- layout: page 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. menu: support -lang: es +lang: en --- # Version Support @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/fr/3x/api.md b/fr/3x/api.md old mode 100755 new mode 100644 index f9bd651fcf..46084808cd --- a/fr/3x/api.md +++ b/fr/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - Référence de l'API +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: fr -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x N'EST PLUS PRIS EN CHARGE** - Les problèmes de performances et de sécurité connus et inconnus n'ont pas été traités depuis la dernière mise à jour (1er août 2015). Il est fortement recommandé d'utiliser la dernière version d'Express. -
    - -

    API 3.x

    +Les problèmes de performances et de sécurité connus et inconnus n'ont pas été traités depuis la dernière mise à jour (1er août 2015). Il est fortement recommandé d'utiliser la dernière version d'Express. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
    - - {% include api/en/3x/res.md %} +

    API 3.x

    - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
    diff --git a/fr/4x/api.md b/fr/4x/api.md old mode 100755 new mode 100644 index 89327e1a51..0ce14005a6 --- a/fr/4x/api.md +++ b/fr/4x/api.md @@ -2,27 +2,26 @@ layout: api version: 4x title: Express 4.x - Référence de l'API +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: fr -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +

    API 4.x

    - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
    diff --git a/fr/5x/api.md b/fr/5x/api.md index 57cf546fbe..443fda6a67 100644 --- a/fr/5x/api.md +++ b/fr/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - Référence de l'API +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: fr -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/fr/advanced/best-practice-performance.md b/fr/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 90ed247ce7..56fd3b1536 --- a/fr/advanced/best-practice-performance.md +++ b/fr/advanced/best-practice-performance.md @@ -1,35 +1,39 @@ --- layout: page -title: Meilleures pratiques en termes de performances pour l'utilisation d'Express - en production +title: Meilleures pratiques en termes de performances pour l'utilisation d'Express en production +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: fr -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # Meilleures pratiques en production : performances et fiabilité -## Présentation - Cet article traite des meilleures pratiques en termes de performances et de fiabilité pour les applications Express déployées en production. La présente rubrique s'inscrit clairement dans le concept "devops", qui couvre à la fois le développement traditionnel et l'exploitation. Ainsi, les informations se divisent en deux parties : -* [A faire dans votre code](#code) (partie développement, "dev"). -* [A faire dans votre environnement/configuration](#env) (partie exploitation, "ops"). - - +- Things to do in your code (the dev part): + - Utiliser le middleware pour exploiter les fichiers statiques + - [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) + - [Do logging correctly](#do-logging-correctly) + - Traiter correctement les exceptions +- [A faire dans votre environnement/configuration](#env) (partie exploitation, "ops"). + - Définir NODE_ENV sur "production" + - Vérifier que votre application redémarre automatiquement + - Exécuter votre application dans un cluster + - [Cache request results](#cache-request-results) + - Utilisation de StrongLoop PM avec un équilibreur de charge Nginx + - Encore mieux, utilisez un proxy inverse pour exploiter les fichiers statiques ; pour plus d'informations, voir [Utiliser un proxy inverse](#proxy). ## A faire dans votre code Les actions suivantes peuvent être réalisées dans votre code afin d'améliorer les performances de votre application : -* Utiliser la compression gzip -* Ne pas utiliser les fonctions synchrones -* Utiliser le middleware pour exploiter les fichiers statiques -* Procéder à une journalisation correcte -* Traiter correctement les exceptions +- Utiliser le middleware pour exploiter les fichiers statiques +- [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) +- [Do logging correctly](#do-logging-correctly) +- Traiter correctement les exceptions ### Utiliser la compression gzip @@ -39,6 +43,7 @@ La compression Gzip peut considérablement réduire la taille du corps de répon const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` @@ -50,19 +55,11 @@ Les fonctions et les méthodes synchrones ralentissent le processus d'exécution Bien que Node et plusieurs modules mettent à disposition les versions synchrone et asynchrone de leurs fonctions, utilisez toujours la version asynchrone en production. L'utilisation d'une fonction synchrone n'est justifiée que lors du démarrage initial. -Si vous utilisez Node.js 4.0+ ou io.js 2.1.0+, vous pouvez utiliser l'option de ligne de commande `--trace-sync-io` pour imprimer un avertissement et une trace de pile chaque fois que votre application utilise une API synchrone. Bien entendu vous n'utiliserez pas réellement cette option en production, mais plutôt pour vérifier que votre code est prêt pour la phase production. Pour plus d'informations, voir [Weekly update for io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0). - -### Utiliser le middleware pour exploiter les fichiers statiques - -En développement, vous pouvez utiliser [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) pour exploiter les fichiers statiques. Ne l'utilisez toutefois pas en production, car cette fonction doit lire le système de fichiers pour chaque demande de fichier ; elle se heurterait à des temps d'attente importants qui affecteraient les performances globales de l'application. Notez que `res.sendFile()` n'est *pas* implémentée avec l'appel système [sendfile](http://linux.die.net/man/2/sendfile), qui la rendrait beaucoup plus efficace. - -Utilisez plutôt le middleware [serve-static](https://www.npmjs.com/package/serve-static) (ou tout middleware équivalent), qui est optimisé pour l'utilisation des fichiers dans les applications Express. - -Encore mieux, utilisez un proxy inverse pour exploiter les fichiers statiques ; pour plus d'informations, voir [Utiliser un proxy inverse](#proxy). +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. Bien entendu vous n'utiliserez pas réellement cette option en production, mais plutôt pour vérifier que votre code est prêt pour la phase production. Pour plus d'informations, voir [Weekly update for io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0). ### Procéder à une journalisation correcte -En règle générale, vous utilisez la journalisation à partir de votre application à deux fins : le débogage et la journalisation de l'activité de votre application (principalement tout le reste). L'utilisation de `console.log()` ou de `console.err()` pour imprimer des messages de journal sur le terminal est une pratique courante en développement. Cependant, [ces fonctions sont synchrones](https://nodejs.org/api/console.html#console_console_1) lorsque la destination est un terminal ou un fichier ; elles ne conviennent donc pas en production, à moins que vous ne dirigiez la sortie vers un autre programme. +En règle générale, vous utilisez la journalisation à partir de votre application à deux fins : le débogage et la journalisation de l'activité de votre application (principalement tout le reste). L'utilisation de `console.log()` ou de `console.err()` pour imprimer des messages de journal sur le terminal est une pratique courante en développement. 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 @@ -70,9 +67,7 @@ Si vous utilisez la journalisation à des fins de débogage, utilisez un module #### Pour journaliser l'activité de votre application -Si vous journalisez l'activité de votre application (par exemple, pour suivre le trafic ou les appels API), utilisez une bibliothèque de journalisation telle que [Winston](https://www.npmjs.com/package/winston) ou [Bunyan](https://www.npmjs.com/package/bunyan) plutôt que d'utiliser `console.log()`. Pour obtenir une comparaison détaillée de ces deux bibliothèques, consultez l'article StrongLoop intitulé [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/). - - +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. ### Traiter correctement les exceptions @@ -80,32 +75,19 @@ Les applications Node plantent lorsqu'elles tombent sur une exception non interc Pour vérifier que vous traitez toutes les exceptions, procédez comme suit : -* [Utiliser try-catch](#try-catch) -* [Utiliser des promesses](#promises) +- [Utiliser try-catch](#try-catch) +- [Utiliser des promesses](#promises) Avant de s'immerger dans les rubriques qui suivent, il est conseillé de posséder des connaissances de base concernant le traitement des erreurs Node/Express, à savoir l'utilisation des rappels "error-first" et la propagation des erreurs dans le middleware. Node utilise la convention de "rappel error-first" pour renvoyer les erreurs issues des fonctions asynchrones, dans laquelle le premier paramètre de la fonction callback est l'objet error, suivi par les données de résultat dans les paramètres suivants. Pour n'indiquer aucune erreur, indiquez null comme premier paramètre. La fonction de rappel doit suivre la convention de rappel "error-first" de sorte à traiter l'erreur de manière significative. Dans Express, la meilleure pratique consiste à utiliser la fonction next() pour propager les erreurs via la chaîne du middleware. Pour plus d'informations sur les bases du traitement des erreurs, voir : -* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (blogue StrongLoop) - -#### A ne pas faire - -Vous ne devriez *pas* écouter l'événement `uncaughtException`, émis lorsqu'une exception remonte vers la boucle d'événements. L'ajout d'un programme d'écoute d'événement pour `uncaughtException` va modifier le comportement par défaut du processus qui rencontre une exception ; le processus va continuer à s'exécuter malgré l'exception. Cela pourrait être un bon moyen d'empêcher votre application de planter, mais continuer à exécuter l'application après une exception non interceptée est une pratique dangereuse qui n'est pas recommandée, étant donné que l'état du processus devient peu fiable et imprévisible. - -De plus, l'utilisation d'`uncaughtException` est officiellement reconnue comme étant [rudimentaire](https://nodejs.org/api/process.html#process_event_uncaughtexception) et il a été [proposé](https://github.com/nodejs/node-v0.x-archive/issues/2582) de le supprimer. Ecouter `uncaughtException` n'est qu'une mauvaise idée. Voilà pourquoi nous recommandons d'utiliser plusieurs processus et superviseurs à la place : faire planter son application et la redémarrer est souvent plus sûr que de la restaurer après une erreur. - -L'utilisation de [domain](https://nodejs.org/api/domain.html) n'est également pas recommandée. Ce module obsolète ne résout globalement pas le problème. - - +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### Utiliser try-catch Try-catch est un élément de langage JavaScript que vous pouvez utiliser pour intercepter les exceptions dans le code synchrone. Utilisez try-catch pour traiter les erreurs d'analyse JSON, comme indiqué ci-dessous, par exemple. -Utilisez un outil tel que [JSHint](http://jshint.com/) ou [JSLint](http://www.jslint.com/) pour vous aider à identifier les exceptions implicites comme les [erreurs de référence dans les variables non définies](http://www.jshint.com/docs/options/#undef). - Voici un exemple d'utilisation de try-catch pour traiter une exception potentielle de plantage de processus. Cette fonction middleware accepte un paramètre de zone de requête nommé "params" qui est un objet JSON. @@ -126,85 +108,70 @@ app.get('/search', (req, res) => { Toutefois, try-catch ne fonctionne que dans le code synchrone. Etant donné que la plateforme Node est principalement asynchrone (en particulier dans un environnement de production), try-catch n'interceptera pas beaucoup d'exceptions. - - #### Utiliser des promesses -Les promesses vont traiter n'importe quelle exception (explicite et implicite) dans les blocs de code asynchrone qui utilisent `then()`. Contentez-vous d'ajouter `.catch(next)` à la fin des chaînes de promesse. Par exemple : +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -Toutes les erreurs asynchrones et synchrones sont à présent propagées vers le middleware de traitement des erreurs. - -Observez toutefois les deux avertissements suivants : - -1. L'intégralité de votre code asynchrone doit renvoyer des promesses (à l'exception des émetteurs). Si une bibliothèque spécifique ne renvoie pas de promesses, convertissez l'objet de base à l'aide d'une fonction d'aide telle que [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html). -2. Les émetteurs d'événements (comme les flux) peuvent toujours générer des exceptions non interceptées. Veillez donc à traiter l'événement d'erreur de manière appropriée ; par exemple : +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -Pour plus d'informations sur le traitement des erreurs à l'aide de promesses, voir : +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. -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +#### A ne pas faire - +Vous ne devriez _pas_ écouter l'événement `uncaughtException`, émis lorsqu'une exception remonte vers la boucle d'événements. L'ajout d'un programme d'écoute d'événement pour `uncaughtException` va modifier le comportement par défaut du processus qui rencontre une exception ; le processus va continuer à s'exécuter malgré l'exception. Cela pourrait être un bon moyen d'empêcher votre application de planter, mais continuer à exécuter l'application après une exception non interceptée est une pratique dangereuse qui n'est pas recommandée, étant donné que l'état du processus devient peu fiable et imprévisible. -## A faire dans votre environnement/configuration +De plus, l'utilisation d'`uncaughtException` est officiellement reconnue comme étant [rudimentaire](https://nodejs.org/api/process.html#process_event_uncaughtexception) et il a été [proposé](https://github.com/nodejs/node-v0.x-archive/issues/2582) de le supprimer. Ecouter `uncaughtException` n'est qu'une mauvaise idée. Voilà pourquoi nous recommandons d'utiliser plusieurs processus et superviseurs à la place : faire planter son application et la redémarrer est souvent plus sûr que de la restaurer après une erreur. + +L'utilisation de [domain](https://nodejs.org/api/domain.html) n'est également pas recommandée. Ce module obsolète ne résout globalement pas le problème. + +## Things to do in your environment / setup + +{#in-environment} Les actions suivantes peuvent être réalisées dans votre environnement système afin d'améliorer les performances de votre application : -* Définir NODE_ENV sur "production" -* Vérifier que votre application redémarre automatiquement -* Exécuter votre application dans un cluster -* Mettre en cache les résultats d'une demande -* Utiliser un équilibreur de charge -* Utiliser un proxy inverse +- Définir NODE_ENV sur "production" +- Vérifier que votre application redémarre automatiquement +- Exécuter votre application dans un cluster +- [Cache request results](#cache-request-results) +- Utilisation de StrongLoop PM avec un équilibreur de charge Nginx +- Encore mieux, utilisez un proxy inverse pour exploiter les fichiers statiques ; pour plus d'informations, voir [Utiliser un proxy inverse](#proxy). ### Définir NODE_ENV sur "production" -La variable d'environnement NODE_ENV spécifie l'environnement dans lequel une application s'exécute (en règle générale, développement ou production). Le moyen le plus simple d'améliorer vos performances consiste à définir NODE_ENV sur "production." +La variable d'environnement NODE_ENV spécifie l'environnement dans lequel une application s'exécute (en règle générale, développement ou production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. En définissant NODE_ENV sur "production", Express : -* Met en cache les modèles d'affichage. -* Met en cache les fichiers CSS générés à partir d'extensions CSS. -* Génère moins de messages d'erreur prolixes. +- Met en cache les modèles d'affichage. +- Met en cache les fichiers CSS générés à partir d'extensions CSS. +- Génère moins de messages d'erreur prolixes. -[Les tests indiquent](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) que ce simple paramétrage peut multiplier les performances d'application par trois ! +[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! Si vous avez besoin d'écrire du code spécifique à un environnement, vous pouvez vérifier la valeur de NODE_ENV avec `process.env.NODE_ENV`. Sachez que la vérification de la valeur de n'importe quelle variable d'environnement pénalise les performances et devrait donc être effectuée avec modération. -En développement, vous définissez généralement les variables d'environnement dans votre shell interactif, à l'aide de `export` ou de votre fichier `.bash_profile` par exemple. Il n'est toutefois pas conseillé de le faire sur un serveur de production ; utilisez plutôt le système init de votre système d'exploitation (systemd ou Upstart). La section qui suit fournit des détails sur l'utilisation de votre système init en général, mais la définition de NODE_ENV est tellement importante pour les performances (et facile à réaliser), qu'elle est mise en évidence ici. - -Avec Upstart, utilisez le mot clé `env` dans votre fichier de travail. Par exemple : - -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` - -Pour plus d'informations, voir [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables). +En développement, vous définissez généralement les variables d'environnement dans votre shell interactif, à l'aide de `export` ou de votre fichier `.bash_profile` par exemple. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). La section qui suit fournit des détails sur l'utilisation de votre système init en général, mais la définition de NODE_ENV est tellement importante pour les performances (et facile à réaliser), qu'elle est mise en évidence ici. Avec systemd, utilisez la directive `Environment` dans votre fichier d'unité. Par exemple : @@ -213,16 +180,14 @@ Avec systemd, utilisez la directive `Environment` dans votre fichier d'unité. P Environment=NODE_ENV=production ``` -Pour plus d'informations, voir [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html). - -Si vous utilisez StrongLoop Process Manager, vous pouvez également [définir la variable d'environnement lorsque vous installez StrongLoop PM en tant que service](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables). +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Vérifier que votre application redémarre automatiquement En production, vous ne souhaitez jamais que votre application soit déconnectée. Vous devez donc veiller à ce qu'elle redémarre si elle plante et si le serveur plante. Même si vous espérez que cela n'arrive pas, vous devez en réalité considérer ces deux éventualités en : -* Utilisant un gestionnaire de processus pour redémarrer l'application (et Node) lorsqu'elle plante. -* Utilisant le système init fourni par votre système d'exploitation pour redémarrer le gestionnaire de processus lorsque le système d'exploitation plante. Vous pouvez également utiliser le système init sans gestionnaire de processus. +- Utilisant un gestionnaire de processus pour redémarrer l'application (et Node) lorsqu'elle plante. +- Utilisant le système init fourni par votre système d'exploitation pour redémarrer le gestionnaire de processus lorsque le système d'exploitation plante. Vous pouvez également utiliser le système init sans gestionnaire de processus. Les applications Node plantent si elles tombent sur une exception non interceptée. Avant toute chose, vérifiez que votre application est correctement testée et qu'elle traite toutes les exceptions (voir [Traiter correctement les exceptions](#exceptions) pour plus de détails). En cas d'échec, mettez en place un mécanisme qui garantit que si et lorsque votre application plante, elle redémarre automatiquement. @@ -232,54 +197,35 @@ En développement, vous avez simplement démarré votre application à partir de En plus de redémarrer votre application lorsqu'elle plante, un gestionnaire de processus peut vous permettre : -* De vous informer sur les performances d'exécution et la consommation des ressources. -* De modifier les paramètres de manière dynamique afin d'améliorer les performances. -* De contrôler la mise en cluster (StrongLoop PM et pm2). +- De vous informer sur les performances d'exécution et la consommation des ressources. +- De modifier les paramètres de manière dynamique afin d'améliorer les performances. +- Control clustering (pm2). -Les gestionnaires de processus les plus populaires pour Node sont les suivants : - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -Pour obtenir une comparaison détaillée de ces trois gestionnaires de processus, voir [http://strong-pm.io/compare/](http://strong-pm.io/compare/). - -L'utilisation de l'un de ces trois gestionnaires de processus suffira à garder votre application active, même si elle plantera de temps en temps. - -StrongLoop PM possède un grand nombre de fonctionnalités qui ciblent en particulier le déploiement en production. Vous pouvez l'utiliser avec les outils StrongLoop associés pour : - -* Générer et mettre en package votre application en local, puis la déployer en toute sécurité sur votre système de production. -* Redémarrer automatiquement votre application si elle plante pour une raison quelconque. -* Gérer vos clusters à distance. -* Afficher les profils d'UC et les instantanés de segment de mémoire pour optimiser les performances et diagnostiquer les fuites de mémoire. -* Afficher les mesures de performance de votre application. -* Evoluer facilement vers plusieurs hôtes avec un contrôlé intégré de l'équilibreur de charge Nginx. - -Comme décrit ci-dessous, lorsque vous installez StrongLoop PM en tant que service de système d'exploitation à l'aide de votre système init, il redémarre automatiquement au redémarrage du système. Ainsi, vos processus applicatifs et vos clusters resteront toujours actifs. +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 init -Le niveau de fiabilité suivant consiste à garantir que votre application redémarre lorsque le serveur redémarre. Les systèmes peuvent toujours tomber en panne pour divers motifs. Pour garantir que votre application redémarre si le serveur plante, utilisez le système init intégré à votre système d'exploitation. Les deux principaux systèmes init actuellement utilisés sont [systemd](https://wiki.debian.org/systemd) et [Upstart](http://upstart.ubuntu.com/). +Le niveau de fiabilité suivant consiste à garantir que votre application redémarre lorsque le serveur redémarre. Les systèmes peuvent toujours tomber en panne pour divers motifs. Pour garantir que votre application redémarre si le serveur plante, utilisez le système init intégré à votre système d'exploitation. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Vous pouvez utiliser les systèmes init de deux manières dans votre application Express : -* Exécutez votre application dans un gestionnaire de processus, puis installez le gestionnaire de processus en tant que service avec le système init. Le gestionnaire de processus va redémarrer votre application lorsqu'elle plantera et le système init va redémarrer le gestionnaire de processus lorsque le système d'exploitation redémarrera. Il s'agit de la méthode recommandée. -* Exécutez votre application (et Node) directement avec le système init. Cette méthode est plus simple, mais vous ne profitez pas des avantages d'un gestionnaire de processus. +- Exécutez votre application dans un gestionnaire de processus, puis installez le gestionnaire de processus en tant que service avec le système init. Le gestionnaire de processus va redémarrer votre application lorsqu'elle plantera et le système init va redémarrer le gestionnaire de processus lorsque le système d'exploitation redémarrera. Il s'agit de la méthode recommandée. +- Exécutez votre application (et Node) directement avec le système init. Cette méthode est plus simple, mais vous ne profitez pas des avantages d'un gestionnaire de processus. ##### Systemd Systemd est un système Linux et un gestionnaire de services. La plupart des distributions Linux principales ont adopté systemd comme leur système init par défaut. -Un fichier de configuration de service systemd est appelé *fichier d'unité* et porte l'extension .service. Voici un exemple de fichier d'unité permettant de gérer une application Node directement (remplacez le texte en gras par les valeurs appropriées à votre système et votre application) : +Un fichier de configuration de service systemd est appelé _fichier d'unité_ et porte l'extension .service. Voici un exemple de fichier d'unité permettant de gérer une application Node directement (remplacez le texte en gras par les valeurs appropriées à votre système et votre application) : Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -301,99 +247,14 @@ Restart=always [Install] WantedBy=multi-user.target ``` -Pour plus d'informations sur systemd, voir la [page d'aide de systemd](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). - -##### StrongLoop PM en tant que service systemd - -Vous pouvez facilement installer StrongLoop Process Manager en tant que service systemd. Une fois que c'est fait, lorsque le serveur redémarre, il redémarre automatiquement StrongLoop PM, qui redémarre ensuite toutes les applications qu'il gère. - -Pour installer StrongLoop PM en tant que service systemd : - -```bash -$ sudo sl-pm-install --systemd -``` - -Démarrez ensuite le service comme suit : - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -Pour plus d'informations, voir [Setting up a production host](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10) dans la documentation StrongLoop. - -##### Upstart - -Upstart est un outil système disponible sur un grand nombre de distributions Linux et qui permet de démarrer des tâches et des services pendant le démarrage du système, de les arrêter pendant l'arrêt du système et de les superviser. Vous pouvez configurer votre application Express ou votre gestionnaire de processus en tant que service, puis Upstart le redémarrera automatiquement lorsqu'il plantera. - -Un service Upstart est défini dans un fichier de configuration de travail (également appelé "travail") portant l'extension `.conf`. L'exemple qui suit décrit comment créer un travail appelé "myapp" pour une application nommée "myapp" avec le fichier principal situé dans `/projects/myapp/index.js`. - -Créez un fichier nommé `myapp.conf` dans `/etc/init/` avec le contenu suivant (remplacez le texte en gras par les valeurs appropriées à votre système et votre application) : - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -REMARQUE : ce script nécessite Upstart 1.4 ou ultérieur, pris en charge sur Ubuntu 12.04-14.10. -Etant donné que le travail est configuré pour s'exécuter au démarrage du système, votre application sera démarrée avec le système d'exploitation et sera redémarrée automatiquement si l'application plante ou si le système tombe en panne. - -En plus de redémarrer automatiquement l'application, Upstart vous permet d'utiliser les commandes suivantes : - -* `start myapp` – Démarre l'application -* `restart myapp` – Redémarre l'application -* `stop myapp` – Arrête l'application - -Pour plus d'informations sur Upstart, voir [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook). - -##### StrongLoop PM en tant que service Upstart - -Vous pouvez facilement installer StrongLoop Process Manager en tant que service Upstart. Une fois que c'est fait, lorsque le serveur redémarre, il redémarre automatiquement StrongLoop PM, qui redémarre ensuite toutes les applications qu'il gère. - -Pour installer StrongLoop PM en tant que service Upstart 1.4 : - -```bash -$ sudo sl-pm-install -``` - -Exécutez ensuite le service comme suit : - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -REMARQUE : sur les systèmes qui ne prennent pas en charge Upstart 1.4, les commandes sont légèrement différentes. Pour plus d'informations, voir [Setting up a production host](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) dans la documentation StrongLoop. +Pour plus d'informations sur systemd, voir la [page d'aide de systemd](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). ### Exécuter votre application dans un cluster Dans un système multicoeur, vous pouvez augmenter les performances d'une application Node en lançant un cluster de processus. Un cluster exécute plusieurs instances de l'application, idéalement une instance sur chaque coeur d'UC, répartissant ainsi la charge et les tâches entre les instances. - +![Balancing between application instances using the cluster API](/images/clustering.png) IMPORTANT : étant donné que les instances d'application s'exécutent en tant que processus distincts, elles ne partagent pas le même espace mémoire. Autrement dit, les objets sont en local sur chaque instance de l'application. Par conséquent, vous ne pouvez pas conserver l'état dans le code de l'application. Vous pouvez toutefois utiliser un magasin de données en mémoire tel que [Redis](http://redis.io/) pour stocker les données de session et l'état. Cette fonctionnalité s'applique essentiellement à toutes les formes de mise à l'échelle horizontale, que la mise en cluster soit effectuée avec plusieurs processus ou avec plusieurs serveurs physiques. @@ -401,43 +262,52 @@ Dans les applications mises en cluster, les processus de traitement peuvent plan #### Utilisation du module cluster de Node -La mise en cluster peut être réalisée avec le [module cluster](https://nodejs.org/docs/latest/api/cluster.html) de Node. Ce module permet à un processus maître de générer des processus de traitement et de répartir les connexions entrantes parmi ces processus. Toutefois, plutôt que d'utiliser ce module directement, utilisez l'un des nombreux outils qui le font pour vous, à savoir [node-pm](https://www.npmjs.com/package/node-pm) ou [cluster-service](https://www.npmjs.com/package/cluster-service) par exemple. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). Ce module permet à un processus maître de générer des processus de traitement et de répartir les connexions entrantes parmi ces processus. -#### Utilisation de StrongLoop PM +#### Using PM2 -Si vous déployez votre application dans StrongLoop Process Manager (PM), vous pouvez alors utiliser la mise en cluster *sans* modifier votre code d'application. +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 StrongLoop Process Manager (PM) exécute une application, il l'exécute automatiquement dans un cluster avec un nombre de processus de traitement égal au nombre de coeurs d'UC sur le système. Vous pouvez modifier manuellement le nombre de processus de traitement dans le cluster à l'aide de l'outil de ligne de commande slc 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. -Par exemple, en supposant que vous avez déployé votre application sur prod.foo.com et que StrongLoop PM est en mode écoute sur le port 8701 (par défaut), pour définir la taille du cluster sur 8 à l'aide de slc : +To enable cluster mode, start your application like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -Pour plus d'informations sur la mise en cluster avec StrongLoop PM, voir [Clustering](https://docs.strongloop.com/display/SLC/Clustering) dans la documentation StrongLoop. +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 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ 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. ### Mettre en cache les résultats d'une demande Pour améliorer les performances en production, vous pouvez également mettre en cache le résultat des demandes, de telle sorte que votre application ne répète pas l'opération de traitement de la même demande plusieurs fois. -Utilisez un serveur de mise en cache tel que [Varnish](https://www.varnish-cache.org/) ou [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (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-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. ### Utiliser un équilibreur de charge Quel que soit le niveau d'optimisation d'une application, une instance unique ne peut traiter qu'un volume limité de charge et de trafic. Pour faire évoluer une application, vous pouvez exécuter plusieurs instances de cette application et répartir le trafic en utilisant un équilibreur de charge. La configuration d'un équilibreur de charge peut améliorer les performances et la vitesse de votre application et lui permettre d'évoluer plus largement qu'avec une seule instance. -Un équilibreur de charge est généralement un proxy inverse qui orchestre le trafic entrant et sortant de plusieurs instances d'application et serveurs. Vous pouvez facilement configurer un équilibreur de charge pour votre application à l'aide de [Nginx](http://nginx.org/en/docs/http/load_balancing.html) ou de [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). - -Avec l'équilibrage de charge, vous devrez peut-être vérifier que les demandes associées à un ID de session spécifique sont connectées au processus dont elles sont issues. Ce procédé est appelé *affinité de session* (ou *sessions persistantes*) et peut être effectué en utilisant un magasin de données tel que Redis pour les données de session (en fonction de votre application), comme décrit ci-dessus. Pour en savoir plus, voir [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). - -#### Utilisation de StrongLoop PM avec un équilibreur de charge Nginx +Un équilibreur de charge est généralement un proxy inverse qui orchestre le trafic entrant et sortant de plusieurs instances d'application et serveurs. 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). -[StrongLoop Process Manager](http://strong-pm.io/) est intégré à un contrôleur Nginx, ce qui permet de paramétrer facilement les configurations d'environnement de production à plusieurs hôtes. Pour plus d'informations, voir [Scaling to multiple servers](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers) (documentation StrongLoop). - +Avec l'équilibrage de charge, vous devrez peut-être vérifier que les demandes associées à un ID de session spécifique sont connectées au processus dont elles sont issues. Ce procédé est appelé _affinité de session_ (ou _sessions persistantes_) et peut être effectué en utilisant un magasin de données tel que Redis pour les données de session (en fonction de votre application), comme décrit ci-dessus. Pour en savoir plus, voir [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). ### Utiliser un proxy inverse Un proxy inverse accompagne une application Web et exécute des opérations de prise en charge sur les demandes, en plus de diriger les demandes vers l'application. Il peut gérer les pages d'erreur, la compression, la mise en cache, le dépôt de fichiers et l'équilibrage de charge entre autres. -La transmission de tâches qui ne requièrent aucune connaissance de l'état d'application à un proxy inverse permet à Express de réaliser des tâches d'application spécialisées. C'est pour cette raison qu'il est recommandé d'exécuter Express derrière un proxy inverse tel que [Nginx](https://www.nginx.com/) ou [HAProxy](http://www.haproxy.org/) en production. +La transmission de tâches qui ne requièrent aucune connaissance de l'état d'application à un proxy inverse permet à Express de réaliser des tâches d'application spécialisées. 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. diff --git a/fr/advanced/best-practice-security.md b/fr/advanced/best-practice-security.md old mode 100755 new mode 100644 index ac293abc54..16b74538ad --- a/fr/advanced/best-practice-security.md +++ b/fr/advanced/best-practice-security.md @@ -1,22 +1,47 @@ --- layout: page title: Meilleures pratiques de sécurité pour Express en production +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: fr -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # Meilleures pratiques en production : Sécurité ## Présentation -Le terme *"production"* fait référence à la phase du cycle de vie du logiciel au cours de laquelle une application ou une API est généralement disponible pour ses consommateurs ou utilisateurs finaux. En revanche, en phase de *"développement"*, l'écriture et le test de code se poursuivent activement et l'application n'est pas ouverte pour un accès externe. Les environnements système correspondants sont respectivement appelés environnement de *production* et environnement de *développement*. +Le terme _"production"_ fait référence à la phase du cycle de vie du logiciel au cours de laquelle une application ou une API est généralement disponible pour ses consommateurs ou utilisateurs finaux. En revanche, en phase de _"développement"_, l'écriture et le test de code se poursuivent activement et l'application n'est pas ouverte pour un accès externe. Les environnements système correspondants sont respectivement appelés environnement de _production_ et environnement de _développement_. Les environnements de développement et de production sont généralement configurés différemment et leurs exigences divergent grandement. Ce qui convient parfaitement en développement peut être inacceptable en production. Par exemple, dans un environnement de développement, vous pouvez souhaiter une consignation prolixe des erreurs en vue du débogage, alors que ce type de comportement présente des risques au niveau de sécurité en environnement de production. De plus, en environnement de développement, vous n'avez pas à vous soucier de l'extensibilité, de la fiabilité et des performances, tandis que ces éléments sont essentiels en environnement de production. +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + Cet article traite des meilleures pratiques en terme de sécurité pour les applications Express déployées en production. +- [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) + - [hsts](https://github.com/helmetjs/hsts) définit l'en-tête `Strict-Transport-Security` qui impose des connexions (HTTP sur SSL/TLS) sécurisées au serveur. + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) supprime l'en-tête `X-Powered-By`. + - [Reduce fingerprinting](#reduce-fingerprinting) + - [xssFilter](https://github.com/helmetjs/x-xss-protection) définit `X-XSS-Protection` afin d'activer le filtre de script intersites (XSS) dans les navigateurs Web les plus récents. + - [noCache](https://github.com/helmetjs/nocache) définit des en-têtes `Cache-Control` et Pragma pour désactiver la mise en cache côté client. + - [ieNoOpen](https://github.com/helmetjs/ienoopen) définit `X-Download-Options` pour IE8+. + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure) + - Désactivez au minimum l'en-tête X-Powered-By + - [Additional considerations](#additional-considerations) + ## N'utilisez pas de versions obsolètes ou vulnérables d'Express Les versions 2.x et 3.x d'Express ne sont plus prises en charge. Les problèmes liés à la sécurité et aux performances dans ces versions ne seront pas corrigés. Ne les utilisez pas ! Si vous êtes passé à la version 4, suivez le [guide de migration](/{{ page.lang }}/guide/migrating-4.html). @@ -27,53 +52,122 @@ Vérifiez également que vous n'utilisez aucune des versions vulnérables d'Expr Si votre application traite ou transmet des données sensibles, utilisez [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security) (Transport Layer Security) afin de sécuriser la connexion et les données. Cette technologie de l'information chiffre les données avant de les envoyer du client au serveur, ce qui vous préserve des risques d'hameçonnage les plus communs (et faciles). Même si les requêtes Ajax et POST ne sont pas clairement visibles et semblent "masquées" dans les navigateurs, leur trafic réseau n'est pas à l'abri d'une [détection de paquet](https://en.wikipedia.org/wiki/Packet_analyzer) ni des [attaques d’intercepteur](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). -Vous connaissez sans doute le chiffrement SSL (Secure Socket Layer). [TLS est simplement une évolution de SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). En d'autres termes, si vous utilisiez SSL auparavant, envisagez de passer à TLS. Nous recommandons généralement Nginx pour gérer TLS. Pour des informations de référence fiables concernant la configuration de TLS sur Nginx (et d'autres serveurs), voir [Configurations de serveur recommandées (wiki Mozilla)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). +Vous connaissez sans doute le chiffrement SSL (Secure Socket Layer). [TLS est simplement une évolution de SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). En d'autres termes, si vous utilisiez SSL auparavant, envisagez de passer à TLS. Nous recommandons généralement Nginx pour gérer TLS. Pour des informations de référence fiables concernant la configuration de TLS sur Nginx (et d'autres serveurs), voir [Configurations de serveur recommandées (wiki Mozilla)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). Par ailleurs, un outil très pratique, [Let's Encrypt](https://letsencrypt.org/about/), autorité de certification gratuite, automatisée et ouverte fournie par le groupe de recherche sur la sécurité sur Internet, [ISRG (Internet Security Research Group)](https://letsencrypt.org/isrg/), vous permet de vous procurer gratuitement un certificat TLS. +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## Utilisez Helmet [Helmet](https://www.npmjs.com/package/helmet) vous aide à protéger votre application de certaines des vulnérabilités bien connues du Web en configurant de manière appropriée des en-têtes HTTP. -Helmet n'est actuellement qu'une collection de neuf fonctions middleware plus petites qui définissent des en-têtes HTTP liés à la sécurité : +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: -* [csp](https://github.com/helmetjs/csp) définit l'en-tête `Content-Security-Policy` pour la protection contre les attaques de type cross-site scripting et autres injections intersites. -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) supprime l'en-tête `X-Powered-By`. -* [hsts](https://github.com/helmetjs/hsts) définit l'en-tête `Strict-Transport-Security` qui impose des connexions (HTTP sur SSL/TLS) sécurisées au serveur. -* [ieNoOpen](https://github.com/helmetjs/ienoopen) définit `X-Download-Options` pour IE8+. -* [noCache](https://github.com/helmetjs/nocache) définit des en-têtes `Cache-Control` et Pragma pour désactiver la mise en cache côté client. -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) définit `X-Content-Type-Options` pour protéger les navigateurs du reniflage du code MIME d'une réponse à partir du type de contenu déclaré. -* [frameguard](https://github.com/helmetjs/frameguard) définit l'en-tête `X-Frame-Options` pour fournir une protection [clickjacking](https://www.owasp.org/index.php/Clickjacking). -* [xssFilter](https://github.com/helmetjs/x-xss-protection) définit `X-XSS-Protection` afin d'activer le filtre de script intersites (XSS) dans les navigateurs Web les plus récents. +- `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 +- `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 +- `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 + +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Installez Helmet comme n'importe quel autre module : ```bash -$ npm install --save helmet +$ npm install helmet ``` Puis, pour l'utiliser dans votre code : ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### Désactivez au minimum l'en-tête X-Powered-By +## Reduce fingerprinting -Si vous ne voulez pas utiliser Helmet, désactivez au minimum l'en-tête `X-Powered-By`. Les intrus peuvent utiliser cet en-tête (activé par défaut) afin de détecter les applications qui exécutent Express et lancer ensuite des attaques spécifiquement ciblées. +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. -Il est donc conseillé de neutraliser l'en-tête à l'aide de la méthode `app.disable()` comme suit : +By default, Express sends the `X-Powered-By` response header that you can +disable using the `app.disable()` method: ```js app.disable('x-powered-by') ``` -Si vous utilisez `helmet.js`, cette opération s'effectue automatiquement. +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## Utilisez les cookies de manière sécurisée @@ -81,12 +175,12 @@ Pour garantir que les cookies n'ouvrent pas votre application aux attaques, n'ut Il existe deux modules principaux de session de cookie de middleware : -* [express-session](https://www.npmjs.com/package/express-session) qui remplace le middleware `express.session` intégré à Express 3.x. -* [cookie-session](https://www.npmjs.com/package/cookie-session) qui remplace le middleware `express.cookieSession` intégré à Express 3.x. +- [express-session](https://www.npmjs.com/package/express-session) qui remplace le middleware `express.session` intégré à Express 3.x. +- [cookie-session](https://www.npmjs.com/package/cookie-session) qui remplace le middleware `express.cookieSession` intégré à Express 3.x. -La principale différence entre ces deux modules tient à la manière dont ils sauvegardent les données de session des cookies. Le middleware [express-session](https://www.npmjs.com/package/express-session) stocke les données de session sur le serveur ; il ne sauvegarde que l'ID session dans le cookie lui-même, mais pas les données de session. Par défaut, il utilise le stockage en mémoire et n'est pas conçu pour un environnement de production. En production, vous devrez configurer un magasin de sessions évolutif (voir la liste des [magasins de sessions compatibles](https://github.com/expressjs/session#compatible-session-stores)). +La principale différence entre ces deux modules tient à la manière dont ils sauvegardent les données de session des cookies. Le middleware [express-session](https://www.npmjs.com/package/express-session) stocke les données de session sur le serveur ; il ne sauvegarde que l'ID session dans le cookie lui-même, mais pas les données de session. Par défaut, il utilise le stockage en mémoire et n'est pas conçu pour un environnement de production. En production, vous devrez configurer un magasin de sessions évolutif (voir la liste des [magasins de sessions compatibles](https://github.com/expressjs/session#compatible-session-stores)). -En revanche, le middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implémente un stockage sur cookie, c'est-à-dire qu'il sérialise l'intégralité de la session sur le cookie, et non simplement une clé de session. Utilisez-le uniquement lorsque les données de session sont relativement peu nombreuses et faciles à coder sous forme de valeurs primitives (au lieu d'objets). Même si les navigateurs sont censés prendre en charge au moins 4096 octets par cookie, pour ne pas risquer de dépasser cette limite, limitez-vous à 4093 octets par domaine. De plus, n'oubliez pas que les données de cookie seront visibles du client et que s'il n'est pas nécessaire qu'elles soient sécurisées ou illisibles, express-session est probablement la meilleure solution. +En revanche, le middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implémente un stockage sur cookie, c'est-à-dire qu'il sérialise l'intégralité de la session sur le cookie, et non simplement une clé de session. Utilisez-le uniquement lorsque les données de session sont relativement peu nombreuses et faciles à coder sous forme de valeurs primitives (au lieu d'objets). Même si les navigateurs sont censés prendre en charge au moins 4096 octets par cookie, pour ne pas risquer de dépasser cette limite, limitez-vous à 4093 octets par domaine. De plus, n'oubliez pas que les données de cookie seront visibles du client et que s'il n'est pas nécessaire qu'elles soient sécurisées ou illisibles, express-session est probablement la meilleure solution. ### N'utilisez pas de nom de cookie de session par défaut @@ -100,19 +194,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### Définissez des options de sécurité de cookie Définissez les options de cookie suivantes pour accroître la sécurité : -* `secure` - Garantit que le navigateur n'envoie le cookie que sur HTTPS. -* `httpOnly` - Garantit que le cookie n'est envoyé que sur HTTP(S), pas au JavaScript du client, ce qui renforce la protection contre les attaques de type cross-site scripting. -* `domain` - Indique le domaine du cookie ; utilisez cette option pour une comparaison avec le domaine du serveur dans lequel l'URL est demandée. S'ils correspondent, vérifiez ensuite l'attribut de chemin. -* `path` - Indique le chemin du cookie ; utilisez cette option pour une comparaison avec le chemin demandé. Si le chemin et le domaine correspondent, envoyez le cookie dans la demande. -* `expires` - Utilisez cette option pour définir la date d'expiration des cookies persistants. +- `secure` - Garantit que le navigateur n'envoie le cookie que sur HTTPS. +- `httpOnly` - Garantit que le cookie n'est envoyé que sur HTTP(S), pas au JavaScript du client, ce qui renforce la protection contre les attaques de type cross-site scripting. +- `domain` - Indique le domaine du cookie ; utilisez cette option pour une comparaison avec le domaine du serveur dans lequel l'URL est demandée. S'ils correspondent, vérifiez ensuite l'attribut de chemin. +- `path` - Indique le chemin du cookie ; utilisez cette option pour une comparaison avec le chemin demandé. Si le chemin et le domaine correspondent, envoyez le cookie dans la demande. +- `expires` - Utilisez cette option pour définir la date d'expiration des cookies persistants. Exemple d'utilisation du middleware [cookie-session](https://www.npmjs.com/package/cookie-session) : @@ -132,23 +225,59 @@ app.use(session({ path: 'foo/bar', expires: expiryDate } -}) -) +})) ``` -## Autres considérations +## Implémentez la limitation de débit pour empêcher les attaques de force brute liées à l'authentification. + +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. + +[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) + +## 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. + +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` + +If you want to stay more secure, consider [Snyk](https://snyk.io/). -Voici d'autres recommandations issues de l'excellente [liste de contrôle de sécurité Node.js](https://blog.risingstack.com/node-js-security-checklist/). Pour tous les détails sur ces recommandations, reportez-vous à cet article de blogue : +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: -* Implémentez la limitation de débit pour empêcher les attaques de force brute liées à l'authentification. Une façon de faire consiste à utiliser [StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) pour mettre en place une règle de limitation de débit. Sinon, vous pouvez utiliser des middleware tels que [express-limiter](https://www.npmjs.com/package/express-limiter), mais vous devrez alors modifier quelque peu votre code. -* Filtrez et nettoyez toujours les entrées utilisateur pour vous protéger contre les attaques de cross-site scripting (XSS) et d'injection de commande. -* Défendez-vous contre les attaques par injection SQL en utilisant des requêtes paramétrées ou des instructions préparées. -* Utilisez l'outil [sqlmap](http://sqlmap.org/) à code source ouvert pour détecter les vulnérabilités par injection SQL dans votre application. -* Utilisez les outils [nmap](https://nmap.org/) et [sslyze](https://github.com/nabla-c0d3/sslyze) pour tester la configuration de vos chiffrements, clés et renégociations SSL, ainsi que la validité de votre certificat. -* Utilisez [safe-regex](https://www.npmjs.com/package/safe-regex) pour s'assurer que vos expressions régulières ne sont pas exposées à des attaques ReDoS ([regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)). +```bash +$ npm install -g snyk +$ cd your-app +``` -## Eviter les autres vulnérabilités connues +Use this command to test your application for vulnerabilities: + +```bash +$ snyk test +``` + +### Eviter les autres vulnérabilités connues Gardez un oeil sur les recommandations [Node Security Project](https://npmjs.com/advisories) qui peuvent concerner Express ou d'autres modules utilisés par votre application. En règle générale, Node Security Project est une excellente ressource de connaissances et d'outils sur la sécurité de Node. Pour finir, les applications Express - comme toutes les autres applications Web - peuvent être vulnérables à une variété d'attaques Web. Familiarisez vous avec les [vulnérabilités Web](https://www.owasp.org/www-project-top-ten/) connues et prenez des précautions pour les éviter. + +## Autres considérations + +Voici d'autres recommandations issues de l'excellente [liste de contrôle de sécurité Node.js](https://blog.risingstack.com/node-js-security-checklist/). Pour tous les détails sur ces recommandations, reportez-vous à cet article de blogue : + +- Filtrez et nettoyez toujours les entrées utilisateur pour vous protéger contre les attaques de cross-site scripting (XSS) et d'injection de commande. +- Défendez-vous contre les attaques par injection SQL en utilisant des requêtes paramétrées ou des instructions préparées. +- Utilisez l'outil [sqlmap](http://sqlmap.org/) à code source ouvert pour détecter les vulnérabilités par injection SQL dans votre application. +- Utilisez les outils [nmap](https://nmap.org/) et [sslyze](https://github.com/nabla-c0d3/sslyze) pour tester la configuration de vos chiffrements, clés et renégociations SSL, ainsi que la validité de votre certificat. +- Utilisez [safe-regex](https://www.npmjs.com/package/safe-regex) pour s'assurer que vos expressions régulières ne sont pas exposées à des attaques ReDoS ([regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)). + +[helmet]: \ No newline at end of file diff --git a/fr/advanced/developing-template-engines.md b/fr/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 95792a5df2..da95518aa5 --- a/fr/advanced/developing-template-engines.md +++ b/fr/advanced/developing-template-engines.md @@ -1,10 +1,10 @@ --- layout: page title: Développement de moteurs de modèles pour 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. menu: advanced lang: fr -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. +redirect_from: " " --- # Développement de moteurs de modèles pour Express @@ -17,9 +17,10 @@ Le code suivant est un exemple d'implémentation d'un moteur de modèle très si const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -34,6 +35,7 @@ Votre application est désormais en mesure d'afficher le rendu des fichiers `.nt #title# #message# ``` + ENsuite, créez la route suivante dans votre application. ```js @@ -41,4 +43,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -Lorsque vous effectuerez une demande à la page d'accueil, `index.ntl` sera rendu au format HTML. + +Lorsque vous effectuerez une demande à la page d'accueil, `index.ntl` sera rendu au format HTML. \ No newline at end of file diff --git a/fr/advanced/healthcheck-graceful-shutdown.md b/fr/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..843ff78c9b --- /dev/null +++ b/fr/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: fr +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### Exemple + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/fr/advanced/security-updates.md b/fr/advanced/security-updates.md old mode 100755 new mode 100644 index efb6b8e23b..556cdda32c --- a/fr/advanced/security-updates.md +++ b/fr/advanced/security-updates.md @@ -1,10 +1,10 @@ --- layout: page title: Express 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. menu: advanced lang: fr -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # Mises à jour de sécurité @@ -16,32 +16,73 @@ Les vulnérabilités Node.js affectent directement Express. Cependant, [gardez u La liste ci-dessous répertorie les vulnérabilités Express qui ont été corrigées dans la mise à jour de la version spécifiée. +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * Correction de la vulnérabilité de divulgation de racine dans `express.static`, `res.sendfile` et `res.sendFile` - * 4.10.7 - * Correction de la vulnérabilité de redirection ouverte dans `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 - * Correction des vulnérabilités de traversée de répertoire dans `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 peut divulguer des `fd` dans certaines situations qui affectent `express.static` et `res.sendfile`. Des demandes malveillantes pouvaient entraîner la divulgation de `fd`, ainsi que des erreurs `EMFILE` et une absence de réponse du serveur. - * 4.8.0 - * Les tableaux creux qui possèdent des index très élevés dans la chaîne de requête pouvaient entraîner la saturation de mémoire et la panne du serveur. - * Les objets contenant des chaînes de requête extrêmement imbriquées pouvaient entraîner le blocage du processus et figer temporairement le serveur. +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - Correction de la vulnérabilité de divulgation de racine dans `express.static`, `res.sendfile` et `res.sendFile` +- 4.10.7 + - Correction de la vulnérabilité de redirection ouverte dans `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 + - Correction des vulnérabilités de traversée de répertoire dans `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 peut divulguer des `fd` dans certaines situations qui affectent `express.static` et `res.sendfile`. Des demandes malveillantes pouvaient entraîner la divulgation de `fd`, ainsi que des erreurs `EMFILE` et une absence de réponse du serveur. +- 4.8.0 + - Les tableaux creux qui possèdent des index très élevés dans la chaîne de requête pouvaient entraîner la saturation de mémoire et la panne du serveur. + - Les objets contenant des chaînes de requête extrêmement imbriquées pouvaient entraîner le blocage du processus et figer temporairement le serveur. ## 3.x - * 3.19.1 - * Correction de la vulnérabilité de divulgation de racine dans `express.static`, `res.sendfile` et `res.sendFile` - * 3.19.0 - * Correction de la vulnérabilité de redirection ouverte dans `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 - * Correction des vulnérabilités de traversée de répertoire dans `express.static`. - * 3.16.6 - * Node.js 0.10 peut divulguer des `fd` dans certaines situations qui affectent `express.static` et `res.sendfile`. Des demandes malveillantes pouvaient entraîner la divulgation de `fd`, ainsi que des erreurs `EMFILE` et une absence de réponse du serveur. - * 3.16.0 - * Les tableaux creux qui possèdent des index très élevés dans la chaîne de requête pouvaient entraîner la saturation de mémoire et la panne du serveur. - * Les objets contenant des chaînes de requête extrêmement imbriquées pouvaient entraîner le blocage du processus et figer temporairement le serveur. - * 3.3.0 - * La réponse 404 à une tentative de substitution de méthode non prise en charge était susceptible d'entraîner des attaques de type cross-site scripting. +
    + **Express 3.x N'EST PLUS PRIS EN CHARGE** + +Les problèmes de performances et de sécurité connus et inconnus n'ont pas été traités depuis la dernière mise à jour (1er août 2015). Il est fortement recommandé d'utiliser la dernière version d'Express. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
    + +- 3.19.1 + - Correction de la vulnérabilité de divulgation de racine dans `express.static`, `res.sendfile` et `res.sendFile` +- 3.19.0 + - Correction de la vulnérabilité de redirection ouverte dans `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 + - Correction des vulnérabilités de traversée de répertoire dans `express.static`. +- 3.16.6 + - Node.js 0.10 peut divulguer des `fd` dans certaines situations qui affectent `express.static` et `res.sendfile`. Des demandes malveillantes pouvaient entraîner la divulgation de `fd`, ainsi que des erreurs `EMFILE` et une absence de réponse du serveur. +- 3.16.0 + - Les tableaux creux qui possèdent des index très élevés dans la chaîne de requête pouvaient entraîner la saturation de mémoire et la panne du serveur. + - Les objets contenant des chaînes de requête extrêmement imbriquées pouvaient entraîner le blocage du processus et figer temporairement le serveur. +- 3.3.0 + - La réponse 404 à une tentative de substitution de méthode non prise en charge était susceptible d'entraîner des attaques de type cross-site scripting. \ No newline at end of file diff --git a/fr/api.md b/fr/api.md old mode 100755 new mode 100644 index b125d5745a..0b89e19f7b --- a/fr/api.md +++ b/fr/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - Référence de l'API +version: 5x +title: Express 5.x - Référence de l'API +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: fr -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    API 4.x

    - - - {% include api/en/4x/express.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
    diff --git a/fr/changelog/index.md b/fr/changelog/index.md new file mode 100644 index 0000000000..7c128a5aa9 --- /dev/null +++ b/fr/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: fr +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/fr/guide/behind-proxies.md b/fr/guide/behind-proxies.md old mode 100755 new mode 100644 index cb9fb96182..3ee3740b11 --- a/fr/guide/behind-proxies.md +++ b/fr/guide/behind-proxies.md @@ -1,37 +1,44 @@ --- layout: page title: Serveurs proxy derrière Express +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. menu: guide lang: fr -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. +redirect_from: " " --- -# Express derrière proxys +# Serveurs proxy derrière Express -Lorsque vous exécutez une application Express derrière un proxy, affectez à la variable d'application `trust proxy` l'une des valeurs indiquées dans le tableau suivant, en utilisant [app.set()](/{{ page.lang }}/4x/api.html#app.set). +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.
    -L'exécution de l'application n'échouera pas si la variable d'application `trust proxy` n'est pas définie, mais l'adresse IP du proxy sera enregistrée de manière incorrecte en tant qu'adresse IP du client.`` +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.
    +The application setting `trust proxy` may be set to one of the values listed in the following table. + - - + - +
    TypeValeur
    Booléen -Si la valeur est `true`, l'adresse IP du client est interprétée comme étant l'entrée la plus à gauche dans l'en-tête `X-Forwarded-*`. +Si la valeur est `true`, l'adresse IP du client est interprétée comme étant l'entrée la plus à gauche dans l'en-tête `X-Forwarded-*`. + Si la valeur est `false`, l'application est interprétée comme étant directement accessible sur Internet et l'adresse IP du client est dérivée de `req.connection.remoteAddress`. Il s'agit du paramètre par défaut. + +
    +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. +
    Adresses IPIP addresses -Adresse IP, sous-réseau ou tableau d'adresses IP et de sous-réseaux auxquels faire confiance. La liste suivante montre les noms de sous-réseau préconfigurés : -* 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` +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: + +- 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` Vous pouvez définir les adresses IP de l'une des manières suivantes : @@ -42,20 +49,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -S'ils sont spécifiés, les sous-réseaux ou les adresses IP sont exclus du processus d'identification d'adresse, et l'adresse IP sans confiance la plus proche du serveur d'applications est identifiée comme étant l'adresse IP du client. +S'ils sont spécifiés, les sous-réseaux ou les adresses IP sont exclus du processus d'identification d'adresse, et l'adresse IP sans confiance la plus proche du serveur d'applications est identifiée comme étant l'adresse IP du client. 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. +
    Numérique -Approuve le `n`ème tronçon à partir proxy de face comme étant le client. +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. + +
    +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. +
    FonctionFunction -Implémentation de confiance personnalisée. N'utilisez cette option que si vous êtes sûr de vous. - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -63,12 +74,13 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
    -La définition d'une valeur autre que `false` `trust proxy` entraîne trois modifications importantes : +Enabling `trust proxy` will have the following impact:
    • La valeur de [req.hostname](/{{ page.lang }}/api.html#req.hostname) est dérivée de l'ensemble de valeurs indiqué dans l'en-tête `X-Forwarded-Host`, qui peut être défini par le client ou par le proxy. diff --git a/fr/guide/database-integration.md b/fr/guide/database-integration.md old mode 100755 new mode 100644 index 0487324d41..93d9ccd6bb --- a/fr/guide/database-integration.md +++ b/fr/guide/database-integration.md @@ -1,216 +1,269 @@ --- layout: page title: Express database integration +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: fr -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # Intégration de bases de données L'ajout de la fonctionnalité permettant de connecter des bases de données aux applications Express consiste simplement à charger un pilote Node.js approprié pour les bases de données de votre application. Ce document explique brièvement comment ajouter et utiliser dans votre application Express certains des modules Node.js les plus populaires pour les systèmes de base de données : -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
      -Ces pilotes de base de données ne sont qu'une partie de ceux disponibles. Pour d'autres options, +Ces pilotes de base de données ne sont qu'une partie de ceux disponibles. Pour d'autres options, consultez le site [npm](https://www.npmjs.com/).
      - - ## Cassandra **Module** : [cassandra-driver](https://github.com/datastax/nodejs-driver) **Installation** +### Installation + ```bash $ npm install cassandra-driver ``` -**Exemple** +### Exemple + +```js +const cassandra = require('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 -
      -
      -var cassandra = require('cassandra-driver');
      -var client = new cassandra.Client({ contactPoints: ['localhost']});
      +```bash
      +$ npm install couchbase
      +```
       
      -client.execute('select key from system.local', function(err, result) {
      -  if (err) throw err;
      -  console.log(result.rows[0]);
      -});
      -
      -
      +### Exemple - +```js +const couchbase = require('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** +### Installation + ```bash $ npm install nano ``` -**Exemple** +### Exemple -
      -
      -var nano = require('nano')('http://localhost:5984');
      -nano.db.create('books');
      -var books = nano.db.use('books');
      +```js
      +const nano = require('nano')('http://localhost:5984')
      +nano.db.create('books')
      +const books = nano.db.use('books')
       
      -//Insert a book document in the books database
      -books.insert({name: 'The Art of war'}, null, function(err, body) {
      -  if (!err){
      -    console.log(body);
      +// Insert a book document in the books database
      +books.insert({ name: 'The Art of war' }, null, (err, body) => {
      +  if (err) {
      +    console.log(err)
      +  } else {
      +    console.log(body)
         }
      -});
      +})
       
      -//Get a list of all books
      -books.list(function(err, body){
      -  console.log(body.rows);
      -});
      -
      -
      - - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **Module** : [levelup](https://github.com/rvagg/node-levelup) **Installation** +### Installation + ```bash $ npm install level levelup leveldown ``` -**Exemple** - -
      -
      -var levelup = require('levelup');
      -var db = levelup('./mydb');
      +### Exemple
       
      -db.put('name', 'LevelUP', function (err) {
      +```js
      +const levelup = require('levelup')
      +const db = levelup('./mydb')
       
      -  if (err) return console.log('Ooops!', err);
      -  db.get('name', function (err, value) {
      -    if (err) return console.log('Ooops!', err);
      -    console.log('name=' + value);
      -  });
      +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** +### Installation + ```bash $ npm install mysql ``` -**Exemple** +### Exemple -
      -
      -var mysql      = require('mysql');
      -var connection = mysql.createConnection({
      -  host     : 'localhost',
      -  user     : 'dbuser',
      -  password : 's3kreee7'
      -});
      +```js
      +const mysql = require('mysql')
      +const connection = mysql.createConnection({
      +  host: 'localhost',
      +  user: 'dbuser',
      +  password: 's3kreee7',
      +  database: 'my_db'
      +})
       
      -connection.connect();
      +connection.connect()
       
      -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      -  if (err) throw err;
      -  console.log('The solution is: ', rows[0].solution);
      -});
      +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
      +  if (err) throw err
       
      -connection.end();
      -
      -
      + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **Module** : [mongodb](https://github.com/mongodb/node-mongodb-native) **Installation** +### Installation + ```bash $ npm install mongodb ``` -**Exemple** +### Example (v2.\*) + +```js +const MongoClient = require('mongodb').MongoClient + +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +### Example (v3.\*) -
      -
      -var MongoClient = require('mongodb').MongoClient;
      +```js
      +const MongoClient = require('mongodb').MongoClient
       
      -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
      -  if (err) {
      -    throw err;
      -  }
      -  db.collection('mammals').find().toArray(function(err, result) {
      -    if (err) {
      -      throw err;
      -    }
      -    console.log(result);
      -  });
      -});
      -
      -
      +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err -Si vous voulez un pilote de modèle d'objet pour MongoDB, recherchez [Mongoose](https://github.com/LearnBoost/mongoose). + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` - +Si vous voulez un pilote de modèle d'objet pour MongoDB, recherchez [Mongoose](https://github.com/LearnBoost/mongoose). ## Neo4j **Module** : [apoc](https://github.com/hacksparrow/apoc) **Installation** +### Installation + ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**Exemple** +### Exemple -
      -
      -var apoc = require('apoc');
      +```js
      +const neo4j = require('neo4j-driver')
      +const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
       
      -apoc.query('match (n) return n').exec().then(
      -  function (response) {
      -    console.log(response);
      -  },
      -  function (fail) {
      -    console.log(fail);
      -  }
      -);
      -
      -
      +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 @@ -218,7 +271,7 @@ apoc.query('match (n) return n').exec().then( ### Installation - Remarque: [Voir les conditions préalables à l'installation](https://github.com/oracle/node-oracledb#-installation). +Remarque: [Voir les conditions préalables à l'installation](https://github.com/oracle/node-oracledb#-installation). ```bash $ npm install oracledb @@ -258,129 +311,182 @@ async function getEmployee (empId) { getEmployee(101) ``` - - ## PostgreSQL **Module** : [pg-promise](https://github.com/vitaly-t/pg-promise) **Installation** +### Installation + ```bash $ npm install pg-promise ``` -**Exemple** - -
      -
      -var pgp = require("pg-promise")(/*options*/);
      -var db = pgp("postgres://username:password@host:port/database");
      -
      -db.one("SELECT $1 AS value", 123)
      -    .then(function (data) {
      -        console.log("DATA:", data.value);
      -    })
      -    .catch(function (error) {
      -        console.log("ERROR:", error);
      -    });
      -
      -
      +### Exemple - +```js +const pgp = require('pg-promise')(/* options */) +const db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **Module** : [redis](https://github.com/mranney/node_redis) **Installation** +### Installation + ```bash $ npm install redis ``` -**Exemple** +### Exemple -
      -
      -var client = require('redis').createClient();
      +```js
      +const redis = require('redis')
      +const client = redis.createClient()
       
      -client.on('error', function (err) {
      -  console.log('Error ' + err);
      -});
      +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.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', function (err, replies) {
      +client.hkeys('hash key', (err, replies) => {
      +  console.log(`${replies.length} replies:`)
       
      -  console.log(replies.length + ' replies:');
      -  replies.forEach(function (reply, i) {
      -    console.log('    ' + i + ': ' + reply);
      -  });
      +  replies.forEach((reply, i) => {
      +    console.log(`    ${i}: ${reply}`)
      +  })
       
      -  client.quit();
      +  client.quit()
      +})
      +```
       
      -});
      -
      -
      +## SQL Server - +**Module**: [tedious](https://github.com/tediousjs/tedious) + +### Installation + +```bash +$ npm install tedious +``` + +### Exemple + +```js +const Connection = require('tedious').Connection +const Request = require('tedious').Request + +const config = { + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } +} + +const connection = new Connection(config) + +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **Module** : [sqlite3](https://github.com/mapbox/node-sqlite3) **Installation** +### Installation + ```bash $ npm install sqlite3 ``` -**Exemple** - -
      -
      -var sqlite3 = require('sqlite3').verbose();
      -var db = new sqlite3.Database(':memory:');
      +### Exemple
       
      -db.serialize(function() {
      +```js
      +const sqlite3 = require('sqlite3').verbose()
      +const db = new sqlite3.Database(':memory:')
       
      -  db.run('CREATE TABLE lorem (info TEXT)');
      -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
      +db.serialize(() => {
      +  db.run('CREATE TABLE lorem (info TEXT)')
      +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
       
      -  for (var i = 0; i < 10; i++) {
      -    stmt.run('Ipsum ' + i);
      +  for (let i = 0; i < 10; i++) {
      +    stmt.run(`Ipsum ${i}`)
         }
       
      -  stmt.finalize();
      +  stmt.finalize()
       
      -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
      -    console.log(row.id + ': ' + row.info);
      -  });
      -});
      +  db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
      +    console.log(`${row.id}: ${row.info}`)
      +  })
      +})
       
      -db.close();
      -
      -
      - - +db.close() +``` ## ElasticSearch **Module** : [elasticsearch](https://github.com/elastic/elasticsearch-js) **Installation** +### Installation + ```bash $ npm install elasticsearch ``` -**Exemple** +### Exemple -
      -
      -var elasticsearch = require('elasticsearch');
      -var client = elasticsearch.Client({
      +```js
      +const elasticsearch = require('elasticsearch')
      +const client = elasticsearch.Client({
         host: 'localhost:9200'
      -});
      +})
       
       client.search({
         index: 'books',
      @@ -393,10 +499,9 @@ client.search({
             }
           }
         }
      -}).then(function(response) {
      -  var hits = response.hits.hits;
      -}, function(error) {
      -  console.trace(error.message);
      -});
      -
      -
      +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/fr/guide/debugging.md b/fr/guide/debugging.md old mode 100755 new mode 100644 index 17fde6280f..fe17283137 --- a/fr/guide/debugging.md +++ b/fr/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Débogage d'Express +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: fr -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # Débogage d'Express @@ -18,7 +18,7 @@ $ DEBUG=express:* node index.js Sous Windows, utilisez la commande correspondante. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` L'exécution de cette commande sur l'application par défaut générée par le [générateur express](/{{ page.lang }}/starter/generator.html) imprime le résultat suivant : @@ -59,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -104,3 +104,27 @@ Vous pouvez spécifier plusieurs espaces de noms de débogage en affectant une l ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/fr/guide/error-handling.md b/fr/guide/error-handling.md old mode 100755 new mode 100644 index d191b5c539..d367a8ac1c --- a/fr/guide/error-handling.md +++ b/fr/guide/error-handling.md @@ -1,16 +1,198 @@ --- layout: page title: Traitement d'erreurs Express +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: fr -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # Traitement d'erreurs +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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. Par exemple : + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + Définissez les fonctions middleware de traitement d'erreurs de la même manière que les autres fonctions middleware, à l'exception près que les fonctions de traitement d'erreurs se composent de quatre arguments et non de trois : +`(err, req, res, next)`. Par exemple : + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +Si vous disposez d'un gestionnaire de routage avec plusieurs fonctions callback, vour pouvez utiliser le paramètre `route` pour passer au gestionnaire de routage suivant. +Par exemple : + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +Si vous transmettez tout à la fonction `next()` (sauf la chaîne `'route'`), Express considère la demande en cours +comme étant erronée et ignorera tout routage de gestion non lié à une erreur et toute fonction middleware restants. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. Par exemple : + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. Par exemple : + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +You could also use a chain of handlers to rely on synchronous error +catching, by reducing the asynchronous code to something trivial. Par exemple : + +```js +app.get('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## Le gestionnaire de traitement d'erreurs par défaut + +Express propose un gestionnaire d'erreurs intégré, qui traite toutes les erreurs qui pourraient survenir dans l'application. Cette fonction middleware de traitement d'erreurs par défaut est ajoutée à la fin de la pile de fonctions middleware. + +Si vous transmettez l'erreur à `next()` et que vous ne voulez pas la gérer dans +un gestionnaire d'erreurs, elle sera gérée par le gestionnaire d'erreurs intégré ; l'erreur sera alors écrite dans le client avec la +trace de pile. La trace de pile n'est pas incluse dans l'environnement de production. + +
      +Définissez la variable d'environnement `NODE_ENV` sur `production` afin d'exécuter l'application en mode 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. + +Si vous appelez `next()` avec une erreur après avoir démarré l'écriture de la +réponse (par exemple, si vous rencontrez une erreur lors de la diffusion en flux de la +réponse au client) le gestionnaire de traitement d'erreurs par défaut Express ferme la +connexion et met la demande en échec. + +De ce fait, lorsque vous ajoutez un gestionnaire d'erreurs personnalisé, vous devriez déléguer +les mécanismes de gestion d'erreur par défaut à Express, lorsque les en-têtes +ont déjà été envoyés au client : + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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)`. Par exemple : ```js @@ -26,7 +208,10 @@ Définissez le middleware de traitement d'erreurs en dernier, après les autres const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -35,14 +220,16 @@ app.use((err, req, res, next) => { Les réponses issues d'une fonction middleware peuvent être au format de votre choix, par exemple une page d'erreur HTML, un simple message ou une chaîne JSON. -A des fins organisationnelles (et d'infrastructure de niveau supérieur), vous pouvez définir plusieurs fonctions middleware de traitement d'erreurs, tout comme vous le feriez avec d'autres fonctions middleware ordinaires. -Par exemple, si vous vouliez définir un gestionnaire d'erreurs pour les demandes réalisées avec `XHR` et pour celles réalisées sans, vous pourriez utiliser les commandes suivantes : +A des fins organisationnelles (et d'infrastructure de niveau supérieur), vous pouvez définir plusieurs fonctions middleware de traitement d'erreurs, tout comme vous le feriez avec d'autres fonctions middleware ordinaires. Par exemple, si vous vouliez définir un gestionnaire d'erreurs pour les demandes réalisées avec `XHR` et pour celles réalisées sans, vous pourriez utiliser les commandes suivantes : ```js const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -60,6 +247,8 @@ function logErrors (err, req, res, next) { Egalement dans cet exemple, `clientErrorHandler` est défini comme suit ; dans ce cas, l'erreur est explicitement transmise à la fonction suivante : +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) { if (req.xhr) { @@ -69,6 +258,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + La fonction "catch-all" `errorHandler` peut être mise en oeuvre comme suit : ```js @@ -78,19 +268,16 @@ function errorHandler (err, req, res, next) { } ``` -Si vous transmettez tout à la fonction `next()` (sauf la chaîne `'route'`), Express considère la demande en cours -comme étant erronée et ignorera tout routage de gestion non lié à une erreur et toute fonction middleware restants. Si vous voulez gérer cette erreur de quelque façon que ce soit, vous devrez créer -une route de gestion d'erreur tel que décrit dans la section suivante. - -Si vous disposez d'un gestionnaire de routage avec plusieurs fonctions callback, vour pouvez utiliser le paramètre `route` pour passer au gestionnaire de routage suivant. Par exemple : +If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. Par exemple : ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -99,40 +286,9 @@ app.get('/a_route_behind_paywall', }) }) ``` -Dans cet exemple, le gestionnaire `getPaidContent` sera ignoré, mais tous les gestionnaires restants dans `app` pour `/a_route_behind_paywall` continueront d'être exécutés. -
      -Les appels `next()` et `next(err)` indiquent que le gestionnaire en cours a fini et quel est son état. -`next(err)` ignorera tous les gestionnaires restants dans la chaîne, sauf ceux définis pour gérer les erreurs tel que décrit ci-dessus. -
      - -## Le gestionnaire de traitement d'erreurs par défaut - -Express propose un gestionnaire d'erreurs intégré, qui traite toutes les erreurs qui pourraient survenir dans l'application. Cette fonction middleware de traitement d'erreurs par défaut est ajoutée à la fin de la pile de fonctions middleware. - -Si vous transmettez l'erreur à `next()` et que vous ne voulez pas la gérer dans -un gestionnaire d'erreurs, elle sera gérée par le gestionnaire d'erreurs intégré ; l'erreur sera alors écrite dans le client avec la -trace de pile. La trace de pile n'est pas incluse dans l'environnement de production. +Dans cet exemple, le gestionnaire `getPaidContent` sera ignoré, mais tous les gestionnaires restants dans `app` pour `/a_route_behind_paywall` continueront d'être exécutés.
      -Définissez la variable d'environnement `NODE_ENV` sur `production` afin d'exécuter l'application en mode production. +Les appels `next()` et `next(err)` indiquent que le gestionnaire en cours a fini et quel est son état. `next(err)` ignorera tous les gestionnaires restants dans la chaîne, sauf ceux définis pour gérer les erreurs tel que décrit ci-dessus.
      - -Si vous appelez `next()` avec une erreur après avoir démarré l'écriture de la -réponse (par exemple, si vous rencontrez une erreur lors de la diffusion en flux de la -réponse au client) le gestionnaire de traitement d'erreurs par défaut Express ferme la -connexion et met la demande en échec. - -De ce fait, lorsque vous ajoutez un gestionnaire d'erreurs personnalisé, vous devriez déléguer -les mécanismes de gestion d'erreur par défaut à Express, lorsque les en-têtes -ont déjà été envoyés au client : - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/fr/guide/migrating-4.md b/fr/guide/migrating-4.md old mode 100755 new mode 100644 index 4d07905aaa..ef764dadf2 --- a/fr/guide/migrating-4.md +++ b/fr/guide/migrating-4.md @@ -1,10 +1,10 @@ --- layout: page title: Migration vers 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. menu: guide lang: fr -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. +redirect_from: " " --- # Migration vers Express 4 @@ -26,7 +26,7 @@ Cet article couvre : De nombreuses modifications importantes ont été faites dans Express 4 :
        -
      • Modification du système principal et middleware d'Express. Les dépendances Connect et des middleware intégrés ont été supprimées, vous devez donc ajouter les middleware vous-même. +
      • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
      • Modifications du système de routage.
      • Autres modifications diverses.
      • @@ -34,8 +34,8 @@ De nombreuses modifications importantes ont été faites dans Express 4 : Voir aussi : -* [Nouvelles fonctions dans la version 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) -* [Migration de la version 3.x vers 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) +- [Nouvelles fonctions dans la version 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) +- [Migration de la version 3.x vers 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)

        Modification du système principal et middleware d'Express @@ -55,7 +55,7 @@ middleware requis pour exécuter votre application. Procédez comme suit : La table suivante répertorie le middelware Express 3 et ces équivalents dans Express 4. - + @@ -87,7 +87,7 @@ La table suivante répertorie le middelware Express 3 et ces équivalents dans E -
        Express 3Express 4
        Express 3Express 4
        express.bodyParser body-parser + multer
        serve-index
        express.static serve-static
        + Vous trouverez ici la [liste complète](https://github.com/senchalabs/connect#middleware) du middleware Express 4. @@ -101,11 +101,12 @@ Dans la version 4 vous pouvez utilisez un paramètre variable pour définir le c Par exemple : ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

        Le système de routage

        @@ -117,8 +118,9 @@ La façon de définir des routes n'a pas changé mais le système de routage pos pour vous aider à organiser vos routes : {: .doclist } -* Une nouvelle méthode, `app.route()`, permettant de créer des gestionnaires de routage sous forme de chaîne pour un chemin de routage. -* Une nouvelle classe, `express.Router`, permettant de créer des gestionnaires de routage modulaires pouvant être montés. + +- Une nouvelle méthode, `app.route()`, permettant de créer des gestionnaires de routage sous forme de chaîne pour un chemin de routage. +- Une nouvelle classe, `express.Router`, permettant de créer des gestionnaires de routage modulaires pouvant être montés.

        méthode app.route()

        @@ -128,13 +130,13 @@ Voici quelques exemples de gestionnaires de chemin de chaînage définis à l'ai ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -154,16 +156,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -175,7 +177,7 @@ Puis, chargez le module de routage dans l'application : ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -190,7 +192,7 @@ Autres modifications Le tableau suivant répertorie les autres modifications mineures mais importantes dans Express 4 : - + @@ -248,7 +250,7 @@ Ne résout plus les adresses URL relatives. `req.params` @@ -300,7 +302,7 @@ Cette fonctionnalité se limite désormais à définir la valeur de cookie de ba `res.cookie()` pour plus de fonctionnalités. -
        Objet Description
        -Anciennement un tableau ; il s'agit dorénavant d'un objet. +Was an array; now an object.
        +

        Exemple de migration d'application

        @@ -344,7 +346,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -382,15 +384,15 @@ $ npm install serve-favicon morgan method-override express-session body-parser m Apportez les modifications suivantes à `app.js` : 1. Les fonctions Express Middleware intégrées `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` et - `express.errorHandler` ne sont plus disponibles sur l'objet - `express`. Vous devez installer leurs fonctions alternatives - manuellement et les charger dans l'application. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` et + `express.errorHandler` ne sont plus disponibles sur l'objet + `express`. Vous devez installer leurs fonctions alternatives + manuellement et les charger dans l'application. 2. Vous ne devez plus charger la fonction `app.router`. - Il ne s'agit pas d'un objet d'application Express 4 valide. Supprimez le code - `app.use(app.router);`. + Il ne s'agit pas d'un objet d'application Express 4 valide. Supprimez le code + `app.use(app.router);`. 3. Assurez-vous que les fonctions middleware sont chargées dans l'ordre correct - chargez `errorHandler` après avoir chargé les routes d'application. @@ -413,7 +415,7 @@ Le fait d'exécuter la commande `npm` ci-dessus mettra à jour `package.json` co "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -479,7 +481,7 @@ server.listen(app.get('port'), () => { A mois que vous deviez utiliser le module `http` (socket.io/SPDY/HTTPS) directement, vous n'avez pas à le charger et l'application peut être démarrée comme suit : ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -496,13 +498,13 @@ $ node . ``` Chargez [http://localhost:3000](http://localhost:3000) - et voyez comment la page d'accueil est générée par Express 4. +et voyez comment la page d'accueil est générée par Express 4.

        Mise à niveau vers le générateur d'applications Express 4

        L'outil de ligne de commande qui permet de générer une application Express est toujours - `express`, mais pour effectuer la mise à niveau vers la nouvelle version, vous devez désinstaller - le générateur d'applications Express 3 puis installer la nouvelle version d'`express-generator`. +`express`, mais pour effectuer la mise à niveau vers la nouvelle version, vous devez désinstaller +le générateur d'applications Express 3 puis installer la nouvelle version d'`express-generator`.

        Installation

        @@ -515,12 +517,14 @@ $ npm uninstall -g express En fonction de la configuration de vos privilèges de fichier et de répertoire, vous devrez exécuter cette commande avec `sudo`.A présent, installez le nouveau générateur : +Now install the new generator: + ```bash $ npm install -g express-generator ``` En fonction de la configuration de vos privilèges de fichier et de répertoire, -vous devrez exécuter cette commande avec `sudo`. +vous devrez exécuter cette commande avec `sudo`.A présent, installez le nouveau générateur : Désormais, la commande `express` sur votre système est mise à jour vers le générateur Express 4. @@ -529,9 +533,10 @@ Désormais, la commande `express` sur votre système est mise à jour vers le g Les options et les syntaxe de commande restent généralement identiques, avec les exceptions suivantes : {: .doclist } -* L'option `--sessions` a été supprimée. -* L'option `--jshtml` a été supprimée. -* L'option `--hogan` a été ajoutée à la prise en charge de [Hogan.js](http://twitter.github.io/hogan.js/). + +- L'option `--sessions` a été supprimée. +- L'option `--jshtml` a été supprimée. +- L'option `--hogan` a été ajoutée à la prise en charge de [Hogan.js](http://twitter.github.io/hogan.js/).

        Exemple

        @@ -574,7 +579,7 @@ supprimez la ligne `module.exports = app;` à la fin du fichier ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -588,5 +593,5 @@ var debug = require('debug')('app4') Ensuite, modifiez `"start": "node ./bin/www"` dans le fichier `package.json` en `"start": "node app.js"`. Vous avez à présent déplacé la fonctionnalité depuis `./bin/www` de nouveau -dans `app.js`. Cette modification n'est pas recommandée, mais l'exercice vous aide à comprendre le mode de fonctionnement +dans `app.js`. Cette modification n'est pas recommandée, mais l'exercice vous aide à comprendre le mode de fonctionnement du fichier `./bin/www` et la raison pour laquelle le fichier `app.js` ne se lance plus seul. diff --git a/fr/guide/migrating-5.md b/fr/guide/migrating-5.md old mode 100755 new mode 100644 index ca78f1cc43..6ff8a73161 --- a/fr/guide/migrating-5.md +++ b/fr/guide/migrating-5.md @@ -1,32 +1,25 @@ --- layout: page title: Migration vers Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: fr -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # Migration vers Express 5

        Présentation

        -Express 5.0 est encore au stade d'édition alpha mais voici un -aperçu des modifications qui figureront dans l'édition et la procédure -de migration de l'application Express 4 vers Express 5. - Express 5 n'est pas très différent d'Express 4 : les modifications apportées à l'API ne sont pas aussi importantes qu'entre -les versions 3.0 et 4.0. -Bien que l'API de base reste identique, des modifications radicales ont été apportées ; en d'autres termes, un programme Express 4 risque de ne pas fonctionner si +les versions 3.0 et 4.0. Bien que l'API de base reste identique, des modifications radicales ont été apportées ; en d'autres termes, un programme Express 4 risque de ne pas fonctionner si vous le mettez à jour pour utiliser Express 5. -Pour installer la dernière version alpha et pour -prévisualiser Express 5, entrez la commande suivante dans le -répertoire principal de l'application : +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` Vous pouvez alors exécuter les tests automatisés pour voir les @@ -36,13 +29,25 @@ exécutez votre application pour détecter les erreurs qui se produisent. Vous saurez tout de suite si l'application utilise des méthodes ou des propriétés. -

        Modifications dans Express 5

        +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` -Voici la liste des modifications (par rapport à l'édition alpha -2) qui vous concerneront en tant qu'utilisateur d'Express. -Consultez la -[demande d'extraction](https://github.com/expressjs/express/pull/2237) -pour une liste de toutes les fonctions planifiées. +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

        Modifications dans Express 5

        **Méthodes et propriétés supprimées** @@ -55,26 +60,40 @@ nom pour app.param(name, fn)
      • req.param(name)
      • res.json(obj, status)
      • res.jsonp(obj, status)
      • +
      • res.redirect('back') and res.location('back')
      • +
      • res.redirect(url, status)
      • res.send(body, status)
      • res.send(status)
      • res.sendfile()
      • +
      • router.param(fn)
      • +
      • express.static.mime
      • +
      • express:router debug logs
      -**Modifié** +**Améliorations** -**Améliorations** +**Modifié** -

      Méthodes et propriétés supprimées

      +### Méthodes et propriétés supprimées Si vous utilisez une de ces méthodes ou propriétés dans votre application, elle tombera en panne. Vous devrez donc modifier votre @@ -91,9 +110,30 @@ Initialement, `del` était utilisé au lieu de `delete` car `delete` est un mot clé réservé dans JavaScript. Cependant, à partir d'ECMAScript 6, `delete` et les autres mots clés réservés peuvent -être utilisés en toute légalité comme noms de propriété. Vous pouvez lire la -discussion qui a donné lieu à l'obsolescence de la fonction -`app.del` ici. +être utilisés en toute légalité comme noms de propriété. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

      app.param(fn)

      @@ -107,14 +147,45 @@ version 4.11.0 et Express 5 ne la prend plus en charge. Les noms de méthode suivants ont été mis au pluriel. Dans Express 4, l'utilisation des anciennes méthodes ont généré un avertissement d'obsolescence. Express 5 ne les prend plus du tout en charge : +`req.acceptsLanguage()` est remplacé par +`req.acceptsLanguages()`. + `req.acceptsCharset()` est remplacé par `req.acceptsCharsets()`. `req.acceptsEncoding()` est remplacé par `req.acceptsEncodings()`. -`req.acceptsLanguage()` est remplacé par -`req.acceptsLanguages()`. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

      Signe deux-points (:) de tête dans le nom de la fonction app.param(name, fn)

      @@ -136,6 +207,37 @@ d'extraction des données de formulaire a été supprimée. Vous devrez désormais rechercher spécifiquement le nom du paramètre soumis dans l'objet `req.params`, `req.body` ou `req.query`. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

      res.json(obj, status)

      Express 5 ne prend plus en charge la signature @@ -144,6 +246,20 @@ statut et enchaînez-le à la méthode `res.json()` comme suit : `res.status(status).json(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

      res.jsonp(obj, status)

      Express 5 ne prend plus en charge la signature @@ -151,17 +267,89 @@ Express 5 ne prend plus en charge la signature statut et enchaînez-le à la méthode `res.jsonp()` comme suit : `res.status(status).jsonp(obj)`. -

      res.send(body, status)

      +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

      res.redirect(url, status)

      Express 5 ne prend plus en charge la signature `res.send(obj, status)`. A la place, définissez le statut et enchaînez-le à la méthode `res.send()` comme suit : `res.status(status).send(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

      res.redirect('back') and res.location('back')

      + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

      res.send(body, status)

      + +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

      res.send(status)

      -Express 5 ne prend plus en charge la signature -res.send(statut), où *`statut`* +Express 5 ne prend plus en charge la signature res.send(statut), où _`statut`_ est un nombre. A la place, utilisez la fonction `res.sendStatus(statusCode)` qui définit le code de statut de l'en-tête de réponse HTTP et envoie @@ -170,19 +358,177 @@ Si vous devez envoyer un nombre à l'aide de la fonction `res.send()`, mettez ce nombre entre guillemets pour qu'Express ne l'interprète pas comme une tentative d'utilisation de l'ancienne signature non prise en charge. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +``` +

      res.sendfile()

      La fonction `res.sendfile()` a été remplacée par une version CamelCase `res.sendFile()` dans Express 5. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

      router.param(fn)

      + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. Elle est obsolète depuis la +version 4.11.0 et Express 5 ne la prend plus en charge. + +

      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. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

      express:router debug logs

      + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

      Modifié

      +

      Path route matching syntax

      + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. Par exemple : + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

      Rejected promises handled from middleware and handlers

      + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

      express.urlencoded

      + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

      app.listen

      + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +Par exemple : + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

      app.router

      L'objet `app.router`, qui a été supprimé dans Express 4, est revenu dans Express 5. Dans la version, cet objet n'est qu'une référence dans le routeur Express de base, contrairement à Express 3, où une application devait le charger explicitement. +

      req.body

      + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

      req.host

      Dans Express 4, la `req.host` retirait de @@ -190,13 +536,21 @@ manière incorrecte le numéro de port s'il était présent. Dans Express 5, ce

      req.query

      -Dans Express 4.7 et à partir d'Express 5, l'option -d'analyseur de requêtes peut accepter `false` pour -désactiver l'analyse syntaxique de chaîne de requête lorsque vous -souhaitez utiliser votre propre fonction pour la logique d'analyse -syntaxique de chaîne de requête. +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". -

      Améliorations

      +

      res.clearCookie

      + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

      res.status

      + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

      res.vary

      + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### Améliorations

      res.render()

      @@ -204,3 +558,7 @@ Cette méthode impose désormais un comportement asynchrone pour tous les moteurs de vue. Cela évite les bogues générés par les moteurs de vue qui avaient une implémentation synchrone et qui ne prenaient pas en compte l'interface recommandée. + +

      Brotli encoding support

      + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/fr/guide/overriding-express-api.md b/fr/guide/overriding-express-api.md new file mode 100644 index 0000000000..66655cc9f8 --- /dev/null +++ b/fr/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: fr +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/fr/guide/routing.md b/fr/guide/routing.md old mode 100755 new mode 100644 index 99fcf868f8..b429d68e3e --- a/fr/guide/routing.md +++ b/fr/guide/routing.md @@ -1,17 +1,28 @@ --- layout: page title: Routage Express +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: fr -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # Routage -*Routage* fait référence à la définition de points finaux d'application (URI) et à la façon dont ils répondent aux demandes client. +_Routage_ fait référence à la définition de points finaux d'application (URI) et à la façon dont ils répondent aux demandes client. Pour une introduction au routage, voir [Basic routing](/{{ page.lang }}/starter/basic-routing.html). +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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. + Le code suivant est un exemple de routage très basique. ```js @@ -42,17 +53,11 @@ app.post('/', (req, res) => { }) ``` -Express prend en charge les méthodes de routage suivantes qui correspondent aux méthodes HTTP : `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search`, and `connect`. - -
      -Pour router des méthodes qui se traduisent par des noms de variables JavaScript non valides, utilisez la notation entre crochets. For example, -`app['m-search']('/', function ...` -
      +Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). Il existe une méthode de routage spéciale, `app.all()`, qui n'est pas dérivée d'une méthode HTTP. Cette méthode est utilisée pour charger des fonctions middleware à un chemin d'accès pour toutes les méthodes de demande. -Dans l'exemple suivant, le gestionnaire sera exécuté pour les demandes de "/secret", que vous utilisiez GET, POST, PUT, DELETE ou toute autre méthode de demande HTTP prise en charge dans le [module http](https://nodejs.org/api/http.html#http_http_methods). - ```js app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') @@ -64,15 +69,32 @@ app.all('/secret', (req, res, next) => { Les chemins de routage, combinés à une méthode de demande, définissent les noeuds finaux sur lesquels peuvent être effectuées les demandes. Les chemins de routage peuvent être des chaînes, des masques de chaîne ou des expressions régulières. -
      - Express utilise [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) pour faire correspondre les chemins de routage ; pour connaître toutes les façons de définir des chemins de routage, voir la documentation path-to-regexp. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) est un outil pratique permettant de tester des routes Express de base, bien qu'il ne prenne pas en charge le filtrage par motif. -
      +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
      -Les chaînes de requête ne font pas partie du chemin de routage. -
      +{% include admonitions/caution.html content=caution-character %} + +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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 Route Tester](http://forbeslindesay.github.io/express-route-tester/) est un outil pratique permettant de tester des routes Express de base, bien qu'il ne prenne pas en charge le filtrage par motif. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. -Il s'agit d'exemples de chemins de routage basés sur des chaînes. +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Il s'agit d'exemples de chemins de routage basés sur des chaînes. Ce chemin de routage fera correspondre des demandes à la route racine, `/`. @@ -98,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -Il s'agit d'exemples de chemins de routage basés sur des masques de chaîne. +### Il s'agit d'exemples de chemins de routage basés sur des masques de chaîne. + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} Ce chemin de routage fait correspondre `acd` et `abcd`. @@ -132,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
      -Les caractères ?, +, * et () sont des sous-ensembles de leur expression régulière équivalente. Le trait d'union (-) et le point (.) sont interprétés littéralement par des chemins d'accès basés sur des chaînes. -
      - -Exemples de chemins de routage basés sur des expressions régulières : +### Exemples de chemins de routage basés sur des expressions régulières : Ce chemin de routage fera correspondre tout élément dont le nom de chemin comprend la lettre "a". @@ -154,13 +176,80 @@ app.get(/.*fly$/, (req, res) => { }) ``` +

      +Les chaînes de requête ne font pas partie du chemin de routage. +

      + +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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
      +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} +

      Gestionnaires de routage

      Vous pouvez fournir plusieurs fonctions de rappel qui se comportent comme des [middleware](/{{ page.lang }}/guide/using-middleware.html) pour gérer une demande. La seule exception est que ces fonctions de rappel peuvent faire appel à `next('route')` pour ignorer les rappels de route restants. Vous pouvez utiliser ce mécanisme pour imposer des conditions préalables sur une route, puis passer aux routes suivantes si aucune raison n'est fournie pour traiter la route actuelle. Les gestionnaires de route se trouvent sous la forme d'une fonction, d'un tableau de fonctions ou d'une combinaison des deux, tel qu'indiqué dans les exemples suivants. -Une fonction de rappel unique peut traiter une route. Par exemple : +Une fonction de rappel unique peut traiter une route. Par exemple : ```js app.get('/example/a', (req, res) => { @@ -178,7 +267,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -Un tableau de fonctions de rappel peut traiter une route. Par exemple : + +Un tableau de fonctions de rappel peut traiter une route. Par exemple : ```js const cb0 = function (req, res, next) { @@ -198,7 +288,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -Une combinaison de fonctions indépendantes et des tableaux de fonctions peuvent gérer une route. Par exemple : +Une combinaison de fonctions indépendantes et des tableaux de fonctions peuvent gérer une route. Par exemple : ```js const cb0 = function (req, res, next) { @@ -223,17 +313,17 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => { Les méthodes de l'objet de réponse (`res`) décrites dans le tableau suivant peuvent envoyer une réponse au client, et mettre fin au cycle de demande-réponse. Si aucune de ces méthodes n'est appelée par un gestionnaire de routage, la demande du client restera bloquée. -| Méthode | Description -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Vous invite à télécharger un fichier. -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Met fin au processus de réponse. -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envoie une réponse JSON. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Envoie une réponse JSON avec une prise en charge JSONP. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redirige une demande. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Génère un modèle de vue. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envoie une réponse de divers types. -| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | Envoie une réponse sous forme de flux d'octets. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Définit le code de statut de réponse et envoie sa représentation sous forme de chaîne comme corps de réponse. +| Méthode | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Vous invite à télécharger un fichier. | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Met fin au processus de réponse. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envoie une réponse JSON. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Envoie une réponse JSON avec une prise en charge JSONP. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redirige une demande. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Génère un modèle de vue. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envoie une réponse de divers types. | +| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | Send a file as an octet stream. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Définit le code de statut de réponse et envoie sa représentation sous forme de chaîne comme corps de réponse. |

      app.route()

      @@ -268,10 +358,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -289,9 +381,15 @@ Puis, chargez le module de routage dans l'application : ```js const birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` L'application pourra dorénavant gérer des demandes dans `/birds` et `/birds/about`, et appeler la fonction middleware `timeLog` spécifique à la 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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/fr/guide/using-middleware.md b/fr/guide/using-middleware.md old mode 100755 new mode 100644 index b5797a323e..9ef30e0f26 --- a/fr/guide/using-middleware.md +++ b/fr/guide/using-middleware.md @@ -1,34 +1,34 @@ --- layout: page title: Utilisation de middleware Express +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: fr -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # Utilisation de middleware Express est une infrastructure web middleware et de routage, qui a des fonctions propres minimes : une application Express n'est ni plus ni moins qu'une succession d'appels de fonctions middleware. -Les fonctions de *middleware* sont des fonctions qui peuvent accéder à l'[objet Request](/{{ page.lang }}/4x/api.html#req) (`req`), l'[objet response](/{{ page.lang }}/4x/api.html#res) (`res`) et à la fonction middleware suivant dans le cycle demande-réponse de l'application. La fonction middleware suivant est couramment désignée par une variable nommée `next`. +Les fonctions de _middleware_ sont des fonctions qui peuvent accéder à l'[objet Request](/{{ page.lang }}/4x/api.html#req) (`req`), l'[objet response](/{{ page.lang }}/4x/api.html#res) (`res`) et à la fonction middleware suivant dans le cycle demande-réponse de l'application. La fonction middleware suivant est couramment désignée par une variable nommée `next`. Les fonctions middleware effectuent les tâches suivantes : -* Exécuter tout type de code. -* Apporter des modifications aux objets de demande et de réponse. -* Terminer le cycle de demande-réponse. -* Appeler la fonction middleware suivant dans la pile. +- Exécuter tout type de code. +- Apporter des modifications aux objets de demande et de réponse. +- Terminer le cycle de demande-réponse. +- Appeler la fonction middleware suivant dans la pile. Si la fonction middleware en cours ne termine pas le cycle de demande-réponse, elle doit appeler la fonction `next()` pour transmettre le contrôle à la fonction middleware suivant. Sinon, la demande restera bloquée. Une application Express peut utiliser les types de middleware suivants : - - [Middleware niveau application](#middleware.application) - - [Middleware niveau routeur](#middleware.router) - - [Middleware de traitement d'erreurs](#middleware.error-handling) - - [Middleware intégré](#middleware.built-in) - - [Middleware tiers](#middleware.third-party) +- [Middleware niveau application](#middleware.application) +- [Middleware niveau routeur](#middleware.router) +- [Middleware de traitement d'erreurs](#middleware.error-handling) +- [Middleware intégré](#middleware.built-in) +- [Middleware tiers](#middleware.third-party) Vous pouvez charger le middleware niveau application et niveau routeur à l'aide d'un chemin de montage facultatif. Vous pouvez également charger une série de fonctions middleware ensemble, ce qui crée une sous-pile du système de middleware à un point de montage. @@ -40,6 +40,7 @@ Liez le middleware niveau application à une instance de l'objet [app object](/{ Cet exemple illustre une fonction middleware sans chemin de montage. La fonction est exécutée à chaque fois que l'application reçoit une demande. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -93,12 +94,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` Pour ignorer les fonctions middleware issues d'une pile de middleware de routeur, appelez `next('route')` pour passer le contrôle à la prochaine route. -**REMARQUE **: `next('route')` ne fonctionnera qu'avec les fonctions middleware qui ont été chargées via les fonctions `app.METHOD()` ou `router.METHOD()`. + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} Cet exemple illustre une sous-pile de middleware qui gère les demandes GET adressées au chemin `/user/:id`. @@ -107,15 +115,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +Voici un exemple d'utilisation de la fonction middleware `express.static` avec un objet options élaboré : + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -126,11 +155,13 @@ Le middleware niveau routeur fonctionne de la même manière que le middleware n ```js const router = express.Router() ``` + Chargez le middleware niveau routeur par le biais des fonctions `router.use()` et `router.METHOD()`. Le code d'exemple suivant réplique le système de middleware illustré ci-dessus pour le middleware niveau application, en utilisant un middleware niveau routeur : ```js +const express = require('express') const app = express() const router = express.Router() @@ -154,7 +185,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -169,10 +200,36 @@ router.get('/user/:id', (req, res, next) => { // mount the router on the app app.use('/', router) ``` + +Pour obtenir plus de détails sur la fonction `serve-static` et ses options, reportez-vous à la documentation [serve-static](https://github.com/expressjs/serve-static). + +Cet exemple illustre une sous-pile de middleware qui gère les demandes GET adressées au chemin `/user/:id`. + +```js +const express = require('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) +}) +``` +

      Middleware de traitement d'erreurs

      -Le middleware de traitement d'erreurs comporte toujours *quatre* arguments. Vous devez fournir quatre arguments pour l'identifier comme une fonction middleware de traitement d'erreurs. Même si vous n'avez pas besoin d'utiliser l'objet `next`, vous devez le spécifier pour maintenir la signature. Sinon, l'objet `next` sera interprété comme un middleware ordinaire et n'arrivera pas à gérer les erreurs. +Le middleware de traitement d'erreurs comporte toujours *quatre* arguments. Vous devez fournir quatre arguments pour l'identifier comme une fonction middleware de traitement d'erreurs. Même si vous n'avez pas besoin d'utiliser l'objet `next`, vous devez le spécifier pour maintenir la signature. Sinon, l'objet `next` sera interprété comme un middleware ordinaire et n'arrivera pas à gérer les erreurs.
      Définissez les fonctions middleware de traitement d'erreurs de la même façon que d'autres fonctions middleware, à l'exception près qu'il faudra 4 arguments au lieu de 3, et plus particulièrement avec la signature `(err, req, res, next)`) : @@ -191,52 +248,11 @@ Pour obtenir des détails sur le middleware de traitement d'erreurs, reportez-vo Depuis la version 4.x, Express ne dépend plus de [Connect](https://github.com/senchalabs/connect). A l'exception de `express.static`, toutes les fonctions middleware précédemment incluses à Express' font désormais partie de modules distincts. Veuillez vous reporter à [la liste des fonctions middleware](https://github.com/senchalabs/connect#middleware). -

      express.static(root, [options])

      - -La seule fonction middleware intégrée dans Express est `express.static`. Cette fonction est basée sur [serve-static](https://github.com/expressjs/serve-static) et a la responsabilité de servir les actifs statiques d'une application Express. +La seule fonction middleware intégrée dans Express est `express.static`. -L'argument `root` spécifie le répertoire racine à partir duquel servir les actifs statiques. - -L'objet `options` facultatif peut avoir les propriétés suivantes : - -| Propriété | Description | Type | Valeur par défaut | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Option pour servir les fichiers dotfiles. Les valeurs possibles sont "allow", "deny" et "ignore" | Chaîne | "ignore" | -| `etag` | Activer ou désactiver la génération etag | Booléen | `true` | -| `extensions` | Définit l'extension de fichier de rechange. | Tableau | `[]` | -| `index` | Envoie le fichier d'index du répertoire. Utilisez `false` pour désactiver l'indexation de répertoire. | Mix | "index.html" | - `lastModified` | Définit l'en-tête `Last-Modified` sur la date de dernière modification du fichier dans le système d'exploitation. Les valeurs possibles sont `true` ou `false`. | Booléen | `true` | -| `maxAge` | Définit la propriété max-age de l'en-tête Cache-Control, en millisecondes ou par une chaîne au format [ms format](https://www.npmjs.org/package/ms) | Numérique | 0 | -| `redirect` | Réapplique les barres obliques "/" lorsque le chemin d'accès est un répertoire. | Booléen | `true` | -| `setHeaders` | Fonction pour définir les en-têtes HTTP à servir avec le fichier. | Fonction | | - -Voici un exemple d'utilisation de la fonction middleware `express.static` avec un objet options élaboré : - -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -Vous pouvez avoir plusieurs répertoires statiques par application : - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` - -Pour obtenir plus de détails sur la fonction `serve-static` et ses options, reportez-vous à la documentation [serve-static](https://github.com/expressjs/serve-static). +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**

      Middleware tiers

      diff --git a/fr/guide/using-template-engines.md b/fr/guide/using-template-engines.md old mode 100755 new mode 100644 index 4dbd3482f3..1ff2075c6e --- a/fr/guide/using-template-engines.md +++ b/fr/guide/using-template-engines.md @@ -1,18 +1,25 @@ --- layout: page title: Utilisation de moteurs de modèles avec Express +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: fr -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- # Utilisation de moteurs de modèles avec Express -Pour qu'Express puisse afficher le rendu des fichiers modèles, vous devez définir les paramètres d'application suivants : +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. -* `views`, le répertoire dans lequel se trouvent les fichiers modèles. Par exemple : `app.set('views', './views')` -* `view engine`, le moteur de modèle à utiliser. Par exemple : `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, le répertoire dans lequel se trouvent les fichiers modèles. Par exemple : `app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, le moteur de modèle à utiliser. Par exemple : `app.set('view engine', 'pug')` Ensuite, installez le package npm du moteur de modèle correspondant : @@ -24,6 +31,7 @@ $ npm install pug --save Les moteurs de modèles conformes à Express tels que Pug exportent une fonction nommée `__express(filePath, options, callback)`, qui est appelée par la fonction `res.render()` pour générer le code de modèle. Certaines moteurs de modèles ne suivent pas cette convention. La bibliothèque [Consolidate.js](https://www.npmjs.org/package/consolidate) suit cette convention en mappant tous les moteurs de modèles Node.js répandus, et fonctionne donc parfaitement avec Express. +
    Une fois le moteur de vue défini, vous n'avez pas à spécifier le moteur ou à charger le module de moteur de modèles dans votre application ; Express charge le module en interne, comme indiqué ci-dessous (pour l'exemple ci-dessus). @@ -52,4 +60,4 @@ app.get('/', (req, res) => { Lorsque vous faites une demande vers la page d'accueil, le fichier `index.pug` est généré en HTML. -Pour en savoir plus sur le fonctionnement des moteurs de modèle dans Express, voir : ["Développement de moteurs de modèles pour Express"](/{{ page.lang }}/advanced/developing-template-engines.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/fr/guide/writing-middleware.md b/fr/guide/writing-middleware.md old mode 100755 new mode 100644 index 40e79fff7f..4298c6900a --- a/fr/guide/writing-middleware.md +++ b/fr/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: Ecriture de middleware utilisable dans les applications Express +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: fr -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- # Ecriture de middleware utilisable dans les applications Express

    Présentation

    -Les fonctions de *middleware* sont des fonctions qui peuvent accéder à l'[objet Request](/{{ page.lang }}/4x/api.html#req) (`req`), l'[objet response](/{{ page.lang }}/4x/api.html#res) (`res`) et à la fonction middleware suivant dans le cycle demande-réponse de l'application. La fonction middleware suivant est couramment désignée par une variable nommée `next`. +Les fonctions de _middleware_ sont des fonctions qui peuvent accéder à l'[objet Request](/{{ page.lang }}/4x/api.html#req) (`req`), l'[objet response](/{{ page.lang }}/4x/api.html#res) (`res`) et à la fonction middleware suivant dans le cycle demande-réponse de l'application. La fonction middleware suivant est couramment désignée par une variable nommée `next`. Les fonctions middleware effectuent les tâches suivantes : -* Exécuter tout type de code. -* Apporter des modifications aux objets de demande et de réponse. -* Terminer le cycle de demande-réponse. -* Appeler le middleware suivant dans la pile. +- Exécuter tout type de code. +- Apporter des modifications aux objets de demande et de réponse. +- Terminer le cycle de demande-réponse. +- Appeler le middleware suivant dans la pile. Si la fonction middleware en cours ne termine pas le cycle de demande-réponse, elle doit appeler la fonction `next()` pour transmettre le contrôle à la fonction middleware suivant. Sinon, la demande restera bloquée. L'exemple suivant montre les éléments d'un appel de fonction middleware: - -
    -Elements of a middleware function call + + -
    Chemin (route) auquel la fonction middleware s'applique.
    @@ -43,31 +43,14 @@ L'exemple suivant montre les éléments d'un appel de fonction middleware:
    +Elements of a middleware function call -
    Méthode HTTP à laquelle la fonction middleware s'applique.
    +
    +
    Méthode HTTP à laquelle la fonction middleware s'applique.
    - +

    Exemple

    Voici un exemple d'une application Express "Hello World" simple, pour laquelle vous allez définir deux fonctions middleware : +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 const express = require('express') @@ -80,8 +63,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    Développement

    - +

    Middleware function myLogger

    Voici un exemple simple de fonction middleware appelée "myLogger". Cette fonction imprime simplement "LOGGED" lorsqu'une demande traverse l'application. La fonction middleware est affectée à une variable nommée `myLogger`. ```js @@ -92,7 +74,9 @@ const myLogger = function (req, res, next) { ```
    -Notez l'appel ci-dessus de la fonction `next()`, qui appelle la fonction middleware suivant dans l'application. La fonction `next()` ne fait pas partie du Node.js ou de l'API Express, mais c'est le troisième argument qui est transmis à la fonction middleware. La fonction `next()` peut porter n'importe quel nom, mais par convention elle est toujours appelée "next". Pour éviter toute confusion, il est préférable de respecter cette convention. +Notice the call above to `next()`. Notez l'appel ci-dessus de la fonction `next()`, qui appelle la fonction middleware suivant dans l'application. +La fonction `next()` ne fait pas partie du Node.js ou de l'API Express, mais c'est le troisième argument qui est transmis à la fonction middleware. La fonction `next()` peut porter n'importe quel nom, mais par convention elle est toujours appelée "next". +Pour éviter toute confusion, il est préférable de respecter cette convention.
    Pour charger la fonction middleware, appelez `app.use()` en spécifiant la fonction middleware. @@ -124,6 +108,8 @@ Si `myLogger` est chargé après la route au chemin racine, la demande ne l'atte La fonction middleware `myLogger` imprime simplement un message, puis traite la demande à la fonction middleware suivant dans la pile en appelant la fonction `next()`. +

    Middleware function requestTime

    + L'exemple suivant ajoute une propriété appelée `requestTime` à l'objet Request. Nous nommerons cette fonction middleware "requestTime". ```js @@ -154,8 +140,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + Si vous effectuez une demande à la racine de l'application, cette dernière affiche maintenant l'horodatage de la demande dans le navigateur. +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + Puisque vous avez accès à l'objet Request, à l'objet Response, à la fonction middleware suivant dans la pile et à l'API Node.js complète, le champ des possibles avec les fonctions middleware est infini. Pour plus d'informations sur les middleware Express, voir [Utilisation de middleware Express](/{{ page.lang }}/guide/using-middleware.html). + +

    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 +module.exports = 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') + +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. diff --git a/fr/resources/community.md b/fr/resources/community.md old mode 100755 new mode 100644 index 8604358695..6c289ec075 --- a/fr/resources/community.md +++ b/fr/resources/community.md @@ -1,27 +1,93 @@ --- layout: page title: Communauté Express -menu: ressources +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. +menu: resources lang: fr -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # Communauté -## Exemples +## Technical committee -Regardez des douzaines d'[exemples](https://github.com/expressjs/express/tree/master/examples) d'applications Express dans le référentiel qui couvre tous les sujets, en allant de l'authentification et la conception de l'interface de -programme d'application jusqu'à l'intégration du moteur modèle. +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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +Notre communauté si animée a créé une large gamme d'extensions, +[modules middleware](/{{ page.lang }}/resources/middleware.html) et des +infrastructures de niveau supérieur. + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## Problèmes Si vous êtes tombé sur ce que vous pensez être un bug, ou si vous voulez seulement faire une demande de fonctionnalité, ouvrez un ticket dans la [file d'attente d'incidents](https://github.com/expressjs/express/issues). -## Troisième partie +## Exemples -Notre communauté si animée a créé une large gamme d'extensions, -[modules middleware](/{{ page.lang }}/resources/middleware.html) et des -infrastructures de niveau supérieur. Consultez-les sur le [wiki](https://github.com/expressjs/express/wiki). +Regardez des douzaines d'[exemples](https://github.com/expressjs/express/tree/master/examples) d'applications Express dans le référentiel qui couvre tous les sujets, en allant de l'authentification et la conception de l'interface de +programme d'application jusqu'à l'intégration du moteur modèle. + +## 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. + +# Branding of Express.js + +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/fr/resources/contributing.md b/fr/resources/contributing.md new file mode 100644 index 0000000000..081fccbdf3 --- /dev/null +++ b/fr/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: fr +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/fr/resources/glossary.md b/fr/resources/glossary.md old mode 100755 new mode 100644 index fdb7aac08f..b3e9c69b6a --- a/fr/resources/glossary.md +++ b/fr/resources/glossary.md @@ -1,10 +1,10 @@ --- layout: page title: Glossaire Express +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. menu: resources lang: fr -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. +redirect_from: " " --- # Glossaire @@ -15,15 +15,11 @@ En général, un ou plusieurs programmes conçus pour réaliser des opérations ### API -Interface de programme d'application. Développez l'abréviation lorsqu'elle est utilisée pour la première fois. - -### demande - -Demande HTTP. Un client soumet un message de demande HTTP à un serveur, qui renvoie une réponse. La demande doit utiliser une des [méthodes de demande](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) telles que GET, POST... +Interface de programme d'application. Développez l'abréviation lorsqu'elle est utilisée pour la première fois. ### Express -Infrastructure Web minimaliste, souple et rapide pour les applications Node.js. En général, on préfère utiliser "Express" que "Express.js," bien que ce dernier soit acceptable. +Infrastructure Web minimaliste, souple et rapide pour les applications Node.js. En général, on préfère utiliser "Express" que "Express.js," bien que ce dernier soit acceptable. ### libuv @@ -31,19 +27,31 @@ Bibliothèque de prise en charge multiplateforme qui se centralise sur les E-S a ### middleware -Fonction qui est appelée par la couche de routage Express avant le gestionnaire de demande final, et qui se trouve entre une demande brute et la route finale prévue. Quelques points subtiles de terminologie autour des middleware : +Fonction qui est appelée par la couche de routage Express avant le gestionnaire de demande final, et qui se trouve entre une demande brute et la route finale prévue. Quelques points subtiles de terminologie autour des middleware : - * `var foo = require('middleware')` est appelé *demande* ou *utilisation* d'un module Node.js. Ensuite, l'instruction `var mw = foo()` renvoie généralement le middleware. - * `app.use(mw)` est appelé *ajout du middleware à la pile de processus global*. - * `app.get('/foo', mw, function (req, res) { ... })` est appelé *ajout du middleware à la pile de processus "GET /foo"*. +- `var foo = require('middleware')` est appelé _demande_ ou _utilisation_ d'un module Node.js. Ensuite, l'instruction `var mw = foo()` renvoie généralement le middleware. +- `app.use(mw)` est appelé _ajout du middleware à la pile de processus global_. +- `app.get('/foo', mw, function (req, res) { ... })` est appelé _ajout du middleware à la pile de processus "GET /foo"_. ### Node.js -Plateforme logicielle utilisée pour générer des applications réseau évolutives. Node.js utilise JavaScript comme langage de script, et atteint un rendement élevé via une E-S non bloquante et une boucle d'événements à une seule unité d'exécution. Voir [nodejs.org](http://nodejs.org/). **Note d'utilisation** : En général, "Node.js," "Node" par la suite. +Plateforme logicielle utilisée pour générer des applications réseau évolutives. Node.js utilise JavaScript comme langage de script, et atteint un rendement élevé via une E-S non bloquante et une boucle d'événements à une seule unité d'exécution. Voir [nodejs.org](http://nodejs.org/). **Note d'utilisation** : En général, "Node.js," "Node" par la suite. ### open-source, open source -Lorsqu'il est utilisé comme adjectif, utilisez la forme avec le trait d'union. Par exemple : "Il s'agit d'un logiciel open-source." Voir [Open-source software sur Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Remarque : Bien qu'open-source ne soit pas commun, nous utilisons les règles anglaises standard pour unir par un trait d'union un adjectif composé. +Lorsqu'il est utilisé comme adjectif, utilisez la forme avec le trait d'union. Par exemple : "Il s'agit d'un logiciel open-source." Voir [Open-source software sur Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). + +{% capture english-rules %} + +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. + +{% endcapture %} + +{% include admonitions/note.html content=english-rules %} + +### demande + +Demande HTTP. Un client soumet un message de demande HTTP à un serveur, qui renvoie une réponse. La demande doit utiliser une des [méthodes de demande](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) telles que GET, POST... ### réponse @@ -51,7 +59,7 @@ Réponse HTTP. Un serveur renvoie un message de réponse HTTP au client. La rép ### route -Partie de l'URL qui permet d'identifier une ressource. Par exemple, dans `http://foo.com/products/id`, "/products/id" est la route. +Partie de l'URL qui permet d'identifier une ressource. Par exemple, dans `http://foo.com/products/id`, "/products/id" est la route. ### routeur diff --git a/fr/resources/middleware.md b/fr/resources/middleware.md old mode 100755 new mode 100644 index 0cc0b713b7..1d2c5d730c --- a/fr/resources/middleware.md +++ b/fr/resources/middleware.md @@ -1,65 +1,44 @@ --- -layout: page +layout: middleware title: Middleware Express +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. menu: resources lang: fr -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. +redirect_from: " " +module: mw-home --- -# Middleware tiers +## Middleware Express Voici quelques modules de middleware Express : - - [body-parser](https://github.com/expressjs/body-parser) : précédemment `express.bodyParser`, `json` et `urlencoded`. - Voir aussi : - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression) : précédemment `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus) : modules de middleware Connect/Express pour une utilisation des images optimale. Bascule les images en `.webp` ou `.jxr`, dans la mesure du possible. - - [connect-timeout](https://github.com/expressjs/timeout) : précédemment `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser) : précédemment `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session) : précédemment `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler) : précédemment `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug) : outil de développement discret qui ajoute un onglet avec des informations sur les variables de canevas (environnements locaux), les sessions en cours, les données de demandes utiles et bien plus, à votre application. - - [express-partial-response](https://github.com/nemtsov/express-partial-response) : module Express Middleware permettant de filtrer des éléments de réponses JSON en fonction de la chaîne de requête `zones` ; en utilisant la réponse partielle de l'API Google. - - [express-session](https://github.com/expressjs/session) : précédemment `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn) : module Express Middleware permettant d'utiliser un CDN pour les actifs statiques, avec la prise en charge de plusieurs hôtes (Par exemple : cdn1.host.com, cdn2.host.com). - - [express-slash](https://github.com/ericf/express-slash) : module Express Middleware destiné aux personnes qui sont strictes sur le respect des barres obliques. - - [express-stormpath](https://github.com/stormpath/stormpath-express) : module Express Middleware destiné au stockage utilisateur, à l'authentification, à l'autorisation, à la connexion unique et à la sécurité des données. - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize) : module middleware destiné à la redirection des demandes HTTP contenant des majuscules en format canonique en minuscules. - - [helmet](https://github.com/helmetjs/helmet) : module qui aide à sécuriser vos applications en définissant divers en-têtes HTTP. - - [join-io](https://github.com/coderaiser/join-io "join-io") : module permettant de joindre des fichiers à la volée pour réduire le nombre de demandes. - - [method-override](https://github.com/expressjs/method-override) : précédemment `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan) : précédemment `logger` - - [passport](https://github.com/jaredhanson/passport) : module de middleware Express dédié à l'authentification. - - [response-time](https://github.com/expressjs/response-time) : précédemment `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon) : précédemment `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index) : précédemment `express.directory` - - [serve-static](https://github.com/expressjs/serve-static) : module d'utilisation du contenu statique. - - [static-expiry](https://github.com/paulwalker/connect-static-expiry) : URL à empreinte digitale ou en-têtes de mise en cache pour les actifs statiques, y compris la prise en charge d'un ou plusieurs domaines externes. - - [vhost](https://github.com/expressjs/vhost) : précédemment `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers) : module Express Middleware qui offre des méthodes d'auxiliaires courantes destinées aux vues. - - [sriracha-admin](https://github.com/hdngr/siracha) : module Express Middleware qui génère de façon dynamique un site administrateur pour Mongoose. +| [express-slash](https://github.com/ericf/express-slash) : module Express Middleware destiné aux personnes qui sont strictes sur le respect des barres obliques. | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Certains modules middleware précédemment inclus avec Connect ne sont plus pris en charge par l'équipe Connect/Express. Ils sont remplacés par un module alternatif ou devraient être remplacés par un module supérieur. Utilisez l'une des alternatives suivantes : +## Pour découvrir plus de modules de middleware, voir : - - express.cookieParser - - [cookies](https://github.com/jed/cookies) et [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +[view-helpers](https://github.com/madhums/node-view-helpers) : module Express Middleware qui offre des méthodes d'auxiliaires courantes destinées aux vues. -Pour découvrir plus de modules de middleware, voir : +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| [express-slash](https://github.com/ericf/express-slash) : module Express Middleware destiné aux personnes qui sont strictes sur le respect des barres obliques. | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet) : module qui aide à sécuriser vos applications en définissant divers en-têtes HTTP. | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport) : module de middleware Express dédié à l'authentification. | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/fr/resources/middleware/body-parser.md b/fr/resources/middleware/body-parser.md new file mode 100644 index 0000000000..afe4bdcca1 --- /dev/null +++ b/fr/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: fr +redirect_from: " " +module: body-parser +--- diff --git a/fr/resources/middleware/compression.md b/fr/resources/middleware/compression.md new file mode 100644 index 0000000000..750b055c26 --- /dev/null +++ b/fr/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: fr +redirect_from: " " +module: compression +--- diff --git a/fr/resources/middleware/connect-rid.md b/fr/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..9a4a513cd2 --- /dev/null +++ b/fr/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: fr +redirect_from: " " +module: connect-rid +--- diff --git a/fr/resources/middleware/cookie-parser.md b/fr/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..96d0d9cfb6 --- /dev/null +++ b/fr/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: fr +redirect_from: " " +module: cookie-parser +--- diff --git a/fr/resources/middleware/cookie-session.md b/fr/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..5976be4cf5 --- /dev/null +++ b/fr/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: fr +redirect_from: " " +module: cookie-session +--- diff --git a/fr/resources/middleware/cors.md b/fr/resources/middleware/cors.md new file mode 100644 index 0000000000..8df8ad04eb --- /dev/null +++ b/fr/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: fr +redirect_from: " " +module: cors +--- diff --git a/fr/resources/middleware/errorhandler.md b/fr/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..c641ba2a17 --- /dev/null +++ b/fr/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: fr +redirect_from: " " +module: errorhandler +--- diff --git a/fr/resources/middleware/method-override.md b/fr/resources/middleware/method-override.md new file mode 100644 index 0000000000..c4fb97235c --- /dev/null +++ b/fr/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: fr +redirect_from: " " +module: method-override +--- diff --git a/fr/resources/middleware/morgan.md b/fr/resources/middleware/morgan.md new file mode 100644 index 0000000000..78e69fc7c9 --- /dev/null +++ b/fr/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: fr +redirect_from: " " +module: morgan +--- diff --git a/fr/resources/middleware/multer.md b/fr/resources/middleware/multer.md new file mode 100644 index 0000000000..fda2294bb2 --- /dev/null +++ b/fr/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: fr +redirect_from: " " +module: multer +--- diff --git a/fr/resources/middleware/response-time.md b/fr/resources/middleware/response-time.md new file mode 100644 index 0000000000..5f32ac05ef --- /dev/null +++ b/fr/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: fr +redirect_from: " " +module: response-time +--- diff --git a/fr/resources/middleware/serve-favicon.md b/fr/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..1c92e61dbc --- /dev/null +++ b/fr/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: fr +redirect_from: " " +module: serve-favicon +--- diff --git a/fr/resources/middleware/serve-index.md b/fr/resources/middleware/serve-index.md new file mode 100644 index 0000000000..26a4a6b0fd --- /dev/null +++ b/fr/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: fr +redirect_from: " " +module: serve-index +--- diff --git a/fr/resources/middleware/serve-static.md b/fr/resources/middleware/serve-static.md new file mode 100644 index 0000000000..27703e6a07 --- /dev/null +++ b/fr/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: fr +redirect_from: " " +module: serve-static +--- diff --git a/fr/resources/middleware/session.md b/fr/resources/middleware/session.md new file mode 100644 index 0000000000..8b39c5d880 --- /dev/null +++ b/fr/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: fr +redirect_from: " " +module: session +--- diff --git a/fr/resources/middleware/timeout.md b/fr/resources/middleware/timeout.md new file mode 100644 index 0000000000..695519a428 --- /dev/null +++ b/fr/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: fr +redirect_from: " " +module: timeout +--- diff --git a/fr/resources/middleware/vhost.md b/fr/resources/middleware/vhost.md new file mode 100644 index 0000000000..c78c0a5e9b --- /dev/null +++ b/fr/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: fr +redirect_from: " " +module: vhost +--- diff --git a/fr/resources/utils.md b/fr/resources/utils.md new file mode 100644 index 0000000000..96394266b3 --- /dev/null +++ b/fr/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: fr +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| 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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/fr/starter/basic-routing.md b/fr/starter/basic-routing.md old mode 100755 new mode 100644 index 8b165f7b3a..ad9390243b --- a/fr/starter/basic-routing.md +++ b/fr/starter/basic-routing.md @@ -1,21 +1,21 @@ --- layout: page title: Routage de base Express +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. menu: starter lang: fr -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. +redirect_from: " " --- # Routage de base -*Routage* fait référence à la détermination de la façon dont une application répond à un +_Routage_ fait référence à la détermination de la façon dont une application répond à un nœud final spécifique, c'est-à-dire un URI (ou chemin) et une méthode de requête HTTP (GET, POST, etc.). Chaque route peut avoir une ou plusieurs fonctions de gestionnaire, qui sont exécutées lorsque la route est mise en correspondance. La définition de la route utilise la structure suivante : + ```js app.METHOD(PATH, HANDLER) ``` @@ -28,8 +28,7 @@ Où : - `HANDLER` est la fonction exécutée lorsque la route est mise en correspondance.
    -Ce tutoriel suppose qu'une instance d'`express` appelée `app` soit créée et que le serveur soit en cours d'exécution. -Si vous ne savez pas créer et démarrer une application, reportez-vous à l'[exemple Hello world](/{{ page.lang }}/starter/hello-world.html). +Ce tutoriel suppose qu'une instance d'`express` appelée `app` soit créée et que le serveur soit en cours d'exécution. Si vous ne savez pas créer et démarrer une application, reportez-vous à l'[exemple Hello world](/{{ page.lang }}/starter/hello-world.html).
    Les exemples suivants illustrent la définition de routes simples. @@ -67,3 +66,5 @@ app.delete('/user', (req, res) => { ``` Pour plus de détails sur le routage, reportez-vous au [guide de routage](/{{ page.lang }}/guide/routing.html). + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/fr/starter/examples.md b/fr/starter/examples.md new file mode 100644 index 0000000000..db7452abae --- /dev/null +++ b/fr/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: fr +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/fr/starter/faq.md b/fr/starter/faq.md old mode 100755 new mode 100644 index cafcd68973..2da9b99a43 --- a/fr/starter/faq.md +++ b/fr/starter/faq.md @@ -1,11 +1,10 @@ --- layout: page title: FAQ Express +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: fr -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # FAQ @@ -20,13 +19,13 @@ Les routes et la logique propre à l'application peuvent être opérationnelles que vous le souhaitez, et dans les structures de répertoire que vous préférez. Pour plus d'inspiration, consultez les exemples suivants : -* [Listes de routes](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [Feuille de route](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [Contrôleurs de style MVC](https://github.com/expressjs/express/tree/master/examples/mvc) +- [Listes de routes](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [Feuille de route](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [Contrôleurs de style MVC](https://github.com/expressjs/express/tree/master/examples/mvc) Il existe aussi des extensions tiers pour Express, permettant de simplifier certains de ces modèles : -* [Routage ingénieux](https://github.com/expressjs/express-resource) +- [Routage ingénieux](https://github.com/expressjs/express-resource) ## Comment puis-je définir des modèles ? @@ -42,7 +41,6 @@ L'authentification est une autre partie complexe dans laquelle Express ne s'aventure pas. Vous pouvez utiliser tous les schémas d'authentification que vous voulez. Pour un schéma simple de type nom d'utilisateur/mot de passe, voir [cet exemple](https://github.com/expressjs/express/tree/master/examples/auth). - ## Quels moteurs de modèles Express prend-il en charge ? Express prend en charge tous les moteurs de modèles conformes à la signature `(path, locals, callback)`. @@ -50,22 +48,26 @@ Pour normaliser les interfaces de moteur de modèles et la mise en cache, voir l projet [consolidate.js](https://github.com/visionmedia/consolidate.js) pour la prise en charge. Des moteurs de modèles non répertoriés peuvent encore prendre en charge la signature Express. +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). + ## Comment puis-je gérer des réponses 404 ? Dans Express, étant donné que les réponses 404 ne sont pas le résultat d'une erreur, le middleware de traitement d'erreurs ne les traite pas. Ce comportement est -dû au fait qu'une réponse 404 indique simplement l'absence d'un travail supplémentaire à effectuer. -En d'autres termes, Express a exécuté toutes les routes et fonctions middleware, +dû au fait qu'une réponse 404 indique simplement l'absence d'un travail supplémentaire à effectuer. En d'autres termes, Express a exécuté toutes les routes et fonctions middleware, et aucune n'a répondu. Tout ce que vous avez à faire est d'ajouter une fonction middleware à la toute fin de la pile (en-dessous de toutes les autres fonctions) pour gérer une réponse 404 : ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## Comment puis-je configurer un gestionnaire d'erreurs ? Vous pouvez définir un middleware de traitement d'erreurs de la même façon qu'un autre middleware, @@ -85,3 +87,10 @@ Pour plus d'informations, voir [Traitement d'erreurs](/{{ page.lang }}/guide/err Vous ne pouvez pas ! Il n'est pas nécessaire de "générer" un fichier HTML avec la fonction `res.render()`. Si vous avez un fichier spécifique, utilisez la fonction `res.sendFile()`. Si vous utilisez plusieurs actifs d'un répertoire, utilisez la fonction middleware `express.static()`. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/fr/starter/generator.md b/fr/starter/generator.md old mode 100755 new mode 100644 index d41b45d03c..3225d7f22e --- a/fr/starter/generator.md +++ b/fr/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Générateur d'applications Express +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: fr -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Générateur d'applications Express Utilisez l'outil de générateur d'applications, `express`, pour créer rapidement un squelette d'application. -Installez `express` à l'aide de la commande suivante : +You can run the application generator with the `npx` command (available in 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: ```bash -$ npm install express-generator -g +$ npm install -g express-generator +$ express ``` Affichez les options de commande à l'aide de l'option `-h` : @@ -22,7 +29,7 @@ Affichez les options de commande à l'aide de l'option `-h` : ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,8 +40,8 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` @@ -82,6 +89,12 @@ Sous Windows, utilisez la commande suivante : > set DEBUG=myapp:* & npm start ``` +Installez `express` à l'aide de la commande suivante : + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + Ensuite, chargez 'http://hôte_local:3000/' dans votre navigateur pour accéder à l'application. L'application générée possède la structure de répertoire suivante : @@ -111,3 +124,5 @@ L'application générée possède la structure de répertoire suivante :
    La structure d'application créée par le générateur est l'une des nombreuses manières possibles de structurer les applications Express. Vous avez toute latitude pour l'utiliser ou la modifier en fonction de vos besoins.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/fr/starter/hello-world.md b/fr/starter/hello-world.md old mode 100755 new mode 100644 index 61759572ba..ec3f254445 --- a/fr/starter/hello-world.md +++ b/fr/starter/hello-world.md @@ -1,10 +1,10 @@ --- layout: page title: Exemple "Hello world" Express +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: fr -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Exemple Hello world @@ -14,11 +14,6 @@ Il s'agit de l'application Express la plus simple que vous puissiez créer. Cett [générateur Express](/{{ page.lang }}/starter/generator.html), qui crée l'échafaudage d'une application entière, avec des fichiers JavaScript, des modèles Pug et des sous-répertoires pour divers motifs.
    -Premièrement, créez un répertoire appelé `myapp`, rendez-vous dedans et exécutez la commande `npm init`. -Ensuite, installez `express` en tant que dépendance en suivant les instructions du [guide d'installation](/{{ page.lang }}/starter/installing.html). - -Dans le répertoire `myapp`, créez un fichier appelé `app.js` et ajoutez le code suivant : - ```js const express = require('express') const app = express() @@ -34,7 +29,13 @@ app.listen(port, () => { ``` L'application démarre un serveur et écoute le port 3000 à la recherche de connexions. L'application répond "Hello World!" aux demandes adressées -à l'URL racine (`/`) ou à la *route* racine. Pour tous les autres chemins d'accès, elle répondra par **404 Not Found**. +à l'URL racine (`/`) ou à la _route_ racine. Pour tous les autres chemins d'accès, elle répondra par **404 Not Found**. + +### Running Locally + +Premièrement, créez un répertoire appelé `myapp`, rendez-vous dedans et exécutez la commande `npm init`. Ensuite, installez `express` en tant que dépendance en suivant les instructions du [guide d'installation](/{{ page.lang }}/starter/installing.html). + +Dans le répertoire `myapp`, créez un fichier appelé `app.js` et ajoutez le code suivant :
    Les objets `req` (demande) et `res` (réponse) sont exactement les mêmes que ceux que Node fournit, vous pouvez donc appeler @@ -49,3 +50,4 @@ $ node app.js Puis chargez [http://localhost:3000/](http://localhost:3000/) dans un navigateur pour consulter le résultat. +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/fr/starter/installing.md b/fr/starter/installing.md old mode 100755 new mode 100644 index 9428624dbf..a418f7827e --- a/fr/starter/installing.md +++ b/fr/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: Installation d'Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: fr -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # Installation En supposant que [Node.js](https://nodejs.org/) est déjà installé, créez un répertoire pour héberger votre application et faites-en votre répertoire de travail. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -26,7 +29,7 @@ $ npm init Cette commande vous invite à fournir un certain nombre d'informations, telles que le nom et la version de votre application. Pour le moment, vous pouvez simplement appuyer sur la touche RETURN pour accepter les valeurs par défaut, à l'exception de ce qui suit : -```bash +``` entry point: (index.js) ``` @@ -35,17 +38,17 @@ Entrez `app.js` ou un nom de votre choix pour le fichier principal. Si vous souh Installez ensuite Express dans le répertoire `myapp`, puis sauvegardez-le dans la liste des dépendances. Par exemple : ```bash -$ npm install express --save +$ npm install express ``` Pour installer Express de façon temporaire et ne pas l'ajouter à la liste des dépendances, omettez l'option `--save` : ```bash -$ npm install express +$ npm install express --no-save ```
    -Les modules Node.js installés à l'aide de l'option `--save` sont ajoutés à la liste des dépendances `dependencies`, dans le fichier `package.json`. -Par défaut, depuis la version 5.0, `npm install ` ajoute automatiquement le module Node.js à la liste des dépendances. -Par la suite, l'exécution de `npm install` dans le répertoire de l'application installera automatiquement les modules présents dans la liste des dépendances. +` ajoute automatiquement le module Node.js à la liste des dépendances. Par la suite, l'exécution de `npm install` dans le répertoire de l'application installera automatiquement les modules présents dans la liste des dépendances.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/fr/starter/static-files.md b/fr/starter/static-files.md old mode 100755 new mode 100644 index c162ddfb62..b6c8eaa7d9 --- a/fr/starter/static-files.md +++ b/fr/starter/static-files.md @@ -1,10 +1,10 @@ --- layout: page title: Servir des fichiers statiques dans Express -menu: démarrage +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. +menu: starter lang: fr -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # Servir des fichiers statiques dans Express @@ -13,10 +13,16 @@ Pour servir des fichiers statiques tels que les images, les fichiers CSS et les fichiers JavaScript, utilisez la fonction de logiciel intermédiaire intégré `express.static` dans Express. -Passez le nom du répertoire qui contient les actifs -statiques dans la fonction de logiciel intermédiaire -`express.static` afin de commencer à servir -les fichiers directement. Par exemple, utilisez le code suivant pour +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](/{{page.lang}}/4x/api.html#express.static). + +Par exemple, utilisez le code suivant pour servir des images, des fichiers CSS et des fichiers JavaScript dans un répertoire nommé `public` : @@ -52,6 +58,11 @@ app.use(express.static('files')) Express recherche les fichiers dans l'ordre dans lequel vous avez établi les répertoires statiques avec la fonction middleware `express.static`. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + Pour créer un préfixe de chemin d'accès virtuel (dans lequel le chemin d'accès n'existe pas vraiment dans le système de fichiers) pour les fichiers qui sont servis par la fonction @@ -86,3 +97,7 @@ servir : const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/fr/support/index.md b/fr/support/index.md index 78f1d61e94..f9f35c0a92 100644 --- a/fr/support/index.md +++ b/fr/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: fr --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/it/3x/api.md b/it/3x/api.md old mode 100755 new mode 100644 index cb6429072b..83f0aa9f54 --- a/it/3x/api.md +++ b/it/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - Riferimento API +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: it -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x NON È PIU' SUPPORTATO** - I problemi noti e non noti relativi alla sicurezza presenti in 3.x non sono stati indirizzati dall'ultimo aggiornamento (1 agosto 2015). Si consiglia di utilizzare l'ultima versione di Express. -
    - -

    API 3.x

    +I problemi noti e non noti relativi alla sicurezza presenti in 3.x non sono stati indirizzati dall'ultimo aggiornamento (1 agosto 2015). Si consiglia di utilizzare l'ultima versione di Express. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
    - - {% include api/en/3x/res.md %} +

    API 3.x

    - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
    diff --git a/it/4x/api.md b/it/4x/api.md old mode 100755 new mode 100644 index e0c4e4bc80..c9eddee63e --- a/it/4x/api.md +++ b/it/4x/api.md @@ -2,27 +2,26 @@ layout: api version: 4x title: Express 4.x - Riferimento API +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: it -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +

    API 4.x

    - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
    diff --git a/it/5x/api.md b/it/5x/api.md index ffcbb0ad0c..89058de2b8 100644 --- a/it/5x/api.md +++ b/it/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - Riferimento API +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: it -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/it/advanced/best-practice-performance.md b/it/advanced/best-practice-performance.md old mode 100755 new mode 100644 index b9dddc61be..94e4a67938 --- a/it/advanced/best-practice-performance.md +++ b/it/advanced/best-practice-performance.md @@ -1,34 +1,39 @@ --- layout: page title: Best Practice sulle prestazioni utilizzando Express in fase di produzione +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: it -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # Best practice sulla produzione: prestazioni e affidabilità -## Panoramica - In questo articolo vengono descritte le best practice sulle prestazioni e sull'affidabilità per le applicazioni Express implementate per la produzione. Questo argomento entra nel mondo di "devops", coprendo sia le operazioni che lo sviluppo tradizionale. Di conseguenza, le informazioni sono divise in due parti: -* [Operazioni da effettuare nel codice](#code) (la parte dello sviluppo). -* [Operazioni da effettuare nell'ambiente / configurazione](#env) (la parte delle operazioni). - - - -## Operazioni da effettuare nel codice +- Things to do in your code (the dev part): + - Utilizzare la compressione gzip + - [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) + - Gestire in modo appropriato le eccezioni + - [Handle exceptions properly](#handle-exceptions-properly) +- [Operazioni da effettuare nell'ambiente / configurazione](#env) (la parte delle operazioni). + - Impostare NODE_ENV su "produzione" + - Al contrario, utilizzare il middleware [serve-static](https://www.npmjs.com/package/serve-static) (o qualcosa di equivalente), ottimizzato per servire i file per le applicazioni Express. + - Eseguire l'applicazione in un cluster + - + - Utilizzare un servizio di bilanciamento del carico + - Utilizzare un proxy inverso + +## Things to do in your code {#in-code} Di seguito sono elencate alcune operazioni che è possibile effettuare nel codice per migliorare le prestazioni dell'applicazione: -* Utilizzare la compressione gzip -* Non utilizzare funzioni sincrone -* Utilizzare il middleware per servire file statici -* Effettuare correttamente la registrazione -* Gestire in modo appropriato le eccezioni +- Utilizzare la compressione gzip +- [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) +- Gestire in modo appropriato le eccezioni +- [Handle exceptions properly](#handle-exceptions-properly) ### Utilizzare la compressione gzip @@ -38,6 +43,7 @@ La compressione gzip è in grado di ridurre notevolmente la dimensione del conte const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` @@ -49,19 +55,11 @@ I metodi e le funzioni sincrone ostacolano il processo di esecuzione finché non Poiché Node e molti moduli forniscono versioni sicrone e asincrone delle relative funzioni, utilizzare sempre la versione asincrona nella produzione. L'unico caso in cui l'utilizzo di una funzione sincrona è giustificato, è allo startup iniziale. -Se si sta utilizzando Node.js 4.0+ o io.js 2.1.0+, è possibile utilizzare il flag della riga di comando `--trace-sync-io` per stampare un avviso e un'analisi dello stack ogniqualvolta che un'applicazione utilizza una API sincrona. Naturalmente, non si consiglia di utilizzarlo nella produzione, ma solo per assicurare che il codice sia pronto per la produzione. Consultare l'[aggiornamento settimanale per io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0) per ulteriori informazioni. - -### Utilizzare il middleware per servire file statici - -Nello sviluppo, è possibile utilizzare [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) per servire i file statici. Ma non effettuare questa operazione in fase di produzione, poiché questa funzione deve effettuare un processo di lettura dal file system per ciascuna richiesta file, quindi si verificherà una latenza importante e si andrà a influenzare le prestazioni dell'applicazione. Notare che `res.sendFile()` *non* viene implementato con la chiamata di sistema [sendfile](http://linux.die.net/man/2/sendfile), che lo renderebbe molto più efficiente. - -Al contrario, utilizzare il middleware [serve-static](https://www.npmjs.com/package/serve-static) (o qualcosa di equivalente), ottimizzato per servire i file per le applicazioni Express. - -Un'altra opzione potrebbe essere quella di utilizzare un proxy inverso per servire file statici; consultare [Utilizzare un proxy inverso](#proxy) per ulteriori 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. Naturalmente, non si consiglia di utilizzarlo nella produzione, ma solo per assicurare che il codice sia pronto per la produzione. Consultare l'[aggiornamento settimanale per io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0) per ulteriori informazioni. ### Effettuare correttamente la registrazione -Solitamente, esistono due motivi per effettuare la registrazione dall'applicazione: per il debug e la registrazione dell'attività dell'applicazione (sostanzialmente, qualsiasi altra cosa). L'utilizzo di `console.log()` o `console.err()` per stampare i messaggi di log sul terminale, è un'operazione comune nello sviluppo. Ma [queste funzioni sono sincrone](https://nodejs.org/api/console.html#console_console_1) quando la destinazione è un terminale o un file, pertanto non sono adatte per la produzione, a meno che non si indirizzi l'output a un altro programma. +Solitamente, esistono due motivi per effettuare la registrazione dall'applicazione: per il debug e la registrazione dell'attività dell'applicazione (sostanzialmente, qualsiasi altra cosa). L'utilizzo di `console.log()` o `console.err()` per stampare i messaggi di log sul terminale, è un'operazione comune nello sviluppo. 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 @@ -69,42 +67,27 @@ Se si sta effettuando la registrazione per motivi di debug, allora invece di uti #### Per l'attività dell'applicazione -Se si sta registrando l'attività dell'applicazione (ad esempio, si sta tenendo traccia del traffico e delle chiamate API), invece di utilizzare `console.log()`, utilizzare una libreria di registrazione quale [Winston](https://www.npmjs.com/package/winston) o [Bunyan](https://www.npmjs.com/package/bunyan). Per un confronto dettagliato di queste due librerie, consultare il post del blog di StrongLoop [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/). - - +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. -### Gestire in modo appropriato le eccezioni +### Handle exceptions properly Le applicazioni Node danno origine a errori quando riscontrano eccezioni non rilevate. Se tali eccezioni non vengono gestite o se non si effettuano operazioni appropriate, l'applicazione Express si arresterà in modo anomalo. Seguendo i consigli descritti in [Riavvio automatico dell'applicazione](#restart), sarà possibile recuperare l'applicazione dopo un arresto anomalo. Fortunatamente, le applicazioni Express solitamente hanno tempi di avvio molto brevi. Tuttavia, per prima cosa è necessario evitare che si verifichino arresti anomali, e per effettuare ciò, è necessario gestire in modo appropriato le eccezioni. Per essere sicuri di gestire al meglio tutte le eccezioni, utilizzare le seguenti tecniche: -* [Utilizzare try-catch](#try-catch) -* [Utilizzare promises](#promises) +- [Utilizzare try-catch](#try-catch) +- [Utilizzare promises](#promises) Prima di leggere questi argomenti, è necessario avere una conoscenza base della gestione degli errori di Node/Express: utilizzo di error-first callback e diffusione degli errori al middleware. Node utilizza la convenzione "error-first callback" per restituire gli errori da funzioni asincrone, dove il primo parametro per la funzione callback è l'oggetto dell'errore, seguito dai dati nei parametri successivi. Per indicare un errore, indicare null come primo parametro. La funzione callback deve seguire in modo corrispondente la convenzione error-first callback per gestire l'errore in modo significativo. In Express, il miglior modo è quello di utilizzare la funzione next() per diffondere gli errori attraverso la catena middleware. Per ulteriori informazioni sulle nozioni di base della gestione degli errori, consultare: -* [Gestione degli errori in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Come creare applicazioni Node solide: Gestione degli errori](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (blog di StrongLoop) - -#### Cosa non fare - -Una cosa da *non* fare è quella di stare in ascolto per un evento `uncaughtException`, emesso quando un'eccezione si verifica ed è costante nel loop degli eventi. Se si aggiunge un programma di ascolto dell'evento per `uncaughtException` si cambierà il funzionamento predefinito del processo che sta riscontrando un'eccezione; il processo continuerà ad operare malgrado l'eccezione. Questo potrebbe risultare un ottimo modo per prevenire un arresto anomalo dell'applicazione, ma continuare ad utilizzare un'applicazione dopo che si è verificata un'eccezione non rilevata è pericoloso e non è consigliato, poiché lo stato del processo diventa non affidabile e non prevedibile. - -Inoltre, l'utilizzo di `uncaughtException` è ufficialmente riconosciuto come [non conforme](https://nodejs.org/api/process.html#process_event_uncaughtexception) ed esiste una [proposta](https://github.com/nodejs/node-v0.x-archive/issues/2582) per la relativa rimozione dal core. Quindi continuare a visualizzare un evento `uncaughtException` non è un buon segno. Ecco perché consigliamo di usufruire di più processi e supervisori: l'arresto anomalo e il riavvio sono spesso il modo più affidabile per ripristinare una situazione dopo un errore. - -Inoltre, non si consiglia di utilizzare l'opzione [domini](https://nodejs.org/api/domain.html). Solitamente non risolve il problema ed è considerato un modulo obsoleto. - - +- [Gestione degli errori in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### Utilizzare try-catch Try-catch è un linguaggio JavaScript che è possibile utilizzare per rilevare eccezioni in codice sincrono. Ad esempio, utilizzare try-catch, per gestire errori di analisi JSON come mostrato di seguito. -Utilizzare uno strumento come [JSHint](http://jshint.com/) o [JSLint](http://www.jslint.com/) come supporto nel rilevamento di eccezioni implicite quali [errori di riferimento su variabili non definite](http://www.jshint.com/docs/options/#undef). - Di seguito viene riportato un esempio di utilizzo di try-catch per la gestione di un'eccezione che dà origine a un arresto anomalo del processo. Questa funzione middleware accetta un parametro del campo query denominato "params" che è un oggetto JSON. @@ -125,85 +108,70 @@ app.get('/search', (req, res) => { Tuttavia, try-catch funziona solo per il codice sincrono. Poiché la piattaforma Node è principalmente asincrona (nello specifico in un ambiente di produzione), try-catch non sarà in grado di rilevare molte eccezioni. - - #### Utilizzare promises -Promises gestirà qualsiasi eccezione (sia implicita che esplicita) in blocchi di codice asincrono che utilizzano `then()`. Aggiungere `.catch(next)` alla fine della catena promise. Ad esempio: +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -Ora, tutti gli errori asincroni e sincroni vengono inoltrati al middleware degli errori. - -Tuttavia, esistono due punti a cui prestare attenzione: - -1. Tutto il codice asincrono deve restituire promises (ad eccezione di emettitori). Se una libreria particolare non restituire promises, convertire l'oggetto base utilizzando una funzione di supporto come [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html). -2. Emettitori evento (come flussi) possono ancora dare origine ad eccezioni non rilevate. Quindi, assicurarsi di gestire l'evento di errore in modo appropriato, ad esempio: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -Per ulteriori informazioni sulla gestione degli errori mediante l'utilizzo di promises, consultare: +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. -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +#### Cosa non fare + +Una cosa da _non_ fare è quella di stare in ascolto per un evento `uncaughtException`, emesso quando un'eccezione si verifica ed è costante nel loop degli eventi. Se si aggiunge un programma di ascolto dell'evento per `uncaughtException` si cambierà il funzionamento predefinito del processo che sta riscontrando un'eccezione; il processo continuerà ad operare malgrado l'eccezione. Questo potrebbe risultare un ottimo modo per prevenire un arresto anomalo dell'applicazione, ma continuare ad utilizzare un'applicazione dopo che si è verificata un'eccezione non rilevata è pericoloso e non è consigliato, poiché lo stato del processo diventa non affidabile e non prevedibile. + +Inoltre, l'utilizzo di `uncaughtException` è ufficialmente riconosciuto come [non conforme](https://nodejs.org/api/process.html#process_event_uncaughtexception) ed esiste una [proposta](https://github.com/nodejs/node-v0.x-archive/issues/2582) per la relativa rimozione dal core. Quindi continuare a visualizzare un evento `uncaughtException` non è un buon segno. Ecco perché consigliamo di usufruire di più processi e supervisori: l'arresto anomalo e il riavvio sono spesso il modo più affidabile per ripristinare una situazione dopo un errore. + +Inoltre, non si consiglia di utilizzare l'opzione [domini](https://nodejs.org/api/domain.html). Solitamente non risolve il problema ed è considerato un modulo obsoleto. - +## Things to do in your environment / setup -## Operazioni da effettuare nell'ambiente / configurazione +{#in-environment} Di seguito sono elencate alcune operazioni che è possibile effettuare nell'ambiente del sistema per migliorare le prestazioni dell'applicazione: -* Impostare NODE_ENV su "produzione" -* Verificare che l'applicazione sia in grado di riavviarsi automaticamente -* Eseguire l'applicazione in un cluster -* Memorizzare in cache i risultati della richiesta -* Utilizzare un servizio di bilanciamento del carico -* Utilizzare un proxy inverso +- Impostare NODE_ENV su "produzione" +- Al contrario, utilizzare il middleware [serve-static](https://www.npmjs.com/package/serve-static) (o qualcosa di equivalente), ottimizzato per servire i file per le applicazioni Express. +- Eseguire l'applicazione in un cluster +- +- Utilizzare un servizio di bilanciamento del carico +- Utilizzare un proxy inverso ### Impostare NODE_ENV su "produzione" -La variabile di ambiente NODE_ENV indica l'ambiente in cui è in esecuzione un'applicazione (solitamente, sviluppo o applicazione). Una delle cose più semplici da fare per migliorare le prestazioni, è impostare NODE_ENV su "produzione." +La variabile di ambiente NODE_ENV indica l'ambiente in cui è in esecuzione un'applicazione (solitamente, sviluppo o applicazione). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. L'impostazione di NODE_ENV su "produzione" consente ad Express di: -* Memorizzare in cache i template di visualizzazione. -* Memorizzare in cache i file CSS generati da stensioni CSS. -* Generare meno messaggi di errore ridondanti. +- Memorizzare in cache i template di visualizzazione. +- Memorizzare in cache i file CSS generati da stensioni CSS. +- Generare meno messaggi di errore ridondanti. -[I test hanno confermato](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) che seguendo queste indicazioni è possibile migliorare le prestazioni dell'applicazione di tre volte! +[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! Se si ha la necessità di scrivere codice specifico dell'ambiente, è possibile selezionare il valore di NODE_ENV con `process.env.NODE_ENV`. Notare che la selezione del valore di qualsiasi variabile di ambiente influisce sulle prestazioni in modo negativo, quindi questa operazione deve essere effettuata con moderazione. -Nello sviluppo, solitamente si impostano le variabili di ambiente nella shell interattiva, ad esempio utilizzando `export` o il file `.bash_profile`. Ma solitamente non si consiglia di effettuare questa operazione su un server di produzione; al contrario, utilizzare il sistema init del sistema operativo (systemd o Upstart). La sezione successiva fornisce ulteriori dettagli sull'utilizzo in generale del sistema init, però anche impostare NODE_ENV è molto importante per le prestazioni (ed è facile da fare), evidenziato di seguito. - -Con Upstart, utilizzare la parola chiave `env` nel file job. Ad esempio: - -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` - -Per ulteriori informazioni, consultare [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables). +Nello sviluppo, solitamente si impostano le variabili di ambiente nella shell interattiva, ad esempio utilizzando `export` o il file `.bash_profile`. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). La sezione successiva fornisce ulteriori dettagli sull'utilizzo in generale del sistema init, però anche impostare NODE_ENV è molto importante per le prestazioni (ed è facile da fare), evidenziato di seguito. Con systemd, utilizzare la direttiva `Environment` nel file unit. Ad esempio: @@ -212,16 +180,14 @@ Con systemd, utilizzare la direttiva `Environment` nel file unit. Ad esempio: Environment=NODE_ENV=production ``` -Per ulteriori informazioni, consultare [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html). - -Se si sta utilizzando StrongLoop Process Manager, è inoltre possibile [impostare la variabile di ambiente quando si installa StrongLoop PM as a service](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables). +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Verificare che l'applicazione sia in grado di riavviarsi automaticamente In fase di produzione, l'applicazione non deve mai andare offline. Ciò significa che deve riavviarsi nel caso in cui sia l'applicazione che il server terminino in modo anomalo. Anche se ovviamente si spera che entrambe queste situazioni non si verifichino mai, realisticamente è necessario considerare l'eventualità di: -* Utilizzare un process manager per riavviare l'applicazione (e Node) quando termina in modo anomalo. -* Utilizzare il sistema init fornito dal sistema operativo per riavviare il process manager quando il sistema operativo termina in modo anomalo. È inoltre possibile utilizzare il sistema init senza un process manager. +- Utilizzare un process manager per riavviare l'applicazione (e Node) quando termina in modo anomalo. +- Utilizzare il sistema init fornito dal sistema operativo per riavviare il process manager quando il sistema operativo termina in modo anomalo. È inoltre possibile utilizzare il sistema init senza un process manager. Le applicazioni Node terminano in modo anomalo se riscontrano eccezioni non rilevate. La prima cosa da fare è verificare che l'applicazione sia stata verificata e che sia in grado di gestire tutte le eccezioni (consultare [Gestire in modo appropriato le eccezioni](#exceptions) per dettagli). Come prevenzione, attivare un meccanismo che assicuri che applicazione si riavvii automaticamente in caso di arresto anomalo. @@ -231,54 +197,35 @@ Nello sviluppo, l'applicazione è stata avviata semplicemente dalla riga comandi Oltre a fare in modo di riavviare l'applicazione in caso di arresto anomalo, un process manager consente di: -* Ottenere insight relativi alle prestazioni di runtime e al consumo delle risorse. -* Modificare le impostazioni in modo dinamico per migliorare le prestazioni. -* Controllare il processo di clustering (StrongLoop PM e pm2). +- Ottenere insight relativi alle prestazioni di runtime e al consumo delle risorse. +- Modificare le impostazioni in modo dinamico per migliorare le prestazioni. +- Control clustering (pm2). -I process manager più noti per Node sono i seguenti: - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -Per un paragone a livello di funzioni dei tre process manager, consultare l'indirizzo [http://strong-pm.io/compare/](http://strong-pm.io/compare/). - -L'utilizzo di questi process manager sarà sufficiente per far restare attiva l'applicazione, anche se dovesse capitare che si arresti in modo anomalo. - -Tuttavia, StrongLoop PM dispone di molte funzioni che sono indicate in modo specifico per l'implementazione della produzione. È possibile utilizzarle insieme ai relativi strumenti di StrongLoop per: - -* Creare e confezionare l'applicazione localmente, quindi implementarla in modo sicuro al sistema di produzione. -* Riavviare automaticamente l'applicazione se termina in modo anomalo per qualsiasi motivo. -* Gestire i cluster in modo remoto. -* Visualizzare i profili CPU e accumulare le istantanee per ottimizzare le prestazioni e diagnosticare le perdite di memoria. -* Visualizzare le metriche delle prestazioni per l'applicazione. -* Scalare facilmente a più host con un controllo integrato per il servizio di bilanciamento del carico Nginx. - -Come mostrato di seguito, quando si installa StrongLoop PM come servizio del sistema operativo utilizzando il sistema init, si riavvierà automaticamente quando si riavvia il sistema. Pertanto, consentirà ai processi delle applicazioni e ai cluster di restare sempre attivi. +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. #### Utilizzare un sistema init -Il successivo livello di affidabilità è quello di assicurare che l'applicazione venga riavviata quando si riavvia il server. I sistemi possono ancora arrestarsi per moltissimi motivi. Per fare in modo che l'applicazione si riavvii nel caso in cui un server si arresti in modo anomalo, utilizzare il sistema init integrato al sistema operativo. Oggi, i due sistemi init principali in uso sono [systemd](https://wiki.debian.org/systemd) e [Upstart](http://upstart.ubuntu.com/). +Il successivo livello di affidabilità è quello di assicurare che l'applicazione venga riavviata quando si riavvia il server. I sistemi possono ancora arrestarsi per moltissimi motivi. Per fare in modo che l'applicazione si riavvii nel caso in cui un server si arresti in modo anomalo, utilizzare il sistema init integrato al sistema operativo. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Esistono due modi per utilizzare i sistemi init con l'applicazione Express: -* Far eseguire l'applicazione in un process manager e installare il process manager come servizio con il sistema init. Il process manager riavvierà l'applicazione nel caso in cui termini in modo anomalo e il sistema init riavvierà il process manager quando si riavvia il sistema operativo. Questa è la procedura consigliata. -* Far eseguire l'applicazione (e Node) direttamente con il sistema init. Questa operazione risulta più semplice ma non si hanno gli stessi vantaggi dell'utilizzo di un process manager. +- Far eseguire l'applicazione in un process manager e installare il process manager come servizio con il sistema init. Il process manager riavvierà l'applicazione nel caso in cui termini in modo anomalo e il sistema init riavvierà il process manager quando si riavvia il sistema operativo. Questa è la procedura consigliata. +- Far eseguire l'applicazione (e Node) direttamente con il sistema init. Questa operazione risulta più semplice ma non si hanno gli stessi vantaggi dell'utilizzo di un process manager. ##### Systemd Systemd è un sistema Linux e un service manager. Le più importanti distribuzioni Linux hanno utilizzato systemd come sistema init predefinito. -Un file di configurazione del servizio systemd è denominato *unit file*, con un nome file che termina con .service. Segue un unit file di esempio per gestire un'applicazione Node direttamente (sostituire il testo in grassetto con i valori appropriati per il proprio sistema e applicazione): +Un file di configurazione del servizio systemd è denominato _unit file_, con un nome file che termina con .service. Segue un unit file di esempio per gestire un'applicazione Node direttamente (sostituire il testo in grassetto con i valori appropriati per il proprio sistema e applicazione): Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -300,99 +247,14 @@ Restart=always [Install] WantedBy=multi-user.target ``` -Per ulteriori informazioni su systemd, consultare [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). - -##### StrongLoop PM in qualità di servizio systemd - -È possibile installare facilmente StrongLoop Process Manager in qualità di servizio systemd. Dopo l'installazione, quando il server si riavvia, si riavvierà automaticamente StrongLoop PM, il quale riavvierà di conseguenza tutte le applicazioni che sta gestendo. -Per installare StrongLoop PM in qualità di servizio systemd: - -```bash -$ sudo sl-pm-install --systemd -``` - -Successivamente, avviare il servizio con: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -Per ulteriori informazioni, consultare [Configurazione di un host di produzione (documentazione StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10). - -##### Upstart - -Upstart è uno strumento di sistema disponibile su molte distribuzioni Linux per l'avvio delle attività e dei servizi durante lo startup del sistema, per l'arresto delle stesse durante la fase di shutdown e per il controllo delle stesse. È possibile configurare l'applicazione Express o il process manager in qualità di servizio e successivamente Upstart le riavvierà automaticamente quando terminano in modo anomalo. - -Un servizio Upstart è definito in un file di configurazione del lavoro (anche noto come "lavoro") con un nome file che termina con `.conf`. Il seguente esempio mostra come creare un lavoro denominato "myapp" per un'applicazione denominata "myapp" con il file principale ubicato in `/projects/myapp/index.js`. - -Creare un file denominato `myapp.conf` in `/etc/init/` con il seguente contenuto (sostituire il testo in grassetto con i valori appropriati per il proprio sistema e applicazione): - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -NOTA: questo script richiede Upstart 1.4 o versione successiva, supportato su Ubuntu 12.04-14.10. - -Poiché il lavoro è configurato per essere eseguito quando si avvia il sistema, l'applicazione verrà avviata insieme al sistema operativo e riavviata automaticamente se l'applicazione termina in modo anomalo o se il sistema si arresta. - -Oltre a riavviare automaticamente l'applicazione, Upstart consente di utilizzare i seguenti comandi: - -* `start myapp` – Avviare l'applicazione -* `restart myapp` – Riavviare l'applicazione -* `stop myapp` – Arrestare l'applicazione. - -Per ulteriori informazioni su Upstart, consultare [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook). - -##### StrongLoop PM in qualità di servizio Upstart - -È possibile installare facilmente StrongLoop Process Manager in qualità di servizio Upstart. Dopo l'installazione, quando il server si riavvia, si riavvierà automaticamente StrongLoop PM, il quale riavvierà di conseguenza tutte le applicazioni che sta gestendo. - -Per installare StrongLoop PM in qualità di servizio Upstart 1.4: - -```bash -$ sudo sl-pm-install -``` - -Successivamente, eseguire il servizio con: - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -NOTA: su sistemi che non supportano Upstart 1.4, i comandi sono leggermente differenti. Consultare [Configurazione di un host di produzione (documentazione StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) per ulteriori informazioni. +Per ulteriori informazioni su systemd, consultare [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). ### Eseguire l'applicazione in un cluster In un sistema multicore, è possibile aumentare le prestazioni di un'applicazione Node di molte volte avviando un cluster di processi. Un cluster esegue molte istanze di un'applicazione, nel caso ideale, un'istanza su ciascun core CPU, quindi, distribuendo il carico e le attività tra le istanze. - +![Balancing between application instances using the cluster API](/images/clustering.png) IMPORTANTE: poiché le istanze dell'applicazione vengono eseguite come processi separati, non condividono lo stesso spazio di memoria. Ossia, gli oggetti sono locali rispetto a ciascuna istanza dell'applicazione. Pertanto, non è possibile conservare lo stato nel codice dell'applicazione. Tuttavia, è possibile utilizzare un datastore in-memory, ad esempio [Redis](http://redis.io/) per memorizzare lo stato e i dati relativi alla sessione. Questa condizione si applica fondamentalmente a tutti i moduli di scaling orizzontale, se il processo di clustering viene effettuato con più processi o più server fisici. @@ -400,43 +262,52 @@ Nelle applicazioni sottoposte a cluster, i processi di lavoro possono ternare in #### Utilizzo del modulo cluster di Node -Il processo di clustering è stato reso possibile con il [cluster module](https://nodejs.org/docs/latest/api/cluster.html) di Node. Ciò consente a un processo principale di dare origine a processi di lavoro e di distribuire le connessioni in entrata tra i processi di lavoro. Tuttavia, invece di utilizzare direttamente questo modulo, è meglio utilizzare uno dei molti strumenti disponibili che svolgono questa attività automaticamente; ad esempio [node-pm](https://www.npmjs.com/package/node-pm) o [cluster-service](https://www.npmjs.com/package/cluster-service). +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). Ciò consente a un processo principale di dare origine a processi di lavoro e di distribuire le connessioni in entrata tra i processi di lavoro. -#### Utilizzo di StrongLoop PM +#### Using PM2 -Se si implementa l'applicazione a StrongLoop Process Manager (PM), è possibile sfruttare i vantaggi del processo di clustering *senza* dover modificare il codice dell'applicazione. +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 StrongLoop Process Manager (PM) esegue un'applicazione, la esegue automaticamente in un cluster con un numero di processi di lavoro equivalente al numero di core CPU presenti sul sistema. È possibile modificare manualmente il numero di processi di lavoro nel cluster utilizzando lo strumento della riga comandi senza arrestare l'applicazione. +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. -Ad esempio, se l'applicazione è stata implementata su prod.foo.com e StrongLoop PM è in ascolto sulla porta 8701 (quella predefinita), per impostare la dimensione del cluster a otto utilizzando slc: +To enable cluster mode, start your application like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -Per ulteriori informazioni sul processo di clustering con StrongLoop PM, consultare [Processo di clustering](https://docs.strongloop.com/display/SLC/Clustering) nella documentazione StrongLoop. +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 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ 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. ### Memorizzare in cache i risultati della richiesta Un'altra strategia per migliorare le prestazioni in fase di produzione è quella di memorizzare in cache i risultati delle richieste, in modo tale che l'applicazione non debba gestire nuovamente la stessa richiesta. -Utilizzare un server di memorizzazione in cache quale [Varnish](https://www.varnish-cache.org/) o [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (vedere anche [Nginx Caching](https://serversforhackers.com/nginx-caching/)) per migliorare notevolmente la velocità e le prestazioni dell'applicazione. +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. ### Utilizzare un servizio di bilanciamento del carico A prescindere da quanto sia ottimizzata un'applicazione, una singola istanza è in grado di gestire solo una quantità limitata di carico e traffico. Un modo per scalare un'applicazione è quello di eseguire più delle proprie istanze e distribuire il traffico tramite un servizio di bilanciamento del carico. L'impostazione di un servizio di bilanciamento del carico può migliorare la velocità e le prestazioni dell'applicazione e abilitarla a scalare di più di quanto sia possibile fare con una singola istanza. -Un servizio di bilanciamento del carico è solitamente un proxy inverso che gestisce il traffico a e d più istanze di applicazione e server. È possibile impostare facilmente un servizio di bilanciamento del carico per l'applicazione utilizzando [Nginx](http://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 servizio di bilanciamento del carico, è possibile che sia necessario garantire che le richieste associate a un ID sessione particolare si connettano al processo che le ha originate. Questo processo è noto come *affinità sessione* o *sessioni delicate*. Si consiglia di utilizzare un data store, ad esempio Redis, per i dati sessione (a seconda dell'applicazione). Per informazioni, consultare [Utilizzo di più nodi](https://socket.io/docs/v4/using-multiple-nodes/). - -#### Utilizzo di StrongLoop PM con un servizio di bilanciamento del carico Nginx +Un servizio di bilanciamento del carico è solitamente un proxy inverso che gestisce il traffico a e d più istanze di applicazione e server. 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). -[StrongLoop Process Manager](http://strong-pm.io/) si integra con un controller Nginx, rendendo semplice il processo di configurazione di ambienti di produzione multi host. Per ulteriori informazioni, consultare [Processo di scaling su più server](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers) (documentazione StrongLoop). - +Con il servizio di bilanciamento del carico, è possibile che sia necessario garantire che le richieste associate a un ID sessione particolare si connettano al processo che le ha originate. Questo processo è noto come _affinità sessione_ o _sessioni delicate_. Si consiglia di utilizzare un data store, ad esempio Redis, per i dati sessione (a seconda dell'applicazione). Per informazioni, consultare [Utilizzo di più nodi](https://socket.io/docs/v4/using-multiple-nodes/). ### Utilizzare un proxy inverso Un proxy inverso si trova davanti a un'applicazione web ed esegue le operazioni di supporto sulle richieste, oltre a indirizzare le richieste all'applicazione. Inoltre, è in grado di gestire pagine di errore, compressioni, memorizzazioni in cache e il bilanciamento del carico. -Le attività di gestione che non richiedono la conoscenza dello stato dell'applicazione per un proxy inverso consentono ad Express di eseguire attività dell'applicazione specializzate. Per questo motivo, si consiglia di eseguire Express dietro un proxy inverso come [Nginx](https://www.nginx.com/) o [HAProxy](http://www.haproxy.org/) in fase di produzione. +Le attività di gestione che non richiedono la conoscenza dello stato dell'applicazione per un proxy inverso consentono ad Express di eseguire attività dell'applicazione specializzate. 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. diff --git a/it/advanced/best-practice-security.md b/it/advanced/best-practice-security.md old mode 100755 new mode 100644 index 4b237bb6c3..dacbeb615d --- a/it/advanced/best-practice-security.md +++ b/it/advanced/best-practice-security.md @@ -1,25 +1,50 @@ --- layout: page title: Best Practice sulla sicurezza per Express in fase di produzione +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: it -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # Best Practice sulla produzione: Sicurezza ## Panoramica -Il termine *"produzione"* si riferisce alla fase nel ciclo di vita del software quando un'applicazione o API è solitamente disponibile per gli utenti finali o i consumatori. Al contrario, nella fase *"sviluppo"*, si sta ancora scrivendo e verificando il codice e l'applicazione non è aperta ad accessi esterni. Gli ambienti di sistema corrispondenti sono noti rispettivamente come ambienti di *produzione* e di *sviluppo*. +Il termine _"produzione"_ si riferisce alla fase nel ciclo di vita del software quando un'applicazione o API è solitamente disponibile per gli utenti finali o i consumatori. Al contrario, nella fase _"sviluppo"_, si sta ancora scrivendo e verificando il codice e l'applicazione non è aperta ad accessi esterni. Gli ambienti di sistema corrispondenti sono noti rispettivamente come ambienti di _produzione_ e di _sviluppo_. Gli ambienti di sviluppo e produzione sono solitamente configurati diversamente e hanno requisiti molto differenti. Ciò che potrebbe andare bene nello sviluppo potrebbe non essere accettato nella produzione. Ad esempio, in un ambiente di sviluppo è possibile che si richieda una registrazione degli errori ridondante per il processo di debug, mentre la stessa richiesta in un ambiente di produzione potrebbe mettere a rischio la sicurezza. Inoltre, in un ambiente di sviluppo non è necessario preoccuparsi della scalabilità, dell'affidabilità e delle prestazioni, mentre nella produzione è fondamentale tenerne conto. +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + In questo articolo vengono descritte alcune best practice sulla sicurezza per le applicazioni Express distribuite per la produzione. +- [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) + - [hsts](https://github.com/helmetjs/hsts) imposta l'intestazione `Strict-Transport-Security` che rafforza connessioni (HTTP su SSL/TLS) sicure per il server. + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - Se si utilizza `helmet.js`, questa operazione sarà effettuata per conto dell'utente. + - [Reduce fingerprinting](#reduce-fingerprinting) + - [xssFilter](https://github.com/helmetjs/x-xss-protection) imposta `X-XSS-Protection` per abilitare il filtro XSS (Cross-site scripting) nei browser web più recenti. + - [noCache](https://github.com/helmetjs/nocache) imposta le intestazioni `Cache-Control` e Pragma per disabilitare la memorizzazione in cache della parte client. + - [ieNoOpen](https://github.com/helmetjs/ienoopen) imposta `X-Download-Options` per IE8+. + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure) + - [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) rimuove l'intestazione `X-Powered-By`. + - [Additional considerations](#additional-considerations) + ## Non utilizzare versioni obsolete o vulnerabili di Express -Express 2.x e 3.x non sono più supportati. I problemi relativi alla sicurezza e alle prestazioni in queste versioni non verranno risolti. Non utilizzare queste versioni! Se non è stato effettuato l'aggiornamento alla versione 4, consultare la [guida alla migrazione](/{{ page.lang }}/guide/migrating-4.html). +Express 2.x e 3.x non sono più supportati. I problemi relativi alla sicurezza e alle prestazioni in queste versioni non verranno risolti. Non utilizzare queste versioni! Se non è stato effettuato l'aggiornamento alla versione 4, consultare la [guida alla migrazione](/{{ page.lang }}/guide/migrating-4.html). Inoltre, assicurarsi che non si stia utilizzando nessuna delle versioni vulnerabili di Express elencate nella [pagina Aggiornamenti sulla sicurezza](/{{ page.lang }}/advanced/security-updates.html). Nel caso si stia utilizzando una di queste versioni, effettuare l'aggiornamento a una versione aggiornata, preferibilmente l'ultima. @@ -27,53 +52,122 @@ Inoltre, assicurarsi che non si stia utilizzando nessuna delle versioni vulnerab Se l'applicazione utilizza o trasmette dati riservati, utilizzare [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) per proteggere la connessione e i dati. Questa tecnologia codifica i dati prima che vengano inviati dal client al server, proteggendo i dati da alcuni attacchi comuni (e facili) da parte di hacker. Anche se le richieste Ajax e POST possono non essere visibili e "nascoste" nei browser, il relativo traffico di rete è vulnerabile agli attacchi [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) e [man-in-the-middle](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). -Sicuramente si conosce la crittografia SSL (Secure Socket Layer). [TLS non è altro che un miglioramento di SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). In altre parole, se prima si utilizzava SSL, considerare l'opportunità di passare a TLS. Consigliamo di utilizzare Nginx per gestire la TLS. Per informazioni su come configurare correttamente TLS su Nginx (e altri server), consultare [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). +Sicuramente si conosce la crittografia SSL (Secure Socket Layer). [TLS non è altro che un miglioramento di SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). In altre parole, se prima si utilizzava SSL, considerare l'opportunità di passare a TLS. Consigliamo di utilizzare Nginx per gestire la TLS. Per informazioni su come configurare correttamente TLS su Nginx (e altri server), consultare [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). Inoltre, uno strumento molto semplice da utilizzare per ottenere un certificato gratuito TLS è [Let's Encrypt](https://letsencrypt.org/about/), un CA (certificate authority) gratuito, automatizzato e open fornito da [Internet Security Research Group (ISRG)](https://letsencrypt.org/isrg/). +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## Utilizzare Helmet [Helmet](https://www.npmjs.com/package/helmet) è utile per proteggere l'applicazione da alcune vulnerabilità web note configurando le intestazioni HTTP in modo appropriato. -Attualmente, Helmet non è altro che una raccolta di nove funzioni middleware più piccole che impostano le intestazioni HTTP relative alla sicurezza: +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: + +- `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 +- `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 +- `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 -* [csp](https://github.com/helmetjs/csp) imposta l'intestazione `Content-Security-Policy` per impedire attacchi XSS (cross-site scripting) e altri attacchi da altri siti. -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) rimuove l'intestazione `X-Powered-By`. -* [hsts](https://github.com/helmetjs/hsts) imposta l'intestazione `Strict-Transport-Security` che rafforza connessioni (HTTP su SSL/TLS) sicure per il server. -* [ieNoOpen](https://github.com/helmetjs/ienoopen) imposta `X-Download-Options` per IE8+. -* [noCache](https://github.com/helmetjs/nocache) imposta le intestazioni `Cache-Control` e Pragma per disabilitare la memorizzazione in cache della parte client. -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) imposta `X-Content-Type-Options` per impedire ai browser di effettuare l'analisi MIME di una risposta fuori dal contenuto dichiarato. -* [frameguard](https://github.com/helmetjs/frameguard) imposta l'intestazione `X-Frame-Options` per fornire la protezione [clickjacking](https://www.owasp.org/index.php/Clickjacking). -* [xssFilter](https://github.com/helmetjs/x-xss-protection) imposta `X-XSS-Protection` per abilitare il filtro XSS (Cross-site scripting) nei browser web più recenti. +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Installare Helmet come qualsiasi altro modulo: ```bash -$ npm install --save helmet +$ npm install helmet ``` Successivamente, per utilizzarlo nel codice: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### Disattivare almeno l'intestazione X-Powered-By +## Reduce fingerprinting -Se non si desidera Helmet, disattivare almeno l'intestazione `X-Powered-By`. Gli hacker possono utilizzare questa intestazione (abilitata per impostazione predefinita) per rilevare le applicazioni su cui è in esecuzione Express e successivamente avviare attacchi indirizzati in modo specifico. +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. -Quindi, la miglior cosa da fare è disattivare l'intestazione con il metodo `app.disable()`: +By default, Express sends the `X-Powered-By` response header that you can +disable using the `app.disable()` method: ```js app.disable('x-powered-by') ``` -Se si utilizza `helmet.js`, questa operazione sarà effettuata per conto dell'utente. +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## Utilizzare i cookie in modo sicuro @@ -81,16 +175,16 @@ Per fare in modo che i cookie non espongano a rischi l'applicazione, non utilizz Esistono due moduli di sessione cookie middleware principali: -* [express-session](https://www.npmjs.com/package/express-session) che sostituisce il middleware `express.session` integrato a Express 3.x. -* [cookie-session](https://www.npmjs.com/package/cookie-session) che sostituisce il middleware `express.cookieSession` integrato a Express 3.x. +- [express-session](https://www.npmjs.com/package/express-session) che sostituisce il middleware `express.session` integrato a Express 3.x. +- [cookie-session](https://www.npmjs.com/package/cookie-session) che sostituisce il middleware `express.cookieSession` integrato a Express 3.x. -La differenza principale tra questi due moduli è nel modo in cui salvano i dati di sessione dei cookie. Il middleware [express-session](https://www.npmjs.com/package/express-session) memorizza i dati di sessione sul server; salva l'ID sessione nello stesso cookie e non nei dati di sessione. Per impostazione predefinita, utilizza il processo di memorizzazione in-memory e non è progettato per un ambiente di produzione. Nella produzione, sarà necessario configurare un processo di memorizzazione della sessione scalabile; consultare l'elenco di [compatible session stores](https://github.com/expressjs/session#compatible-session-stores). +La differenza principale tra questi due moduli è nel modo in cui salvano i dati di sessione dei cookie. Il middleware [express-session](https://www.npmjs.com/package/express-session) memorizza i dati di sessione sul server; salva l'ID sessione nello stesso cookie e non nei dati di sessione. Per impostazione predefinita, utilizza il processo di memorizzazione in-memory e non è progettato per un ambiente di produzione. Nella produzione, sarà necessario configurare un processo di memorizzazione della sessione scalabile; consultare l'elenco di [compatible session stores](https://github.com/expressjs/session#compatible-session-stores). -Al contrario, il middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implementa la memorizzazione di backup dei cookie: suddivide in serie l'intera sessione per il cookie, piuttosto che una chiave di sessione. Utilizzarlo solo quando i dati di sessione sono relativamente piccoli e facilmente codificati come valori primitivi (piuttosto che oggetti). Poiché si presuppone che i browser supportino almeno 4096 byte per cookie, per non superare il limite, non superare la dimensione di 4093 byte per dominio. Inoltre, fare attenzione perché i dati dei cookie saranno visibili al cliente, quindi, se per qualche motivo devono rimanere sicuri o non visibili, la scelta di utilizzare express-session potrebbe essere quella giusta. +Al contrario, il middleware [cookie-session](https://www.npmjs.com/package/cookie-session) implementa la memorizzazione di backup dei cookie: suddivide in serie l'intera sessione per il cookie, piuttosto che una chiave di sessione. Utilizzarlo solo quando i dati di sessione sono relativamente piccoli e facilmente codificati come valori primitivi (piuttosto che oggetti). Poiché si presuppone che i browser supportino almeno 4096 byte per cookie, per non superare il limite, non superare la dimensione di 4093 byte per dominio. Inoltre, fare attenzione perché i dati dei cookie saranno visibili al cliente, quindi, se per qualche motivo devono rimanere sicuri o non visibili, la scelta di utilizzare express-session potrebbe essere quella giusta. ### Non utilizzare il nome del cookie della sessione predefinito -L'utilizzo del nome del cookie della sessione predefinito potrebbe esporre l'applicazione ad attacchi da parte di hacker. Il problema di sicurezza messo in discussione è simile a quello di `X-Powered-By`: un potenziale hacker potrebbe utilizzarlo per individuare il server e indirizzare gli attacchi di conseguenza. +L'utilizzo del nome del cookie della sessione predefinito potrebbe esporre l'applicazione ad attacchi da parte di hacker. Il problema di sicurezza messo in discussione è simile a quello di `X-Powered-By`: un potenziale hacker potrebbe utilizzarlo per individuare il server e indirizzare gli attacchi di conseguenza. Per evitare questo problema, utilizzare i nomi dei cookie predefiniti; ad esempio, utilizzando il middleware [express-session](https://www.npmjs.com/package/express-session): @@ -100,19 +194,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### Impostare le opzioni di sicurezza dei cookie Impostare le seguenti opzioni per i cookie per aumentare la sicurezza: -* `secure` - Assicura che il browser invii il cookie solo tramite HTTPS. -* `httpOnly` - Assicura che il cookie venga inviato solo tramite HTTP, non JavaScript del client, questa procedura consentirà una protezione da attacchi XSS (cross-site scripting). -* `domain` - Indica il dominio del cookie; utilizzarlo per fare un confronto con il dominio del server in cui è stato richiesto l'URL. Se corrispondono, come fase successiva verificare l'attributo del percorso. -* `path` - Indica il percorso del cookie; utilizzarlo per fare un confronto con il percorso di richiesta. Se questo e il dominio corrispondono, inviare il cookie nella richiesta. -* `expires` - Utilizzarlo per impostare la data di scadenza per i cookie permanenti. +- `secure` - Assicura che il browser invii il cookie solo tramite HTTPS. +- `httpOnly` - Assicura che il cookie venga inviato solo tramite HTTP, non JavaScript del client, questa procedura consentirà una protezione da attacchi XSS (cross-site scripting). +- `domain` - Indica il dominio del cookie; utilizzarlo per fare un confronto con il dominio del server in cui è stato richiesto l'URL. Se corrispondono, come fase successiva verificare l'attributo del percorso. +- `path` - Indica il percorso del cookie; utilizzarlo per fare un confronto con il percorso di richiesta. Se questo e il dominio corrispondono, inviare il cookie nella richiesta. +- `expires` - Utilizzarlo per impostare la data di scadenza per i cookie permanenti. Esempio di utilizzo del middleware [cookie-session](https://www.npmjs.com/package/cookie-session): @@ -132,23 +225,59 @@ app.use(session({ path: 'foo/bar', expires: expiryDate } -}) -) +})) ``` -## Ulteriori informazioni +## 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. -Ecco alcuni consigli sull'eccellente [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Fare riferimento a quel post del blog per tutti i dettagli su questi consigli: +[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) -* Implementare il limite di intervallo per evitare attacchi pesanti al processo di autenticazione. Un modo per effettuare ciò è quello di utilizzare [StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) per rafforzare una policy per il limite di intervallo. In alternativa, è possibile utilizzare il middleware, ad esempio [express-limiter](https://www.npmjs.com/package/express-limiter), ma questo richiede di modificare in parte il codice. -* Filtrare sempre e verificare gli input utente come protezione contro attacchi XSS (cross-site scripting) e command injection. -* Creare una difesa contro attacchi SQL injection utilizzando query con parametri o istruzioni preparate. -* Utilizzare lo strumento [sqlmap](http://sqlmap.org/) open source per rilevare le vulnerabilità SQL injection nell'applicazione. -* Utilizzare gli strumenti [nmap](https://nmap.org/) e [sslyze](https://github.com/nabla-c0d3/sslyze) per verificare la configurazione delle crittografie SSL, delle chiavi e della rinegoziazione come anche la validità del certificato. -* Utilizzare [safe-regex](https://www.npmjs.com/package/safe-regex) per assicurarsi che le espressioni regolari non siano suscettibili ad attacchi [regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). +## Ensure your dependencies are secure -## Evitare altre vulnerabilità note +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. -Prestare attenzione alle avvertenze [Node Security Project](https://npmjs.com/advisories) che potrebbero influenzare Express o altri moduli utilizzati dall'applicazione. Solitamente, il Node Security Project è una risorsa eccellente per questioni di apprendimento e per gli strumenti sulla sicurezza di Node. +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` + +If you want to stay more secure, consider [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: + +```bash +$ npm install -g snyk +$ cd your-app +``` + +Use this command to test your application for vulnerabilities: + +```bash +$ snyk test +``` + +### Evitare altre vulnerabilità note + +Prestare attenzione alle avvertenze [Node Security Project](https://npmjs.com/advisories) che potrebbero influenzare Express o altri moduli utilizzati dall'applicazione. Solitamente, il Node Security Project è una risorsa eccellente per questioni di apprendimento e per gli strumenti sulla sicurezza di Node. Infine, le applicazioni Express, come anche altre applicazioni web, possono essere vulnerabili ad una vasta gamma di attacchi basati su web. Cercare di comprendere al meglio le [vulnerabilità web](https://www.owasp.org/www-project-top-ten/) note e prendere precauzioni per evitarle. + +## Additional considerations + +Ecco alcuni consigli sull'eccellente [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Fare riferimento a quel post del blog per tutti i dettagli su questi consigli: + +- Filtrare sempre e verificare gli input utente come protezione contro attacchi XSS (cross-site scripting) e command injection. +- Creare una difesa contro attacchi SQL injection utilizzando query con parametri o istruzioni preparate. +- Utilizzare lo strumento [sqlmap](http://sqlmap.org/) open source per rilevare le vulnerabilità SQL injection nell'applicazione. +- Utilizzare gli strumenti [nmap](https://nmap.org/) e [sslyze](https://github.com/nabla-c0d3/sslyze) per verificare la configurazione delle crittografie SSL, delle chiavi e della rinegoziazione come anche la validità del certificato. +- Utilizzare [safe-regex](https://www.npmjs.com/package/safe-regex) per assicurarsi che le espressioni regolari non siano suscettibili ad attacchi [regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). + +[helmet]: https://helmetjs.github.io/ \ No newline at end of file diff --git a/it/advanced/developing-template-engines.md b/it/advanced/developing-template-engines.md old mode 100755 new mode 100644 index ba69661c09..421212adad --- a/it/advanced/developing-template-engines.md +++ b/it/advanced/developing-template-engines.md @@ -1,10 +1,10 @@ --- layout: page title: Sviluppo dei motori di template per 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. menu: advanced lang: it -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. +redirect_from: " " --- # Sviluppo dei motori di template per Express @@ -17,9 +17,10 @@ Il seguente codice è un esempio di implementazione di un motore di template mol const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -34,6 +35,7 @@ L'applicazione sarà ora in grado di effettuare il rendering dei file `.ntl`. Cr #title# #message# ``` + Successivamente, creare il seguente percorso nell'applicazione. ```js @@ -41,4 +43,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -Quando si effettua una richiesta per la home page, `index.ntl` verrà visualizzato come HTML. + +Quando si effettua una richiesta per la home page, `index.ntl` verrà visualizzato come HTML. \ No newline at end of file diff --git a/it/advanced/healthcheck-graceful-shutdown.md b/it/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..394218941d --- /dev/null +++ b/it/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: it +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### Esempio + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/it/advanced/security-updates.md b/it/advanced/security-updates.md old mode 100755 new mode 100644 index 2c1846c53a..e524854aac --- a/it/advanced/security-updates.md +++ b/it/advanced/security-updates.md @@ -1,10 +1,10 @@ --- layout: page title: Aggiornamenti sulla sicurezza Express +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: it -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # Aggiornamenti sulla sicurezza @@ -16,32 +16,73 @@ Le vulnerabilità di Node.js influenzano direttamente Express. Pertanto, [verifi L'elenco seguente mostra le vulnerabilità di Express che sono state corrette nell'aggiornamento della versione specificato. +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * Risolta la vulnerabilità del rilevamento del percorso root in `express.static`, `res.sendfile` e `res.sendFile` - * 4.10.7 - * Risolta la vulnerabilità del reindirizzamento aperto 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 - * Risolte le vulnerabilità trasversali della directory 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 può portare alla perdita di `fd` in determinate situazioni che influenzano `express.static` e `res.sendfile`. Le richieste sospette potrebbero causare una perdita di `fd` ed eventualmente il verificarsi di errori `EMFILE` e risposte mancate del server. - * 4.8.0 - * Le matrici sparse che dispongono di indici estremamente elevati nella stringa di query potrebbero causare errori di memoria nel processo e una chiusura anomala del server. - * Gli oggetti di stringa query molto nidificati potrebbero causare un blocco del processo e una mancata risposta da parte del server. +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - Risolta la vulnerabilità del rilevamento del percorso root in `express.static`, `res.sendfile` e `res.sendFile` +- 4.10.7 + - Risolta la vulnerabilità del reindirizzamento aperto 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 + - Risolte le vulnerabilità trasversali della directory 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 può portare alla perdita di `fd` in determinate situazioni che influenzano `express.static` e `res.sendfile`. Le richieste sospette potrebbero causare una perdita di `fd` ed eventualmente il verificarsi di errori `EMFILE` e risposte mancate del server. +- 4.8.0 + - Le matrici sparse che dispongono di indici estremamente elevati nella stringa di query potrebbero causare errori di memoria nel processo e una chiusura anomala del server. + - Gli oggetti di stringa query molto nidificati potrebbero causare un blocco del processo e una mancata risposta da parte del server. ## 3.x - * 3.19.1 - * Risolta la vulnerabilità del rilevamento del percorso root in `express.static`, `res.sendfile` e `res.sendFile` - * 3.19.0 - * Risolta la vulnerabilità del reindirizzamento aperto 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 - * Risolte le vulnerabilità trasversali della directory in `express.static`. - * 3.16.6 - * Node.js 0.10 può portare alla perdita di `fd` in determinate situazioni che influenzano `express.static` e `res.sendfile`. Le richieste sospette potrebbero causare una perdita di `fd` ed eventualmente il verificarsi di errori `EMFILE` e risposte mancate del server. - * 3.16.0 - * Le matrici sparse che dispongono di indici estremamente elevati nella stringa di query potrebbero causare errori di memoria nel processo e una chiusura anomala del server. - * Gli oggetti di stringa query molto nidificati potrebbero causare un blocco del processo e una mancata risposta da parte del server. - * 3.3.0 - * La risposta 404 di un metodo non supportato sovrascrive un tentativo suscettibili in precedenza ad attacchi XSS (cross-site scripting). +
    + **Express 3.x NON È PIU' SUPPORTATO** + +I problemi noti e non noti relativi alla sicurezza presenti in 3.x non sono stati indirizzati dall'ultimo aggiornamento (1 agosto 2015). Si consiglia di utilizzare l'ultima versione di Express. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
    + +- 3.19.1 + - Risolta la vulnerabilità del rilevamento del percorso root in `express.static`, `res.sendfile` e `res.sendFile` +- 3.19.0 + - Risolta la vulnerabilità del reindirizzamento aperto 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 + - Risolte le vulnerabilità trasversali della directory in `express.static`. +- 3.16.6 + - Node.js 0.10 può portare alla perdita di `fd` in determinate situazioni che influenzano `express.static` e `res.sendfile`. Le richieste sospette potrebbero causare una perdita di `fd` ed eventualmente il verificarsi di errori `EMFILE` e risposte mancate del server. +- 3.16.0 + - Le matrici sparse che dispongono di indici estremamente elevati nella stringa di query potrebbero causare errori di memoria nel processo e una chiusura anomala del server. + - Gli oggetti di stringa query molto nidificati potrebbero causare un blocco del processo e una mancata risposta da parte del server. +- 3.3.0 + - La risposta 404 di un metodo non supportato sovrascrive un tentativo suscettibili in precedenza ad attacchi XSS (cross-site scripting). \ No newline at end of file diff --git a/it/api.md b/it/api.md old mode 100755 new mode 100644 index 487116f56f..1db61708d5 --- a/it/api.md +++ b/it/api.md @@ -1,28 +1,21 @@ --- layout: api version: 5x -title: Express 4.x - Riferimento API +title: Express 5.x - Riferimento API +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: it -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    API 4.x

    - - - {% include api/en/4x/express.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
    diff --git a/it/changelog/index.md b/it/changelog/index.md new file mode 100644 index 0000000000..20d8b7df9d --- /dev/null +++ b/it/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: it +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/it/guide/behind-proxies.md b/it/guide/behind-proxies.md old mode 100755 new mode 100644 index b1fa7b0413..b7835b0705 --- a/it/guide/behind-proxies.md +++ b/it/guide/behind-proxies.md @@ -1,20 +1,22 @@ --- layout: page title: Express con i proxy +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. menu: guide lang: it -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. +redirect_from: " " --- # Express con i proxy -Quando si esegue un'applicazione Express con un proxy, impostare (utilizzando [app.set()](/{{ page.lang }}/4x/api.html#app.set)) la variabile dell'applicazione `trust proxy` su uno dei valori elencati nella seguente tabella. +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.
    -Anche se l'applicazione non presenterà errori nell'esecuzione se la variabile dell'applicazione `trust proxy` non è impostata, registrerà comunque in modo errato l'indirizzo IP del proxy come indirizzo IP del client a meno che non venga configurato `trust proxy`. +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.
    +Quando si esegue un'applicazione Express con un proxy, impostare (utilizzando [app.set()](/{{ page.lang }}/4x/api.html#app.set)) la variabile dell'applicazione `trust proxy` su uno dei valori elencati nella seguente tabella. + @@ -24,16 +26,20 @@ Anche se l'applicazione non presenterà errori nell'esecuzione se la variabile d Se impostato su `true`, l'indirizzo IP del client viene considerato come la voce a sinistra dell'intestazione `X-Forwarded-*`. Se impostato su `false`, significa che l'applicazione abbia una connessione diretta a Internet e l'indirizzo IP del client sia arrivato da `req.connection.remoteAddress`. Questa è l'impostazione predefinita. + +
    +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. +
    - + - +
    TipoValore
    Indirizzi IPIP addresses -Un indirizzo IP, una subnet o un array di indirizzi IP e subnet a cui fornire attendibilità. Il seguente elenco mostra i nomi di subnet preconfigurate: +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: -* 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` +- 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` È possibile impostare gli indirizzi IP in uno dei seguenti modi: @@ -44,20 +50,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -Quando specificati, gli indirizzi IP o le subnet vengono esclusi dal processo di determinazione dell'indirizzo e l'indirizzo IP non attendibile più vicino al server delle applicazioni viene considerato come indirizzo IP del client. +Quando specificati, gli indirizzi IP o le subnet vengono esclusi dal processo di determinazione dell'indirizzo e l'indirizzo IP non attendibile più vicino al server delle applicazioni viene considerato come indirizzo IP del client. 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. +
    Numero -Considerare attendibile una parte del percorso `n`th dal server proxy principale come client. +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. + +
    +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. +
    FunzioneFunction -Implementazione attendibilità personalizzata. Questa funzione deve essere utilizzata solo da esperti. - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -65,12 +75,13 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
    -Se si imposta un valore non `false` `trust proxy` si verificano tre importanti cambiamenti: +Enabling `trust proxy` will have the following impact:
    • Il valore di [req.hostname](/{{ page.lang }}/api.html#req.hostname) viene rilevato dalla serie di valori nell'intestazione `X-Forwarded-Host`, la quale può essere impostata dal client o dal proxy. diff --git a/it/guide/database-integration.md b/it/guide/database-integration.md old mode 100755 new mode 100644 index a1851c0e7d..44a3ba2c5f --- a/it/guide/database-integration.md +++ b/it/guide/database-integration.md @@ -1,230 +1,284 @@ --- layout: page title: Integrazione database Express +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: it -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # Integrazione database L'aggiunta della funzionalità che consente di connettere i database alle applicazioni Express è solo un modo per caricare un driver Node.js appropriato per il database nell'applicazione. Questo documento spiega brevemente come aggiungere e utilizzare alcuni dei moduli Node.js più noti per i sistemi database nell'applicazione Express: -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
      -Questi driver di database sono tra quelli più disponibili. Per altre opzioni, +Questi driver di database sono tra quelli più disponibili. Per altre opzioni, effettuare una ricerca nel sito [npm](https://www.npmjs.com/).
      - - ## Cassandra **Modulo**: **Installazione** [cassandra-driver](https://github.com/datastax/nodejs-driver) +### ```bash $ npm install cassandra-driver ``` -**Esempio** +### Esempio -
      -
      -var cassandra = require('cassandra-driver');
      -var client = new cassandra.Client({ contactPoints: ['localhost']});
      +```js
      +const cassandra = require('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)
      +
      +### 
      +
      +```bash
      +$ npm install couchbase
      +```
      +
      +### Esempio
      +
      +```js
      +const couchbase = require('couchbase')
      +const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')
       
      -client.execute('select key from system.local', function(err, result) {
      -  if (err) throw err;
      -  console.log(result.rows[0]);
      -});
      -
      -
      +// 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**: **Installazione** [nano](https://github.com/dscape/nano) +### ```bash $ npm install nano ``` -**Esempio** +### Esempio -
      -
      -var nano = require('nano')('http://localhost:5984');
      -nano.db.create('books');
      -var books = nano.db.use('books');
      -
      -//Insert a book document in the books database
      -books.insert({name: 'The Art of war'}, null, function(err, body) {
      -  if (!err){
      -    console.log(body);
      -  }
      -});
      +```js
      +const nano = require('nano')('http://localhost:5984')
      +nano.db.create('books')
      +const books = nano.db.use('books')
       
      -//Get a list of all books
      -books.list(function(err, body){
      -  console.log(body.rows);
      -});
      -
      -
      +// Insert a book document in the books database +books.insert({ name: 'The Art of war' }, null, (err, body) => { + if (err) { + console.log(err) + } else { + console.log(body) + } +}) - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **Modulo**: **Installazione** [levelup](https://github.com/rvagg/node-levelup) +### ```bash $ npm install level levelup leveldown ``` -**Esempio** - -
      -
      -var levelup = require('levelup');
      -var db = levelup('./mydb');
      +### Esempio
       
      -db.put('name', 'LevelUP', function (err) {
      +```js
      +const levelup = require('levelup')
      +const db = levelup('./mydb')
       
      -  if (err) return console.log('Ooops!', err);
      -  db.get('name', function (err, value) {
      -    if (err) return console.log('Ooops!', err);
      -    console.log('name=' + value);
      -  });
      +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**: **Installazione** [mysql](https://github.com/felixge/node-mysql/) +### ```bash $ npm install mysql ``` -**Esempio** +### Esempio -
      -
      -var mysql      = require('mysql');
      -var connection = mysql.createConnection({
      -  host     : 'localhost',
      -  user     : 'dbuser',
      -  password : 's3kreee7'
      -});
      +```js
      +const mysql = require('mysql')
      +const connection = mysql.createConnection({
      +  host: 'localhost',
      +  user: 'dbuser',
      +  password: 's3kreee7',
      +  database: 'my_db'
      +})
       
      -connection.connect();
      +connection.connect()
       
      -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      -  if (err) throw err;
      -  console.log('The solution is: ', rows[0].solution);
      -});
      +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
      +  if (err) throw err
       
      -connection.end();
      -
      -
      + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **Modulo**: **Installazione** [mongodb](https://github.com/mongodb/node-mongodb-native) +### ```bash $ npm install mongodb ``` -**Esempio** +### Example (v2.\*) -
      -
      -var MongoClient = require('mongodb').MongoClient;
      +```js
      +const MongoClient = require('mongodb').MongoClient
       
      -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
      -  if (err) {
      -    throw err;
      -  }
      -  db.collection('mammals').find().toArray(function(err, result) {
      -    if (err) {
      -      throw err;
      -    }
      -    console.log(result);
      -  });
      -});
      -
      -
      +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err -Se si desidera un driver del modello oggetto per MongoDB, consultare [Mongoose](https://github.com/LearnBoost/mongoose). + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err - + console.log(result) + }) +}) +``` -## Neo4j +### Example (v3.\*) -**Modulo**: **Installazione** -[apoc](https://github.com/hacksparrow/apoc) +```js +const MongoClient = require('mongodb').MongoClient +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err -```bash -$ npm install apoc + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) ``` -**Esempio** +Se si desidera un driver del modello oggetto per MongoDB, consultare [Mongoose](https://github.com/LearnBoost/mongoose). + +## Neo4j -
       
      -var apoc = require('apoc');
      -
      -apoc.query('match (n) return n').exec().then(
      -  function (response) {
      -    console.log(response);
      -  },
      -  function (fail) {
      -    console.log(fail);
      -  }
      -);
      -
      -
      +var apoc = require('apoc');apoc.query('match (n) return n').exec().then( +function (response) { +console.log(response); +}, +function (fail) { +console.log(fail); +} +); + +### - +```bash +$ npm install neo4j-driver +``` + +### Esempio + +```js +const neo4j = require('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) -### Installazione +### - NOTA: [Vedi i prerequisiti di installazione](https://github.com/oracle/node-oracledb#-installation). +NOTA: [Vedi i prerequisiti di installazione](https://github.com/oracle/node-oracledb#-installation). ```bash $ npm install oracledb @@ -264,140 +318,181 @@ async function getEmployee (empId) { getEmployee(101) ``` - - ## PostgreSQL -**Modulo**: **Installazione** -[pg](https://github.com/brianc/node-postgres) +**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise) +### ```bash -$ npm install pg +$ npm install pg-promise ``` -**Esempio** - -
      -
      -var pg = require('pg');
      -var conString = "postgres://username:password@localhost/database";
      -
      -pg.connect(conString, function(err, client, done) {
      -
      -  if (err) {
      -    return console.error('error fetching client from pool', err);
      -  }
      -  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
      -    done();
      -    if (err) {
      -      return console.error('error running query', err);
      -    }
      -    console.log(result.rows[0].number);
      -  });
      -
      -});
      -
      -
      +### Esempio - +```js +const pgp = require('pg-promise')(/* options */) +const db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **Modulo**: **Installazione** [redis](https://github.com/mranney/node_redis) +### ```bash $ npm install redis ``` -**Esempio** +### Esempio -
      -
      -var client = require('redis').createClient();
      +```js
      +const redis = require('redis')
      +const client = redis.createClient()
      +
      +client.on('error', (err) => {
      +  console.log(`Error ${err}`)
      +})
       
      -client.on('error', function (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.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:`)
       
      -client.hkeys('hash key', function (err, replies) {
      +  replies.forEach((reply, i) => {
      +    console.log(`    ${i}: ${reply}`)
      +  })
       
      -  console.log(replies.length + ' replies:');
      -  replies.forEach(function (reply, i) {
      -    console.log('    ' + i + ': ' + reply);
      -  });
      +  client.quit()
      +})
      +```
       
      -  client.quit();
      +## SQL Server
       
      -});
      -
      -
      +**Module**: [tedious](https://github.com/tediousjs/tedious) - +### + +```bash +$ npm install tedious +``` + +### Esempio + +```js +const Connection = require('tedious').Connection +const Request = require('tedious').Request + +const config = { + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } +} + +const connection = new Connection(config) + +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **Modulo**: **Installazione** [sqlite3](https://github.com/mapbox/node-sqlite3) +### ```bash $ npm install sqlite3 ``` -**Esempio** - -
      -
      -var sqlite3 = require('sqlite3').verbose();
      -var db = new sqlite3.Database(':memory:');
      +### Esempio
       
      -db.serialize(function() {
      +```js
      +const sqlite3 = require('sqlite3').verbose()
      +const db = new sqlite3.Database(':memory:')
       
      -  db.run('CREATE TABLE lorem (info TEXT)');
      -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
      +db.serialize(() => {
      +  db.run('CREATE TABLE lorem (info TEXT)')
      +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
       
      -  for (var i = 0; i < 10; i++) {
      -    stmt.run('Ipsum ' + i);
      +  for (let i = 0; i < 10; i++) {
      +    stmt.run(`Ipsum ${i}`)
         }
       
      -  stmt.finalize();
      -
      -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
      -    console.log(row.id + ': ' + row.info);
      -  });
      -});
      +  stmt.finalize()
       
      -db.close();
      -
      -
      + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) + }) +}) - +db.close() +``` ## ElasticSearch **Modulo**: **Installazione** [elasticsearch](https://github.com/elastic/elasticsearch-js) +### ```bash $ npm install elasticsearch ``` -**Esempio** +### Esempio -
      -
      -var elasticsearch = require('elasticsearch');
      -var client = elasticsearch.Client({
      +```js
      +const elasticsearch = require('elasticsearch')
      +const client = elasticsearch.Client({
         host: 'localhost:9200'
      -});
      +})
       
       client.search({
         index: 'books',
      @@ -410,10 +505,9 @@ client.search({
             }
           }
         }
      -}).then(function(response) {
      -  var hits = response.hits.hits;
      -}, function(error) {
      -  console.trace(error.message);
      -});
      -
      -
      +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/it/guide/debugging.md b/it/guide/debugging.md old mode 100755 new mode 100644 index ea7f09ba44..621a78c879 --- a/it/guide/debugging.md +++ b/it/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Debug di Express +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: it -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # Debug di Express @@ -19,7 +19,7 @@ $ DEBUG=express:* node index.js Su Windows, utilizzare il comando corrispondente. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` L'esecuzione di questo comando sull'applicazione predefinita generata da [Programma di creazione express](/{{ page.lang }}/starter/generator.html) consentirà di stampare il seguente output: @@ -60,11 +60,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -105,3 +105,27 @@ $ DEBUG=sample-app:* node ./bin/www ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/it/guide/error-handling.md b/it/guide/error-handling.md old mode 100755 new mode 100644 index 7b93048653..ec4fcd5839 --- a/it/guide/error-handling.md +++ b/it/guide/error-handling.md @@ -1,16 +1,197 @@ --- layout: page title: Gestione degli errori di Express +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: it -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # Gestione degli errori +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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. Ad esempio: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + Definire le funzioni middleware di gestione degli errori nello stesso modo in cui si definiscono altre funzioni middleware, ad eccezione delle funzioni di gestione degli errori che hanno quattro argomenti invece di tre: +`(err, req, res, next)`. Ad esempio: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +Se si dispone di un gestore route con più funzioni di callback, è possibile utilizzare il parametro `route` per passare al successivo gestore route. +Ad esempio: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +Se si trasmette qualsiasi cosa alla funzione `next()` (ad eccezione della stringa `'route'`), Express considera la richiesta corrente come se contenesse errori e ignorerà qualsiasi altra funzione middleware e routing di non gestione degli errori restante. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. Ad esempio: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. Ad esempio: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +You could also use a chain of handlers to rely on synchronous error +catching, by reducing the asynchronous code to something trivial. Ad esempio: + +```js +app.get('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## Il gestore errori predefinito + +Express viene fornito insieme a un gestore degli errori integrato, il quale gestisce gli errori che potrebbero verificarsi nell'applicazione. Questa funzione middleware di gestione degli errori viene aggiunta alla fine dello stack della funzione middleware. + +Se un errore viene ignorato e passato a `next()` e non viene gestito in un gestore +degli errori, verrà gestito dal gestore errori integrato; l'errore verrà scritto sul client con la traccia +stack. La traccia stack non viene inclusa nell'ambiente di produzione. + +
      +Impostare la variabile di ambiente `NODE_ENV` su `production`, per eseguire l'applicazione nella modalità di produzione. +
      + +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. + +Se si chiama `next()` con un errore dopo che si è iniziato a scrivere la risposta +(ad esempio, se si riscontra un errore mentre si esegue lo streaming della +risposta al client) il gestore degli errori predefinito di Express chiude la connessione +e rifiuta la richiesta. + +Pertanto, quando si aggiunge un gestore degli errori personalizzato, si consiglia di associarlo al meccanismo +di gestione degli errori predefinito in Express, quando le intestazioni +sono state già inviate al client: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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)`. Ad esempio: ```js @@ -26,7 +207,10 @@ Si definisce il middleware di gestione degli errori per ultimo, successivamente const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -44,7 +228,10 @@ effettuate utilizzando `XHR` e quelle senza, è necessario utilizzare i seguenti const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -63,6 +250,8 @@ function logErrors (err, req, res, next) { Inoltre, in questo esempio, `clientErrorHandler` viene definito come segue; in questo caso, l'errore viene chiaramente tramandato al successivo: +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) { if (req.xhr) { @@ -72,6 +261,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + La funzione "catch-all" `errorHandler` potrebbe essere implementata come segue: ```js @@ -81,17 +271,16 @@ function errorHandler (err, req, res, next) { } ``` -Se si trasmette qualsiasi cosa alla funzione `next()` (ad eccezione della stringa `'route'`), Express considera la richiesta corrente come se contenesse errori e ignorerà qualsiasi altra funzione middleware e routing di non gestione degli errori restante. Se si desidera gestire quell'errore in qualche modo, sarà necessario creare una route di gestione degli errori come descritto nella sezione successiva. - -Se si dispone di un gestore route con più funzioni di callback, è possibile utilizzare il parametro `route` per passare al successivo gestore route. Ad esempio: +If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. Ad esempio: ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -100,39 +289,9 @@ app.get('/a_route_behind_paywall', }) }) ``` + In questo esempio, il gestore `getPaidContent` verrà ignorato ma qualsiasi altro gestore rimanente in `app` per `/a_route_behind_paywall` verrà eseguito senza interruzione.
      Le chiamate a `next()` e `next(err)` indicano che il gestore corrente è completo e in che stato si trova. `next(err)` ignorerà tutti gli handler rimanenti nella catena ad eccezione degli handler configurati per gestire gli errori come descritto sopra.
      - -## Il gestore errori predefinito - -Express viene fornito insieme a un gestore degli errori integrato, il quale gestisce gli errori che potrebbero verificarsi nell'applicazione. Questa funzione middleware di gestione degli errori viene aggiunta alla fine dello stack della funzione middleware. - -Se un errore viene ignorato e passato a `next()` e non viene gestito in un gestore -degli errori, verrà gestito dal gestore errori integrato; l'errore verrà scritto sul client con la traccia -stack. La traccia stack non viene inclusa nell'ambiente di produzione. - -
      -Impostare la variabile di ambiente `NODE_ENV` su `production`, per eseguire l'applicazione nella modalità di produzione. -
      - -Se si chiama `next()` con un errore dopo che si è iniziato a scrivere la risposta -(ad esempio, se si riscontra un errore mentre si esegue lo streaming della -risposta al client) il gestore degli errori predefinito di Express chiude la connessione -e rifiuta la richiesta. - -Pertanto, quando si aggiunge un gestore degli errori personalizzato, si consiglia di associarlo al meccanismo -di gestione degli errori predefinito in Express, quando le intestazioni -sono state già inviate al client: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/it/guide/migrating-4.md b/it/guide/migrating-4.md old mode 100755 new mode 100644 index 69dee52423..a6e8573d36 --- a/it/guide/migrating-4.md +++ b/it/guide/migrating-4.md @@ -1,10 +1,10 @@ --- layout: page title: Migrazione a 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. menu: guide lang: it -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. +redirect_from: " " --- # Passaggio a Express 4 @@ -26,7 +26,7 @@ Argomenti di questo articolo: Sono state apportate diverse modifiche importanti alla versione Express 4:
        -
      • Modifiche al sistema middleware e al core di Express. Le dipendenze su Connect e il middleware integrato sono state rimosse, pertanto è necessario aggiungere il middleware manualmente. +
      • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
      • Modifiche al sistema di routing.
      • Altre modifiche.
      • @@ -34,8 +34,8 @@ Sono state apportate diverse modifiche importanti alla versione Express 4: Consultare inoltre: -* [Nuove funzioni 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) +- [Nuove funzioni 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)

        Modifiche al sistema middleware e al core di Express @@ -56,7 +56,7 @@ middleware richiesto per eseguire l'applicazione. Seguire semplicemente questi p La seguente tabella elenca il middleware Express 3 e le relative controparti in Express 4. - + @@ -88,7 +88,7 @@ La seguente tabella elenca il middleware Express 3 e le relative controparti in -
        Express 3Express 4
        Express 3Express 4
        express.bodyParser body-parser + multer
        serve-index
        express.static serve-static
        +

    Segue l'[elenco completo](https://github.com/senchalabs/connect#middleware) di middleware Express 4. @@ -102,11 +102,12 @@ Nella versione 4 è possibile utilizzare un parametro di variabile per definire Ad esempio: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

    Il sistema di routing

    @@ -119,8 +120,9 @@ Il modo in cui viene definita la route non è cambiato ma il sistema di routing funzioni utili per organizzare le route: {: .doclist } -* Un nuovo metodo, `app.route()`, per creare handler di route a catena per un percorso route. -* Un nuova classe, `express.Router`, per creare handler di route assemblabili in modo modulare. + +- Un nuovo metodo, `app.route()`, per creare handler di route a catena per un percorso route. +- Un nuova classe, `express.Router`, per creare handler di route assemblabili in modo modulare.

    Metodo app.route()

    @@ -132,13 +134,13 @@ Segue un esempio di handler di route a catena definiti utilizzando la funzione ` ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -160,16 +162,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -181,7 +183,7 @@ Successivamente, caricare il modulo router nell'applicazione: ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -197,7 +199,7 @@ Altre modifiche La seguente tabella elenca altre piccole ma importanti modifiche applicate a Express 4: - + @@ -307,7 +309,7 @@ La funzionalità ora è limitata alla sola impostazione del valore cookie di bas `res.cookie()` per aggiungere altre funzionalità. -
    Oggetto Descrizione
    +

    Esempio di migrazione dell'applicazione

    @@ -351,7 +353,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -391,15 +393,15 @@ $ npm install serve-favicon morgan method-override express-session body-parser m Apportare le seguenti modifiche a `app.js`: 1. Le funzioni middleware di Express integrate `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` e - `express.errorHandler` non sono più disponibili nell'oggetto - `express`. È necessario installare le funzioni alternative - manualmente e caricarle sull'applicazione. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` e + `express.errorHandler` non sono più disponibili nell'oggetto + `express`. È necessario installare le funzioni alternative + manualmente e caricarle sull'applicazione. 2. Non è più necessario caricare la funzione `app.router`. - Non è un oggetto applicazione Express 4 valido, pertanto rimuovere il codice - `app.use(app.router);`. + Non è un oggetto applicazione Express 4 valido, pertanto rimuovere il codice + `app.use(app.router);`. 3. Assicurarsi che le funzioni middleware siano state caricate nell'ordine corretto - caricare `errorHandler` dopo aver caricato le route dell'applicazione. @@ -422,7 +424,7 @@ L'esecuzione del comando `npm` aggiornerà `package.json` come segue: "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -488,7 +490,7 @@ server.listen(app.get('port'), () => { A meno che non sia necessario gestire direttamente il modulo `http` (socket.io/SPDY/HTTPS), il relativo caricamento non è richiesto e l'applicazione può essere avviata semplicemente come segue: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -505,14 +507,14 @@ $ node . ``` Caricare [http://localhost:3000](http://localhost:3000) - e visualizzare la home page sottoposta a rendering da Express 4. +e visualizzare la home page sottoposta a rendering da Express 4.

    Aggiornamento al programma di creazione dell'applicazione Express 4

    Lo strumento della riga comandi per generare un'applicazione Express è sempre - `express` ma per effettuare l'aggiornamento alla nuova versione è necessario disinstallare - il programma di creazione dell'applicazione di Express 3 e successivamente installare il nuovo - `express-generator`. +`express` ma per effettuare l'aggiornamento alla nuova versione è necessario disinstallare +il programma di creazione dell'applicazione di Express 3 e successivamente installare il nuovo +`express-generator`.

    Installazione

    @@ -543,9 +545,10 @@ di Express 4. L'utilizzo e le opzioni del comando sono rimaste quasi gli stessi, con le seguenti eccezioni: {: .doclist } -* È stata rimossa l'opzione `--sessions`. -* È stata rimossa l'opzione `--jshtml`. -* È stata aggiunta l'opzione `--hogan` per supportare [Hogan.js](http://twitter.github.io/hogan.js/). + +- È stata rimossa l'opzione `--sessions`. +- È stata rimossa l'opzione `--jshtml`. +- È stata aggiunta l'opzione `--hogan` per supportare [Hogan.js](http://twitter.github.io/hogan.js/).

    Esempio

    @@ -591,7 +594,7 @@ cancellare la riga in cui viene riportata la dicitura `module.exports = app;` al ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -605,6 +608,6 @@ var debug = require('debug')('app4') Successivamente, modificare `"start": "node ./bin/www"` nel file `package.json` in `"start": "node app.js"`. È stata spostata la funzionalità di `./bin/www` di nuovo in -`app.js`. Questa modifica non è consigliata, ma questa prova consente di comprendere in che modo funziona +`app.js`. Questa modifica non è consigliata, ma questa prova consente di comprendere in che modo funziona il file `./bin/www` e perché il file `app.js` non si avvia più in modo autonomo. diff --git a/it/guide/migrating-5.md b/it/guide/migrating-5.md old mode 100755 new mode 100644 index 949204a43c..1f0ed5b53a --- a/it/guide/migrating-5.md +++ b/it/guide/migrating-5.md @@ -1,32 +1,45 @@ --- layout: page title: Migrazione a Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: it -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # Passaggio a Express 5

    Panoramica

    -Express 5.0 si trova ancora nella fase di release alfa, ma di seguito vengono mostrate le modifiche che verranno riportate nel release e come migrare l'applicazione Express 4 a Express 5. +Express 5 non è molto differente da Express 4: le modifiche all'API non sono così importanti come quelle che sono state effettuate nel passaggio dalla 3.0 alla 4.0. Anche se le API di base sono le stesse, ci sono comunque delle modifiche importanti; in altre parole, un programma Express 4 esistente potrebbe non funzionare se lo si aggiorna per utilizzare Express 5. -Express 5 non è molto differente da Express 4: le modifiche all'API non sono così importanti come quelle che sono state effettuate nel passaggio dalla 3.0 alla 4.0. Anche se le API di base sono le stesse, ci sono comunque delle modifiche importanti; in altre parole, un programma Express 4 esistente potrebbe non funzionare se lo si aggiorna per utilizzare Express 5. +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -Per installare l'ultima alfa e per vedere in anteprima Express 5, immettere il seguente comando nella directory root dell'applicazione: - -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` È quindi possibile eseguire i test automatizzati per trovare errori e correggere i problemi in base agli aggiornamenti elencati di seguito. Dopo aver gestito gli errori del test, avviare l'applicazione per verificare gli errori. Si noterà subito se l'applicazione utilizza qualsiasi metodo o proprietà non supportati. -

    Modifiche in Express 5

    +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` -Di seguito viene riportato l'elenco di modifiche (a partire dal release alfa) che influenzeranno gli utenti di Express. -Consultare [pull request](https://github.com/expressjs/express/pull/2237) per un elenco di funzioni pianificate. +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

    Modifiche in Express 5

    **Proprietà e metodi rimossi** @@ -38,26 +51,40 @@ Consultare [pull request](https://github.com/expressjs/express/pull/2237) per un
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
  • -**Modificato** +**Miglioramenti** -**Miglioramenti** +**Modificato** -

    Proprietà e metodi rimossi

    +### Proprietà e metodi rimossi Se si utilizza uno dei seguenti metodi o proprietà nell'applicazione, quest'ultima si chiuderà in modo anomalo. Quindi, sarà necessario modificare l'applicazione dopo aver effettuato l'aggiornamento alla versione 5. @@ -65,7 +92,30 @@ Se si utilizza uno dei seguenti metodi o proprietà nell'applicazione, quest'ult Express 5 non supporta più la funzione `app.del()`. Se si utilizza questa funzione verrà generato un errore. Per registrare le route HTTP DELETE, utilizzare al contrario la funzione `app.delete()`. -Inizialmente era stato utilizzato il comando `del` al posto di `delete`, perché `delete` è una parola chiave riservata in JavaScript. Tuttavia, a partire da ECMAScript 6, `delete` e altre parole chiave riservate possono essere utilizzate liberamente come nomi di proprietà. È possibile leggere la documentazione in cui viene descritto come si è arrivati alla deprecazione della funzione `app.del` qui. +Inizialmente era stato utilizzato il comando `del` al posto di `delete`, perché `delete` è una parola chiave riservata in JavaScript. Tuttavia, a partire da ECMAScript 6, `delete` e altre parole chiave riservate possono essere utilizzate liberamente come nomi di proprietà. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

    app.param(fn)

    @@ -73,13 +123,44 @@ La firma `app.param(fn)` è stata utilizzata per modificare la funzionalità del

    Nomi di metodi al plurale

    -I seguenti nomi di metodi sono stati messi al plurale. In Express 4, l'utilizzo di vecchi metodi ha dato origine ad avvisi di deprecazione. Express 5 non li supporta più in alcun modo: +I seguenti nomi di metodi sono stati messi al plurale. In Express 4, l'utilizzo di vecchi metodi ha dato origine ad avvisi di deprecazione. Express 5 non li supporta più in alcun modo: + +`req.acceptsLanguage()` è stato sostituito con `req.acceptsLanguages()`. `req.acceptsCharset()` è stato sostituito con `req.acceptsCharsets()`. `req.acceptsEncoding()` è stato sostituito con `req.acceptsEncodings()`. -`req.acceptsLanguage()` è stato sostituito con `req.acceptsLanguages()`. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    Due punti (:) nel nome per app.param(name, fn)

    @@ -91,43 +172,334 @@ Questa procedura non dovrebbe influenzare il codice se si segue correttamente la Questo metodo poco chiaro e molto pericoloso che si utilizzava per richiamare i dati del modulo è stato rimosso. Ora sarà necessario ricercare il nome del parametro inviato nell'oggetto `req.params`, `req.body` o `req.query`. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

    res.json(obj, status)

    Express 5 non supporta più la firma `res.json(obj, status)`. Al contrario, impostare lo stato e successivamente associarlo al metodo `res.json()` come segue: `res.status(status).json(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

    res.jsonp(obj, status)

    Express 5 non supporta più la firma `res.jsonp(obj, status)`. Al contrario, impostare lo stato e successivamente associarlo al metodo `res.jsonp()` come segue: `res.status(status).jsonp(obj)`. -

    res.send(body, status)

    +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    Express 5 non supporta più la firma `res.send(obj, status)`. Al contrario, impostare lo stato e successivamente associarlo al metodo `res.send()` come segue: `res.status(status).send(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

    res.send(body, status)

    + +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

    res.send(status)

    -Express 5 non supporta più la firma res.send(status), dove *`status`* è un numero. Al contrario, utilizzare la funzione `res.sendStatus(statusCode)`, la quale imposta il codice di stato dell'intestazione della risposta HTTP e invia la versione di testo del codice: "Non trovato", "Errore interno del server" e così via. +Express 5 non supporta più la firma res.send(status), dove _`status`_ è un numero. Al contrario, utilizzare la funzione `res.sendStatus(statusCode)`, la quale imposta il codice di stato dell'intestazione della risposta HTTP e invia la versione di testo del codice: "Non trovato", "Errore interno del server" e così via. Se è necessario inviare un numero utilizzando la funzione `res.send()`, citare il numero per convertirlo in una stringa, in modo tale che Express non lo interpreti come un tentativo di utilizzo di una firma vecchia non supportata. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +``` +

    res.sendfile()

    La funzione `res.sendfile()` è stata sostituita da una versione in cui ogni frase composta inizia con una lettera maiuscola che utilizza ad esempio `res.sendFile()` in Express 5. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. È stata considerata obsoleta a partire dalla v4.11.0 e non è più supportata in 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. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    Modificato

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. Ad esempio: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +Ad esempio: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    L'oggetto `app.router`, che era stato rimosso in Express 4, è ritornato in Express 5. Nella nuova versione, questo oggetto è solo un riferimento al router Express di base, diversamente da Express 3, in cui un'applicazione aveva il compito esplicito di caricarlo. +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

    req.host

    In Express 4, la funzione `req.host` andava a rimuovere in modo non corretto il numero porta nel caso fosse stato presente. In Express 5 il numero porta viene conservato.

    req.query

    -In Express 4.7 e da Express 5 in avanti, l'opzione parser query può accettare `false` per disabilitare l'analisi della stringa query quando si desidera utilizzare la propria funzione per la logica di analisi della stringa 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". -

    Miglioramenti

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### Miglioramenti

    res.render()

    Questo metodo ora potenzia i funzionamenti asincroni per tutti i motori di visualizzazione, evitando i bug causati dai motori di visualizzazione con un'implementazione sincrona e che violavano l'interfaccia consigliata. + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/it/guide/overriding-express-api.md b/it/guide/overriding-express-api.md new file mode 100644 index 0000000000..22cf08e11e --- /dev/null +++ b/it/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: it +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/it/guide/routing.md b/it/guide/routing.md old mode 100755 new mode 100644 index c2f93b75ae..bf6c4c4e66 --- a/it/guide/routing.md +++ b/it/guide/routing.md @@ -1,17 +1,28 @@ --- layout: page title: Routing Express +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: it -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # Routing -*Routing* fa riferimento alla definizione di endpoint dell'applicazione (URI) e alla loro modalità di risposta alle richieste del client. +_Routing_ fa riferimento alla definizione di endpoint dell'applicazione (URI) e alla loro modalità di risposta alle richieste del client. Per un'introduzione al concetto di routing, consultare la sezione [Routing di base](/{{ page.lang }}/starter/basic-routing.html). +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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. + Il codice seguente è un esempio di una route veramente di base. ```js @@ -42,17 +53,11 @@ app.post('/', (req, res) => { }) ``` -Express supporta i seguenti metodi di routing che corrispondono a metodi HTTP: `get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search` e `connect`. - -
    -In metodi di route che si convertono in nomi di variabili JavaScript non validi, utilizzare la notazione tra parentesi. Ad esempio, -`app['m-search']('/', function ...` -
    +Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). Esiste un metodo di routing speciale, `app.all()`, che non deriva da alcun metodo HTTP. Questo metodo viene utilizzato per caricare funzioni middleware in un percorso per tutti i metodi di richiesta. -Nell'esempio seguente, l'handler verrà eseguito per richieste a "/secret" se si stanno utilizzando GET, POST, PUT, DELETE, o qualsiasi altro metodo di richiesta HTTP supportato nel [modulo http](https://nodejs.org/api/http.html#http_http_methods). - ```js app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') @@ -64,15 +69,32 @@ app.all('/secret', (req, res, next) => { I percorsi di route, in combinazione con un metodo di richiesta, definiscono gli endpoint a cui possono essere rivolte richieste. I percorsi di route possono essere stringhe, modelli di stringa o espressioni regolari. -
    - Express utilizza [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) per la corrispondenza dei percorsi di route; consultare la documentazione relativa a path-to-regexp per tutte le possibilità di definizione di percorsi di route. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) è uno strumento utile per il test delle route Express di base, anche se non supporta la corrispondenza di modelli. -
    +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
    -Le stringhe di query non fanno parte del percorso di route. -
    +{% include admonitions/caution.html content=caution-character %} + +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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 Route Tester](http://forbeslindesay.github.io/express-route-tester/) è uno strumento utile per il test delle route Express di base, anche se non supporta la corrispondenza di modelli. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. -Ecco alcuni esempi di percorsi di route basati su stringhe. +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Ecco alcuni esempi di percorsi di route basati su stringhe. Questo percorso di route corrisponderà a richieste nella route root, `/`. @@ -98,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -Ecco alcuni esempi di percorsi di route basati su modelli di stringa. +### Ecco alcuni esempi di percorsi di route basati su modelli di stringa. + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} Questo percorso di route corrisponderà a `acd` e `abcd`. @@ -132,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
    -I caratteri ?, +, * e () sono sottoinsiemi delle rispettive controparti di espressioni regolari. Trattino (-) e punto (.) vengono interpretati letteralmente da percorsi basati su stringhe. -
    - -Esempi di percorsi di route basati su espressioni regolari: +### Esempi di percorsi di route basati su espressioni regolari: Questo percorso di route corrisponderà a qualsiasi elemento con "a" nel nome route. @@ -154,13 +176,80 @@ app.get(/.*fly$/, (req, res) => { }) ``` +

    +Le stringhe di query non fanno parte del percorso di route. +

    + +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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
    +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} +

    Handler di route

    È possibile fornire molteplici funzioni di callback che si comportino come [middleware](/{{ page.lang }}/guide/using-middleware.html) per gestire una richiesta. La sola eccezione è rappresentata dal fatto che queste callback potrebbero richiamare `next('route')` per ignorare le callback di route restanti. È possibile utilizzare questo meccanismo per imporre pre-condizioni su una route, quindi, passare il controllo a route successive, nel caso non ci siano motivi per proseguire con la route corrente. Gli handler di route possono avere il formato di una funzione, di un array di funzioni o di combinazioni di entrambi, come illustrato nei seguenti esempi. -Una singola funzione di callback può gestire una route. Ad esempio: +Una singola funzione di callback può gestire una route. Ad esempio: ```js app.get('/example/a', (req, res) => { @@ -178,7 +267,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -Un array di funzioni callback possono gestire una route. Ad esempio: + +Un array di funzioni callback possono gestire una route. Ad esempio: ```js const cb0 = function (req, res, next) { @@ -198,7 +288,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -Una combinazione di funzioni indipendenti e array di funzioni può gestire una route. Ad esempio: +Una combinazione di funzioni indipendenti e array di funzioni può gestire una route. Ad esempio: ```js const cb0 = function (req, res, next) { @@ -223,17 +313,17 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => { I metodi sull'oggetto risposta (`res`) nella seguente tabella possono inviare una risposta al client e terminare il ciclo richiesta-risposta. Se nessuno di questi metodi viene richiamato da un handler di route, la richiesta del client verrà lasciata in sospeso. -| Metodo | Descrizione -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Richiedere un file da scaricare. -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Terminare il processo di risposta. -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Inviare una risposta JSON. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Inviare una risposta JSON con supporto JSONP. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Reindirizzare una richiesta. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Eseguire il rendering di un template di vista. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Inviare una risposta di vari tipi. -| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Inviare un file come un flusso di ottetti. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Impostare il codice di stato della risposta e inviare la relativa rappresentazione di stringa come corpo della risposta. +| Metodo | Descrizione | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Richiedere un file da scaricare. | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Terminare il processo di risposta. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Inviare una risposta JSON. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Inviare una risposta JSON con supporto JSONP. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Reindirizzare una richiesta. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Eseguire il rendering di un template di vista. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Inviare una risposta di vari tipi. | +| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Inviare un file come un flusso di ottetti. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Impostare il codice di stato della risposta e inviare la relativa rappresentazione di stringa come corpo della risposta. |

    app.route()

    @@ -268,10 +358,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -284,14 +376,20 @@ router.get('/about', (req, res) => { module.exports = router ``` -Quindi, caricare il modulo router nell'app: +Successivamente, caricare il modulo router nell'applicazione: ```js const birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` L'app ora sarà in grado di gestire richieste a `/birds` e `/birds/about`, oltre a richiamare la funzione middleware `timeLog`, specifica per la 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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/it/guide/using-middleware.md b/it/guide/using-middleware.md old mode 100755 new mode 100644 index e93d5cf0fe..49ca82c95c --- a/it/guide/using-middleware.md +++ b/it/guide/using-middleware.md @@ -1,34 +1,34 @@ --- layout: page title: Utilizzo del middleware Express +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: it -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # Utilizzo del middleware Express è un framework Web di routing e middleware, con funzionalità sua propria minima: un'applicazione Express è essenzialmente a serie di chiamate a funzioni middleware. -Le funzioni *middleware* sono funzioni con accesso all'[oggetto richiesta](/{{ page.lang }}/4x/api.html#req) (`req`), all'[oggetto risposta](/{{ page.lang }}/4x/api.html#res) (`res`) e alla successiva funzione middleware nel ciclo richiesta-risposta dell'applicazione. La successiva funzione middleware viene comunemente denotata da una variabile denominata `next`. +Le funzioni _middleware_ sono funzioni con accesso all'[oggetto richiesta](/{{ page.lang }}/4x/api.html#req) (`req`), all'[oggetto risposta](/{{ page.lang }}/4x/api.html#res) (`res`) e alla successiva funzione middleware nel ciclo richiesta-risposta dell'applicazione. La successiva funzione middleware viene comunemente denotata da una variabile denominata `next`. Le funzioni middleware possono eseguire le attività elencate di seguito: -* Eseguire qualsiasi codice. -* Apportare modifiche agli oggetti richiesta e risposta. -* Terminare il ciclo richiesta-risposta. -* Chiamare la successiva funzione middleware nello stack. +- Eseguire qualsiasi codice. +- Apportare modifiche agli oggetti richiesta e risposta. +- Terminare il ciclo richiesta-risposta. +- Chiamare la successiva funzione middleware nello stack. Se la funzione middleware corrente non termina il ciclo richiesta-risposta, deve richiamare `next()` per passare il controllo alla successiva funzione middleware. Altrimenti, la richiesta verrà lasciata in sospeso. Un'applicazione Express può utilizzare i seguenti tipi di middleware: - - [Middleware a livello dell'applicazione](#middleware.application) - - [Middleware a livello del router](#middleware.router) - - [Middleware di gestione degli errori](#middleware.error-handling) - - [Middleware integrato](#middleware.built-in) - - [Middleware di terzi](#middleware.third-party) +- [Middleware a livello dell'applicazione](#middleware.application) +- [Middleware a livello del router](#middleware.router) +- [Middleware di gestione degli errori](#middleware.error-handling) +- [Middleware integrato](#middleware.built-in) +- [Middleware di terzi](#middleware.third-party) È possibile caricare il middleware a livello dell'applicazione e del router con un percorso di montaggio facoltativo. È possibile inoltre caricare una serie di funzioni middleware contemporaneamente e, in questo modo, si crea un sotto-stack del sistema middleware in un punto di montaggio. @@ -40,6 +40,7 @@ Associare il middleware al livello dell'applicazione ad un'istanza dell'[oggetto Questo esempio presenta una funzione middleware senza percorso di montaggio. La funzione viene eseguita ogni volta che l'app riceve una richiesta. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -93,12 +94,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` -Per ignorare le restanti funzioni middleware da uno stack di middleware del router, richiamare `next('route')` per passare il controllo alla route successiva. -**NOTA**: `next('route')` funzionerà solo in funzioni middleware che sono state caricate utilizzando le funzioni `app.METHOD()` o `router.METHOD()`. +`redirect` + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} Questo esempio presenta un sotto-stack middleware che gestisce richieste GET nel percorso `/user/:id`. @@ -107,15 +115,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +Ecco un esempio di utilizzo della funzione middleware `express.static` con un oggetto opzioni elaborato: + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -126,11 +155,13 @@ Il middleware a livello del router funziona nello stesso modo di quello a livell ```js const router = express.Router() ``` + Caricare il middleware a livello del router utilizzando le funzioni `router.use()` e `router.METHOD()`. Il seguente codice di esempio replica il sistema middleware mostrato sopra per il middleware a livello dell'applicazione, utilizzando il middleware a livello del router: ```js +const express = require('express') const app = express() const router = express.Router() @@ -154,7 +185,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -169,10 +200,36 @@ router.get('/user/:id', (req, res, next) => { // mount the router on the app app.use('/', router) ``` + +Per ulteriori dettagli sulla funzione `serve-static` e sulle relative opzioni, consultare: documentazione [serve-static](https://github.com/expressjs/serve-static). + +Questo esempio presenta un sotto-stack middleware che gestisce richieste GET nel percorso `/user/:id`. + +```js +const express = require('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) +}) +``` +

    Middleware di gestione degli errori

    -Il middleware di gestione degli errori impiega sempre *quattro* argomenti. È necessario fornire quattro argomenti per identificarlo come funzione middleware di gestione degli errori. Anche se non è necessario utilizzare l'oggetto `next`, lo si deve specificare per mantenere la firma. Altrimenti, l'oggetto `next` verrà interpretato come middleware regolare e non sarà in grado di gestire gli errori. +Il middleware di gestione degli errori impiega sempre *quattro* argomenti. È necessario fornire quattro argomenti per identificarlo come funzione middleware di gestione degli errori. Anche se non è necessario utilizzare l'oggetto `next`, lo si deve specificare per mantenere la firma. Altrimenti, l'oggetto `next` verrà interpretato come middleware regolare e non sarà in grado di gestire gli errori.
    Definire le funzioni middleware di gestione degli errori nello stesso modo delle altre funzioni middleware, ma con quattro argomenti invece di tre, nello specifico con la firma `(err, req, res, next)`): @@ -191,52 +248,11 @@ Per dettagli sul middleware di gestione degli errori, consultare la sezione: [Ge Dalla versione 4.x, Express non dipende più da [Connect](https://github.com/senchalabs/connect). Fatta eccezione per `express.static`, tutte le funzioni middleware che prima erano state incluse in Express, ora sono in moduli separati. Vedere [l'elenco delle funzioni middleware](https://github.com/senchalabs/connect#middleware). -

    express.static(root, [options])

    - -L'unica funzione middleware integrata in Express è `express.static`. Questa funzione è basata su [serve-static](https://github.com/expressjs/serve-static) ed è responsabile della fornitura degli asset statici di un'applicazione Express. +L'unica funzione middleware integrata in Express è `express.static`. -L'argomento `root` specifica la directory root da cui fornire gli asset statici. - -L'oggetto facoltativo `options` può avere le seguenti proprietà: - -| Proprietà | Descrizione | Tipo | Valore predefinito | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Opzione per la fornitura di dotfiles. Valori possibili sono "allow", "deny" e "ignore" | Stringa | "ignore" | -| `etag` | Abilitare o disabilitare la generazione di etag | Booleano | `true` | -| `extensions` | Imposta i fallback dell'estensione file. | Array | `[]` | -| `index` | Invia un file di indice di directory. Impostare su `false` per disabilitare l'indicizzazione della directory. | Misto | "index.html" | - `lastModified` | Impostare l'intestazione `Last-Modified`sulla data dell'ultima modifica del file nel sistema operativo. I valori possibili sono `true` o `false`. | Booleano | `true` | -| `maxAge` | Impostare la proprietà dell'intestazione Cache-Control, in millisecondi o una stringa in [formato ms](https://www.npmjs.org/package/ms) | Numero | 0 | -| `redirect` | Reindirizzare al carattere "/" finale, quando il nome percorso è una directory. | Booleano | `true` | -| `setHeaders` | Funzione per l'impostazione delle intestazioni HTTP perché siano adatte al file. | Funzione | | - -Ecco un esempio di utilizzo della funzione middleware `express.static` con un oggetto opzioni elaborato: - -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -È possibile avere più di una directory statica per app: - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` - -Per ulteriori dettagli sulla funzione `serve-static` e sulle relative opzioni, consultare: documentazione [serve-static](https://github.com/expressjs/serve-static). +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**

    Middleware di terzi

    diff --git a/it/guide/using-template-engines.md b/it/guide/using-template-engines.md old mode 100755 new mode 100644 index 759fad7972..c43bef0919 --- a/it/guide/using-template-engines.md +++ b/it/guide/using-template-engines.md @@ -1,18 +1,25 @@ --- layout: page title: Utilizzo di motori di template con Express +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: it -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- # Utilizzo di motori di template con Express -Prima che Express possa eseguire il rendering di file template, è necessario specificare le seguenti impostazioni dell'applicazione: +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. -* `views`, la directory dove sono ubicati i file di template. Ad esempio: `app.set('views', './views')` -* `view engine`, il motore di template da utilizzare. Ad esempio: `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, la directory dove sono ubicati i file di template. Ad esempio: `app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, il motore di template da utilizzare. Ad esempio: `app.set('view engine', 'pug')` Quindi, installare il pacchetto npm del motore di template corrispondente: @@ -24,6 +31,7 @@ $ npm install pug --save I motori di template compatibili con Express, ad esempio Pug esportano una funzione denominata `__express(filePath, options, callback)`, che viene richiamata dalla funzione `res.render()`, per il rendering del codice di template. Alcuni motori di template non seguono questa convenzione. La libreria [Consolidate.js](https://www.npmjs.org/package/consolidate) segue questa convenzione, associando tutti i motori di template Node.js popolari e, perciò, funziona ininterrottamente in Express. +
    Una volta specificata l'impostazione view engine, non è necessario specificare il motore o caricare il modulo del motore di template nella propria app; Express carica il modulo internamente, come mostrato di seguito (per l'esempio precedente). @@ -52,4 +60,4 @@ app.get('/', (req, res) => { Quando si fa una richiesta alla home page, verrà eseguito il rendering del file `index.pug` come HTML. -Per ulteriori informazioni su come funzionano i motori di template in Express, consultare la sezione: ["Sviluppo dei motori di template per Express"](/{{ page.lang }}/advanced/developing-template-engines.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/it/guide/writing-middleware.md b/it/guide/writing-middleware.md old mode 100755 new mode 100644 index 30071c6db4..d464bb1e1d --- a/it/guide/writing-middleware.md +++ b/it/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: Compilazione del middleware per l'utilizzo nelle applicazioni Express +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: it -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- # Compilazione del middleware per l'utilizzo nelle applicazioni Express

    Panoramica

    -Le funzioni *middleware* sono funzioni con accesso all'[oggetto richiesta](/{{ page.lang }}/4x/api.html#req) (`req`), all'[oggetto risposta](/{{ page.lang }}/4x/api.html#res) (`res`) e alla successiva funzione middleware nel ciclo richiesta-risposta dell'applicazione. La successiva funzione middleware viene comunemente denotata da una variabile denominata `next`. +Le funzioni _middleware_ sono funzioni con accesso all'[oggetto richiesta](/{{ page.lang }}/4x/api.html#req) (`req`), all'[oggetto risposta](/{{ page.lang }}/4x/api.html#res) (`res`) e alla successiva funzione middleware nel ciclo richiesta-risposta dell'applicazione. La successiva funzione middleware viene comunemente denotata da una variabile denominata `next`. Le funzioni middleware possono eseguire le attività elencate di seguito: -* Eseguire qualsiasi codice. -* Apportare modifiche agli oggetti richiesta e risposta. -* Terminare il ciclo richiesta-risposta. -* Chiamare il successivo middleware nello stack. +- Eseguire qualsiasi codice. +- Apportare modifiche agli oggetti richiesta e risposta. +- Terminare il ciclo richiesta-risposta. +- Chiamare il successivo middleware nello stack. Se la funzione middleware corrente non termina il ciclo richiesta-risposta, deve richiamare `next()` per passare il controllo alla successiva funzione middleware. Altrimenti, la richiesta verrà lasciata in sospeso. I seguenti esempi mostrano gli elementi di una chiamata alla funzione middleware: - -
    -Elements of a middleware function call + + -
    Percorso (route) per cui si applica la funzione middleware.
    @@ -43,31 +43,14 @@ I seguenti esempi mostrano gli elementi di una chiamata alla funzione middleware
    +Elements of a middleware function call -
    Metodo HTTP per cui si applica la funzione middleware.
    +
    +
    Metodo HTTP per cui si applica la funzione middleware.
    - +

    Esempio

    Ecco un esempio di una semplice applicazione Express "Hello World", per cui si definiranno due funzioni middleware: +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 const express = require('express') @@ -80,8 +63,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    Sviluppo

    - +

    Middleware function myLogger

    Ecco un semplice esempio di una funzione middleware, denominata "myLogger". Questa funzione stampa semplicemente la dicitura "LOGGED" quando una richiesta all'applicazione la attraversa. La funzione middleware è assegnata ad una variabile denominata `myLogger`. ```js @@ -92,8 +74,9 @@ const myLogger = function (req, res, next) { ```
    -Si noti la chiamata precedente a `next()`. Richiamando questa funzione si richiama la successiva funzione middleware nell'applicazione. -La funzione `next()` non fa parte dell'API Express o Node.js, ma è il terzo argomento trasmesso alla funzione middleware. La funzione `next()` potrebbe essere denominata in qualsiasi modo, ma per convenzione viene sempre denominata "next". Per evitare confusione, utilizzare sempre questa convenzione. +Si noti la chiamata precedente a `next()`. Richiamando questa funzione si richiama la successiva funzione middleware nell'applicazione. +La funzione `next()` non fa parte dell'API Express o Node.js, ma è il terzo argomento trasmesso alla funzione middleware. La funzione `next()` potrebbe essere denominata in qualsiasi modo, ma per convenzione viene sempre denominata "next". +Per evitare confusione, utilizzare sempre questa convenzione.
    Per caricare la funzione middleware, richiamare `app.use()`, specificando la funzione middleware. @@ -125,6 +108,8 @@ Se `myLogger` viene caricato dopo la route sul percorso root, la richiesta non l La funzione middleware `myLogger` stampa semplicemente un messaggio, successivamente passa la richiesta alla successiva funzione middleware nello stack chiamando la funzione `next()`. +

    Middleware function requestTime

    + Nel successivo esempio viene aggiunta una proprietà denominata `requestTime` all'oggetto richiesta. Questa funzione middleware verrà denominata "requestTime". ```js @@ -155,8 +140,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + Quando si effettua una richiesta al root dell'applicazione, l'applicazione mostra la cronologia data e ora della richiesta nel browser. +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + Poiché si dispone dell'accesso all'oggetto richiesta, l'oggetto risposta, la successiva funzione middleware nello stack e l'API Node.js completo, le possibilità con le funzioni middleware sono infinite. Per ulteriori informazioni sul middleware Express, consultare: [Utilizzo del middleware Express](/{{ page.lang }}/guide/using-middleware.html). + +

    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 +module.exports = 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') + +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. diff --git a/it/resources/community.md b/it/resources/community.md old mode 100755 new mode 100644 index 1df147e966..56c5c312be --- a/it/resources/community.md +++ b/it/resources/community.md @@ -1,28 +1,93 @@ --- layout: page title: Community di Express +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: it -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # Community +## 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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +La nostra community molto attiva ha creato una vasta varietà di estensioni, +[moduli middleware](/{{ page.lang }}/resources/middleware.html) e framework di livello più elevato. + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). + +## Problematiche + +Se si riscontra un bug o un problema oppure se si desidera semplicemente sottoporre una richiesta, +aprire un ticket in [coda problemi](https://github.com/expressjs/express/issues). + ## Esempi Visualizzare dozzine di [esempi](https://github.com/expressjs/express/tree/master/examples) di applicazioni Express nel repository che copre tutto dall'autenticazione e progettazione API all'integrazione del motore di template. -## Problematiche +## Github Discussions -Se si riscontra un bug o un problema oppure se si desidera semplicemente sottoporre una richiesta, -aprire un ticket in [coda problemi](https://github.com/expressjs/express/issues). +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. -## Terze parti +# Branding of Express.js -La nostra community molto attiva ha creato una vasta varietà di estensioni, -[moduli middleware](/{{ page.lang }}/resources/middleware.html) e framework di livello più elevato. È possibile verificarli in -[wiki](https://github.com/expressjs/express/wiki). +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/it/resources/contributing.md b/it/resources/contributing.md new file mode 100644 index 0000000000..ef35e0bb17 --- /dev/null +++ b/it/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: it +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/it/resources/glossary.md b/it/resources/glossary.md old mode 100755 new mode 100644 index 6eafedbfc6..43758cc020 --- a/it/resources/glossary.md +++ b/it/resources/glossary.md @@ -1,10 +1,10 @@ --- layout: page title: Glossario di Express +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. menu: resources lang: it -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. +redirect_from: " " --- # Glossario @@ -15,11 +15,11 @@ Solitamente, uno o più programmi progettati per gestire operazioni per uno scop ### API -Interfaccia di programmazione dell'applicazione. Si consiglia di scrivere per intero l'acronimo quando lo si usa per la prima volta. +Interfaccia di programmazione dell'applicazione. Si consiglia di scrivere per intero l'acronimo quando lo si usa per la prima volta. ### Express -Un framework web veloce, non categorico e minimalista per le applicazioni Node.js. Solitamente, si preferisce utilizzare "Express" piuttosto che "Express.js," anche se il secondo è accettabile. +Un framework web veloce, non categorico e minimalista per le applicazioni Node.js. Solitamente, si preferisce utilizzare "Express" piuttosto che "Express.js," anche se il secondo è accettabile. ### libuv @@ -27,23 +27,31 @@ Una libreria di supporto multi-piattaforma che si focalizza su I/O asincrono, in ### middleware -Una funzione che viene richiamata dal livello di routing Express prima dell'handler di richiesta finale, pertanto si trova al centro tra una richiesta base e la route prevista. Segue un elenco che indica alcune terminologie utilizzate per middleware: +Una funzione che viene richiamata dal livello di routing Express prima dell'handler di richiesta finale, pertanto si trova al centro tra una richiesta base e la route prevista. Segue un elenco che indica alcune terminologie utilizzate per middleware: - * `var foo = require('middleware')` significa *richiesta* o *utilizzo* di un modulo Node.js. E l'istruzione `var mw = foo()` solitamente restituisce il middleware. - * `app.use(mw)` significa *aggiunta del middleware allo stack di elaborazione globale*. - * `app.get('/foo', mw, function (req, res) { ... })` significa *aggiunta del middleware allo stack di elaborazione "GET /foo"*. +- `var foo = require('middleware')` significa _richiesta_ o _utilizzo_ di un modulo Node.js. E l'istruzione `var mw = foo()` solitamente restituisce il middleware. +- `app.use(mw)` significa _aggiunta del middleware allo stack di elaborazione globale_. +- `app.get('/foo', mw, function (req, res) { ... })` significa _aggiunta del middleware allo stack di elaborazione "GET /foo"_. ### Node.js -Una piattaforma software utilizzata per creare applicazioni di rete scalabili. Node.js utilizza JavaScript e il relativo linguaggio di scripting e raggiunge una trasmissione di dati elevata tramite un I/O non a blocchi e un loop di evento a thread singolo. Consultare [nodejs.org](http://nodejs.org/). **Nota di utilizzo**: Inizialmente, "Node.js," successivamente "Node". +Una piattaforma software utilizzata per creare applicazioni di rete scalabili. Node.js utilizza JavaScript e il relativo linguaggio di scripting e raggiunge una trasmissione di dati elevata tramite un I/O non a blocchi e un loop di evento a thread singolo. Consultare [nodejs.org](http://nodejs.org/). **Nota di utilizzo**: Inizialmente, "Node.js," successivamente "Node". ### open-source, open source -Quando utilizzato come aggettivo, viene aggiunto un trattino; ad esempio: "Questo è un software open-source." Consultare [Software open-source su Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Nota: anche se è molto comune scriverlo senza trattino, stiamo utilizzando le regole dell'inglese standard che richiedono di inserire un trattino in un aggettivo composto. +Quando utilizzato come aggettivo, viene aggiunto un trattino; ad esempio: "Questo è un software open-source." Consultare [Software open-source su Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). + +{% capture english-rules %} + +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. + +{% endcapture %} + +{% include admonitions/note.html content=english-rules %} ### richiesta -Una richiesta HTTP. Un client un messaggio di richiesta HTTP a un server, il quale restituisce una risposta. La richiesta deve utilizzare uno dei diversi [metodi di richiesta](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) ad esempio GET, POST e così via. +Una richiesta HTTP. Un client un messaggio di richiesta HTTP a un server, il quale restituisce una risposta. La richiesta deve utilizzare uno dei diversi [metodi di richiesta](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) ad esempio GET, POST e così via. ### risposta @@ -51,7 +59,7 @@ Una risposta HTTP. Un server restituisce un messaggio di risposta HTTP al client ### route -Parte di un URL che identifica una risorsa. Ad esempio, in `http://foo.com/products/id`, "/products/id" è la route. +Parte di un URL che identifica una risorsa. Ad esempio, in `http://foo.com/products/id`, "/products/id" è la route. ### router diff --git a/it/resources/middleware.md b/it/resources/middleware.md old mode 100755 new mode 100644 index f829c915b2..c15b0ec53c --- a/it/resources/middleware.md +++ b/it/resources/middleware.md @@ -1,65 +1,44 @@ --- -layout: page +layout: middleware title: Middleware Express +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. menu: resources lang: it -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. +redirect_from: " " +module: mw-home --- -# Middleware di terzi +## Middleware Express Di seguito vengono riportati alcuni moduli middleware Express: - - [body-parser](https://github.com/expressjs/body-parser): in precedenza `express.bodyParser`, `json` e `urlencoded`. - Consultare inoltre: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression): in precedenza `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): moduli middleware Connect/Express per una gestione dell'immagine ottimale. Se possibile, cambia le estensioni delle immagini a `.webp` o `.jxr`. - - [connect-timeout](https://github.com/expressjs/timeout): in precedenza `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser): in precedenza `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session): in precedenza `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler): in precedenza `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug): uno strumento di sviluppo riservato che aggiunge una scheda contenente informazioni sulle variabili di template (locali), sessione corrente, dati della richiesta utili e altro ancora all'applicazione. - - [express-partial-response](https://github.com/nemtsov/express-partial-response): modulo middleware Express per filtrare le parti delle risposte JSON in base alla stringa query `fields`; utilizzando una risposta parziale API Google. - - [express-session](https://github.com/expressjs/session): in precedenza `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): modulo middleware Express per l'utilizzo di un CDN per asset statici, con supporto host multiplo (Ad esempio: cdn1.host.com, cdn2.host.com). - - [express-slash](https://github.com/ericf/express-slash): modulo middleware Express per persone che sono rigide sull'utilizzo di barre. - - [express-stormpath](https://github.com/stormpath/stormpath-express): modulo middleware Express per lo storage utente, autenticazione, autorizzazione, SSO e sicurezza dati. - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): modulo middleware per il reindirizzamento delle richieste HTTP contenenti caratteri maiuscoli per una forma con caratteri minuscoli canonica. - - [helmet](https://github.com/helmetjs/helmet): modulo che aiuta a proteggere le applicazioni impostando varie intestazioni HTTP. - - [join-io](https://github.com/coderaiser/join-io "join-io"): modulo per unire i file in entrata per ridurre il conteggio delle richieste. - - [method-override](https://github.com/expressjs/method-override): in precedenza `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan): in precedenza `logger` - - [passport](https://github.com/jaredhanson/passport): modulo middleware Express per l'autenticazione. - - [response-time](https://github.com/expressjs/response-time): in precedenza `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon): in precedenza `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index): in precedenza `express.directory` - - [serve-static](https://github.com/expressjs/serve-static): modulo per gestire i contenuti statici. - - [static-expiry](https://github.com/paulwalker/connect-static-expiry): URL riconosciute o Caching Header per asset statici incluso il supporto per uno o più domini esterni. - - [vhost](https://github.com/expressjs/vhost): in precedenza `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers): modulo middleware Express che fornisce metodi di aiuto comuni per le viste. - - [sriracha-admin](https://github.com/hdngr/siracha): modulo middleware Express che crea in modo dinamico un sito admin per Mongoose. +| Middleware module | Descrizione | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Alcuni moduli middleware precedentemente inclusi in Connect non sono più supportati dal team di Connect/Express. Questi moduli sono stati sostituiti da un modulo alternativo o dovrebbero essere sostituiti a un modulo migliore. Utilizzare una delle seguenti alternative: +## Per ulteriori moduli middleware, consultare: - - express.cookieParser - - [cookie](https://github.com/jed/cookies) e [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -Per ulteriori moduli middleware, consultare: +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| Middleware module | Descrizione | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet): modulo che aiuta a proteggere le applicazioni impostando varie intestazioni HTTP. | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport): modulo middleware Express per l'autenticazione. | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/it/resources/middleware/body-parser.md b/it/resources/middleware/body-parser.md new file mode 100644 index 0000000000..9999829c13 --- /dev/null +++ b/it/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: it +redirect_from: " " +module: body-parser +--- diff --git a/it/resources/middleware/compression.md b/it/resources/middleware/compression.md new file mode 100644 index 0000000000..4edc2cef9b --- /dev/null +++ b/it/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: it +redirect_from: " " +module: compression +--- diff --git a/it/resources/middleware/connect-rid.md b/it/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..db14f9ad61 --- /dev/null +++ b/it/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: it +redirect_from: " " +module: connect-rid +--- diff --git a/it/resources/middleware/cookie-parser.md b/it/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..dd0d9cf273 --- /dev/null +++ b/it/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: it +redirect_from: " " +module: cookie-parser +--- diff --git a/it/resources/middleware/cookie-session.md b/it/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..f8d9887f15 --- /dev/null +++ b/it/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: it +redirect_from: " " +module: cookie-session +--- diff --git a/it/resources/middleware/cors.md b/it/resources/middleware/cors.md new file mode 100644 index 0000000000..d3b2370819 --- /dev/null +++ b/it/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: it +redirect_from: " " +module: cors +--- diff --git a/it/resources/middleware/errorhandler.md b/it/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..ece2f5d474 --- /dev/null +++ b/it/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: it +redirect_from: " " +module: errorhandler +--- diff --git a/it/resources/middleware/method-override.md b/it/resources/middleware/method-override.md new file mode 100644 index 0000000000..5fb17e57c6 --- /dev/null +++ b/it/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: it +redirect_from: " " +module: method-override +--- diff --git a/it/resources/middleware/morgan.md b/it/resources/middleware/morgan.md new file mode 100644 index 0000000000..edddd98ad1 --- /dev/null +++ b/it/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: it +redirect_from: " " +module: morgan +--- diff --git a/it/resources/middleware/multer.md b/it/resources/middleware/multer.md new file mode 100644 index 0000000000..460f04b22e --- /dev/null +++ b/it/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: it +redirect_from: " " +module: multer +--- diff --git a/it/resources/middleware/response-time.md b/it/resources/middleware/response-time.md new file mode 100644 index 0000000000..1161dcae2a --- /dev/null +++ b/it/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: it +redirect_from: " " +module: response-time +--- diff --git a/it/resources/middleware/serve-favicon.md b/it/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..044c23c51d --- /dev/null +++ b/it/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: it +redirect_from: " " +module: serve-favicon +--- diff --git a/it/resources/middleware/serve-index.md b/it/resources/middleware/serve-index.md new file mode 100644 index 0000000000..c73a6cef84 --- /dev/null +++ b/it/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: it +redirect_from: " " +module: serve-index +--- diff --git a/it/resources/middleware/serve-static.md b/it/resources/middleware/serve-static.md new file mode 100644 index 0000000000..9114f4a6f7 --- /dev/null +++ b/it/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: it +redirect_from: " " +module: serve-static +--- diff --git a/it/resources/middleware/session.md b/it/resources/middleware/session.md new file mode 100644 index 0000000000..f1d8711710 --- /dev/null +++ b/it/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: it +redirect_from: " " +module: session +--- diff --git a/it/resources/middleware/timeout.md b/it/resources/middleware/timeout.md new file mode 100644 index 0000000000..1706114700 --- /dev/null +++ b/it/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: it +redirect_from: " " +module: timeout +--- diff --git a/it/resources/middleware/vhost.md b/it/resources/middleware/vhost.md new file mode 100644 index 0000000000..8bd7806da0 --- /dev/null +++ b/it/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: it +redirect_from: " " +module: vhost +--- diff --git a/it/resources/utils.md b/it/resources/utils.md new file mode 100644 index 0000000000..203b7bf563 --- /dev/null +++ b/it/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: it +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | Descrizione | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/it/starter/basic-routing.md b/it/starter/basic-routing.md old mode 100755 new mode 100644 index d420582a3f..825b79ced4 --- a/it/starter/basic-routing.md +++ b/it/starter/basic-routing.md @@ -1,20 +1,20 @@ --- layout: page title: Routing di base Express +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. menu: starter lang: it -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. +redirect_from: " " --- # Routing di base -Per *Routing* si intende determinare come un'applicazione risponde a una richiesta client a un endpoint particolare, il quale è un URI (o percorso) e un metodo di richiesta HTTP specifico (GET, POST e così via). +Per _Routing_ si intende determinare come un'applicazione risponde a una richiesta client a un endpoint particolare, il quale è un URI (o percorso) e un metodo di richiesta HTTP specifico (GET, POST e così via). Ciascuna route può disporre di una o più funzioni dell'handler, le quali vengono eseguite quando si trova una corrispondenza per la route. La definizione della route ha la seguente struttura: + ```js app.METHOD(PATH, HANDLER) ``` @@ -65,3 +65,5 @@ app.delete('/user', (req, res) => { ``` Per ulteriori dettagli sul routing, consultare il [Manuale routing](/{{ page.lang }}/guide/routing.html). + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/it/starter/examples.md b/it/starter/examples.md new file mode 100644 index 0000000000..12218b9e97 --- /dev/null +++ b/it/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: it +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/it/starter/faq.md b/it/starter/faq.md old mode 100755 new mode 100644 index 242ed721d7..f3d6426e6f --- a/it/starter/faq.md +++ b/it/starter/faq.md @@ -1,11 +1,10 @@ --- layout: page title: FAQ di Express +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: it -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # FAQ @@ -20,13 +19,13 @@ Le route e altre logiche specifiche dell'applicazione possono essere presenti in in qualsiasi struttura di directory desiderata. Visualizzare i seguenti esempi: -* [Elenchi route](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [Definizione route](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [Controllori stile MVC](https://github.com/expressjs/express/tree/master/examples/mvc) +- [Elenchi route](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [Definizione route](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [Controllori stile MVC](https://github.com/expressjs/express/tree/master/examples/mvc) Inoltre, ci sono delle estensioni di terze parti per Express, le quali semplificano alcuni di questi modelli: -* [Routing pieno di risorse](https://github.com/expressjs/express-resource) +- [Routing pieno di risorse](https://github.com/expressjs/express-resource) ## In che modo è possibile definire i modelli? @@ -39,10 +38,9 @@ Consultare [LoopBack](http://loopback.io) per un framework basato su Express inc ## In che modo è possibile autenticare gli utenti? L'autenticazione è un'altra area categorica in cui non si -avventura Express. È possibile utilizzare qualsiasi schema di autenticazione desiderato. +avventura Express. È possibile utilizzare qualsiasi schema di autenticazione desiderato. Per uno schema nome utente / password semplice, consultare [questo esempio](https://github.com/expressjs/express/tree/master/examples/auth). - ## Quale motore di template supporta Express? Express supporta qualsiasi motore di template conforme alla sigla `(path, locals, callback)`. @@ -50,6 +48,8 @@ Per normalizzare le interfacce del motore di template e la memorizzazione in cac [consolidate.js](https://github.com/visionmedia/consolidate.js) per il supporto. I motori di template potrebbero ancora non supportare Express. +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). + ## In che modo è possibile gestire le risposte 404? In Express, le risposte 404 non sono il risultato di un errore, pertanto @@ -62,10 +62,13 @@ per gestire una risposta 404: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## In che modo è possibile impostare un gestore degli errori? È possibile definire il middleware di gestione degli errori nello stesso modo in cui si definisce qualsiasi altro middleware, @@ -86,3 +89,10 @@ Non è necessario farlo! Non è necessario "eseguire il rendering" dell'HTML con Se si dispone di un file specifico, utilizzare la funzione `res.sendFile()`. Se si stanno gestendo molti asset da una directory, utilizzare la funzione middleware `express.static()`. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/it/starter/generator.md b/it/starter/generator.md old mode 100755 new mode 100644 index 34b01f055e..515bbaf68e --- a/it/starter/generator.md +++ b/it/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Programma di creazione applicazione Express +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: it -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Programma di creazione applicazione Express Utilizzare lo strumento di creazione dell'applicazione, `express`, per creare velocemente una struttura dell'applicazione. -Installare `express` con il seguente comando: +You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash -$ npm install express-generator -g +$ npx express-generator +``` + +For earlier Node versions, install the application generator as a global npm package and then launch it: + +```bash +$ npm install -g express-generator +$ express ``` Visualizzare le opzioni del comando con l'opzione `-h`: @@ -22,7 +29,7 @@ Visualizzare le opzioni del comando con l'opzione `-h`: ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -Ad esempio, quanto segue crea un'applicazione Express denominata _myapp_ nella directory di lavoro corrente: +Ad esempio, quanto segue crea un'applicazione Express denominata _myapp_ nella directory di lavoro corrente: The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -70,18 +77,24 @@ $ cd myapp $ npm install ``` -Su MacOS o Linux, eseguire l'applicazione con il seguente comando: +Su Windows, utilizzare questo comando: ```bash $ DEBUG=myapp:* npm start ``` -Su Windows, utilizzare questo comando: +Su MacOS o Linux, eseguire l'applicazione con il seguente comando: ```bash > set DEBUG=myapp:* & npm start ``` +On Windows PowerShell, use this command: + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + Quindi caricare `http://localhost:3000/` sul browser per accedere all'applicazione. L'applicazione creata dispone della seguente struttura per la directory: @@ -111,3 +124,5 @@ L'applicazione creata dispone della seguente struttura per la directory:
    La struttura dell'applicazione creata dal programma di creazione è solo uno dei tanti modi disponibili per creare la struttura delle applicazioni Express. È possibile utilizzare questa struttura o modificarla a seconda delle proprie necessità.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/it/starter/hello-world.md b/it/starter/hello-world.md old mode 100755 new mode 100644 index 5cc747e41b..cadc201ffc --- a/it/starter/hello-world.md +++ b/it/starter/hello-world.md @@ -1,10 +1,10 @@ --- layout: page title: Esempio di "Hello World" di express +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: it -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Esempio di Hello world @@ -13,10 +13,6 @@ description: Get started with Express.js by building a simple 'Hello World' appl In sostanza, questa sarà l'applicazione Express più semplice che è possibile creare. È un'applicazione a singolo file — e *non* quello che si ottiene se si utilizza il [Programma di creazione Express](/{{ page.lang }}/starter/generator.html), il quale crea le fondamenta per un'applicazione completa con molti file JavaScript, template Jade e sotto directory per diversi scopi.
    -Per prima cosa creare una directory denominata `myapp`, passare a quest'ultima ed eseguire `npm init`. Quindi installare `express` come dipendenza, come descritto nella [Guida all'installazione](/{{ page.lang }}/starter/installing.html). - -Nella directory `myapp`, creare un file denominato `app.js` e aggiungere il seguente codice: - ```js const express = require('express') const app = express() @@ -32,7 +28,13 @@ app.listen(port, () => { ``` L'applicazione avvia un server e resta in ascolto sulla porta 3000 per le connessioni. L'applicazione risponde con "Hello World!" per le richieste -all'URL root (`/`) o *route*. Per qualsiasi altro percorso, risponderà con il messaggio **404 Non trovato**. +all'URL root (`/`) o _route_. Per qualsiasi altro percorso, risponderà con il messaggio **404 Non trovato**. + +### Running Locally + +Per prima cosa creare una directory denominata `myapp`, passare a quest'ultima ed eseguire `npm init`. Quindi installare `express` come dipendenza, come descritto nella [Guida all'installazione](/{{ page.lang }}/starter/installing.html). + +Nella directory `myapp`, creare un file denominato `app.js` e aggiungere il seguente codice:
    I valori `req` (richiesta) e `res` (risposta) sono esattamente gli stessi oggetti forniti da Node, quindi è possibile richiamare @@ -47,3 +49,4 @@ $ node app.js Successivamente, caricare [http://localhost:3000/](http://localhost:3000/) su un browser per visualizzare l'output. +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/it/starter/installing.md b/it/starter/installing.md old mode 100755 new mode 100644 index 22e80a7290..c6793ba751 --- a/it/starter/installing.md +++ b/it/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: Installazione di Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: it -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # Installazione Presumendo che sia stato già installato [Node.js](https://nodejs.org/), creare una directory in cui conservare l'applicazione e renderla la directory di lavoro. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -26,7 +29,7 @@ $ npm init Questo comando richiede di specificare alcune informazioni, ad esempio il nome e la versione dell'applicazione. Per il momento, è possibile semplicemente premere il tasto INVIO per accettare i valori di default per molti di esse, ad eccezione di quanto segue: -```bash +``` entry point: (index.js) ``` @@ -35,16 +38,17 @@ Immettere `app.js` o qualsiasi altra cosa come nome del file principale. Se si d Quindi installare Express nella directory `myapp` e salvarlo nell'elenco delle dipendenze. Ad esempio: ```bash -$ npm install express --save +$ npm install express ``` Per installare momentaneamente Express e non aggiungerlo all'elenco di dipendenze, omettere l'opzione `--save`: ```bash -$ npm install express +$ npm install express --no-save ```
    -I moduli Node installati con l'opzione `--save` vengono aggiunti all'elenco `dependencies` nel file `package.json`. -Successivamente, l'esecuzione di `npm install` nella directory `app` installerà automaticamente i moduli nell'elenco di dipendenze. +I moduli Node installati con l'opzione `--save` vengono aggiunti all'elenco `dependencies` nel file `package.json`. Successivamente, l'esecuzione di `npm install` nella directory `app` installerà automaticamente i moduli nell'elenco di dipendenze.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/it/starter/static-files.md b/it/starter/static-files.md old mode 100755 new mode 100644 index 429cce3157..639fcc784c --- a/it/starter/static-files.md +++ b/it/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: Gestione dei file statici in Express +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: it -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # Gestione dei file statici in Express Per gestire i file statici, quali immagini, file CSS e file JavaScript, utilizzare la funzione middleware integrata `express.static` in Express. -Fornire il nome della directory che contiene gli asset statici alla funzione middleware `express.static` per iniziare a gestire i file direttamente. Ad esempio, utilizzare il seguente codice per gestire le immagini, i file CSS e i file JavaScript nella directory denominata `public`: +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](/{{page.lang}}/4x/api.html#express.static). + +Ad esempio, utilizzare il seguente codice per gestire le immagini, i file CSS e i file JavaScript nella directory denominata `public`: ```js app.use(express.static('public')) @@ -40,6 +49,11 @@ app.use(express.static('files')) Express ricerca i file nell'ordine in cui sono state impostate le directory statiche con la funzione middleware `express.static`. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + Per creare un prefisso per il percorso virtuale (in cui il percorso non esiste effettivamente nel file system) per i file gestiti dalla funzione `express.static`, [specificare un percorso di caricamento](/{{ page.lang }}/4x/api.html#app.use) per la directory statica, come mostrato di seguito: ```js @@ -62,3 +76,7 @@ Tuttavia, il percorso fornito per la funzione `express.static` è relativo alla const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/it/support/index.md b/it/support/index.md index f7217129ce..fbc7f4e31b 100644 --- a/it/support/index.md +++ b/it/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: it --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/ja/3x/api.md b/ja/3x/api.md old mode 100755 new mode 100644 index f02f7cd3e5..c39c8881db --- a/ja/3x/api.md +++ b/ja/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - API リファレンス +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: ja -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x は保守されなくなりました** - 最終更新日 (2015 年 8 月 1 日) 以降、3.x における既知および不明のセキュリティーとパフォーマンスの問題には対応していません。最新バージョンの Express を使用することを強くお勧めします。 -
    - -

    3.x API

    +3.xの既知および未知のセキュリティ問題は、最終更新(2015年8月1日)以降は対処されていません。3.x系を使用することは安全であると見なされるべきではありません。 It is highly recommended to use the latest version of Express. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
    - - {% include api/en/3x/res.md %} +

    3.x API

    - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
    diff --git a/ja/4x/api.md b/ja/4x/api.md old mode 100755 new mode 100644 index d09295d276..a194b92f44 --- a/ja/4x/api.md +++ b/ja/4x/api.md @@ -1,28 +1,27 @@ --- layout: api -version: 5x +version: 4x title: Express 4.x - API リファレンス +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: ja -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +

    4.x API

    - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
    diff --git a/ja/5x/api.md b/ja/5x/api.md index c0d5e03c8e..e0d2b5e368 100644 --- a/ja/5x/api.md +++ b/ja/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - API リファレンス +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: ja -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/ja/advanced/best-practice-performance.md b/ja/advanced/best-practice-performance.md old mode 100755 new mode 100644 index e49c56af6d..dee2d1c997 --- a/ja/advanced/best-practice-performance.md +++ b/ja/advanced/best-practice-performance.md @@ -1,107 +1,95 @@ --- layout: page title: 実稼働環境における Express の使用におけるパフォーマンスに関するベスト・プラクティス +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: ja -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # 実稼働環境におけるベスト・プラクティス: パフォーマンスと信頼性 -## 概説 - この記事では、実稼働環境にデプロイされた Express アプリケーションのパフォーマンスと信頼性に関するベスト・プラクティスについて説明します。 -このトピックは、従来型の開発と運用の両方にわたる「DevOps」の世界に明確に分類されます。したがって、情報は次の 2 つの部分に分かれています。 - -* コードで実行する処理 (開発部分) - * [gzip 圧縮を使用する](#use-gzip-compression) - * [同期関数を使用しない](#dont-use-synchronous-functions) - * [ロギングを正確に実行する](#do-logging-correctly) - * [例外を適切に処理する](#handle-exceptions-properly) -* 環境/セットアップで実行する処理 (運用部分) - * [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) - * [Cache request results](#cache-request-results) - * [Use a load balancer](#use-a-load-balancer) - * [Use a reverse proxy](#use-a-reverse-proxy) +This topic clearly falls into the "devops" world, spanning both traditional development and operations. Accordingly, the information is divided into two parts: + +- コードで実行する処理 (開発部分) + - [gzip 圧縮を使用する](#use-gzip-compression) + - [同期関数を使用しない](#dont-use-synchronous-functions) + - [ロギングを正確に実行する](#do-logging-correctly) + - [例外を適切に処理する](#handle-exceptions-properly) +- 環境/セットアップで実行する処理 (運用部分) + - [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) + - [Cache request results](#cache-request-results) + - [Use a load balancer](#use-a-load-balancer) + - [Use a reverse proxy](#use-a-reverse-proxy) ## コードで実行する処理 {#in-code} 以下に、アプリケーションのパフォーマンスを向上させるためにコードで実行できる処理をいくつか挙げます。 -* [gzip 圧縮を使用する](#use-gzip-compression) -* [同期関数を使用しない](#dont-use-synchronous-functions) -* [ロギングを正確に実行する](#do-logging-correctly) -* [例外を適切に処理する](#handle-exceptions-properly) +- [gzip 圧縮を使用する](#use-gzip-compression) +- [同期関数を使用しない](#dont-use-synchronous-functions) +- [ロギングを正確に実行する](#do-logging-correctly) +- [例外を適切に処理する](#handle-exceptions-properly) ### gzip 圧縮を使用する -Gzip 圧縮により、応答本体のサイズを大幅に縮小できるため、Web アプリケーションの速度が高くなります。Express アプリケーションで gzip 圧縮として [compression](https://www.npmjs.com/package/compression) ミドルウェアを使用してください。次に例を示します。 +Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Gzip 圧縮により、応答本体のサイズを大幅に縮小できるため、Web アプリケーションの速度が高くなります。Express アプリケーションで gzip 圧縮として [compression](https://www.npmjs.com/package/compression) ミドルウェアを使用してください。次に例を示します。 For example: ```js const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` -トラフィックが多い実稼働環境の Web サイトでは、圧縮を適用する最適な方法は、リバース・プロキシー・レベルで実装することです ([リバース・プロキシーの使用](#proxy)を参照)。その場合は、compression ミドルウェアを使用する必要はありません。Nginx で gzip 圧縮を有効にする方法について詳しくは、Nginx 資料の [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) を参照してください。 +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. トラフィックが多い実稼働環境の Web サイトでは、圧縮を適用する最適な方法は、リバース・プロキシー・レベルで実装することです ([リバース・プロキシーの使用](#proxy)を参照)。その場合は、compression ミドルウェアを使用する必要はありません。Nginx で gzip 圧縮を有効にする方法について詳しくは、Nginx 資料の [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) を参照してください。 ### 同期関数を使用しない -同期の関数とメソッドは、返されるまで実行中のプロセスを結合します。同期関数に対する 1 回の呼び出しは数マイクロ秒から数ミリ秒で返される可能性がありますが、トラフィックが多い Web サイトでは、これらの呼び出しを合計すると、アプリケーションのパフォーマンスが低下します。実稼働環境では、これらを使用しないでください。 +同期の関数とメソッドは、返されるまで実行中のプロセスを結合します。同期関数に対する 1 回の呼び出しは数マイクロ秒から数ミリ秒で返される可能性がありますが、トラフィックが多い Web サイトでは、これらの呼び出しを合計すると、アプリケーションのパフォーマンスが低下します。実稼働環境では、これらを使用しないでください。 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. -ノードおよび多くのモジュールは、同期版と非同期版の関数を提供していますが、実稼働環境では必ず非同期版を使用してください。同期関数を使用しても構わないのは、初期始動時のみです。 +ノードおよび多くのモジュールは、同期版と非同期版の関数を提供していますが、実稼働環境では必ず非同期版を使用してください。同期関数を使用しても構わないのは、初期始動時のみです。 The only time when a synchronous function can be justified is upon initial startup. -Node.js 4.0+ または io.js 2.1.0+ を使用している場合、アプリケーションで同期 API を使用するときに、いつでも `--trace-sync-io` コマンド・ライン・フラグを使用して、警告とスタック・トレースを出力することができます。無論、この機能を実際に実稼働環境で使用することはありませんが、コードを実稼働環境で使用する準備ができていることを確認するために使用できます。詳細については、[io.js 2.1.0 の週次更新](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0)を参照してください。 +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#cli_trace_sync_io) for more information. ### ロギングを正確に実行する -一般に、アプリケーションからのロギングを行う理由には、デバッグと、アプリケーション・アクティビティー (基本的にその他すべて) のロギングの 2 つがあります。`console.log()` または `console.err()` を使用してログ・メッセージを端末に出力するのは、開発環境では一般的な手法です。しかし、宛先が端末またはファイルの場合、[これらの関数は同期的](https://nodejs.org/api/console.html#console_console_1)であるため、出力を別のプログラムにパイプ接続しない限り、実稼働環境には向いていません。 +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.err()` に送信されるデバッグ・メッセージを制御できます。アプリケーションを純粋に非同期的にしておくために、`console.err()` を別のプログラムにパイプ接続することもできます。しかし、実稼働環境ではデバッグを実行することはお勧めしません。 +デバッグの目的でロギングを実行する場合は、`console.log()` を使用するのではなく、[debug](https://www.npmjs.com/package/debug) などの特殊なデバッグ・モジュールを使用します。このモジュールでは、DEBUG 環境変数を使用して、`console.err()` に送信されるデバッグ・メッセージを制御できます。アプリケーションを純粋に非同期的にしておくために、`console.err()` を別のプログラムにパイプ接続することもできます。しかし、実稼働環境ではデバッグを実行することはお勧めしません。 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? #### アプリケーション・アクティビティー -アプリケーション・アクティビティー (例えば、トラフィックまたは API 呼び出しのトラッキング) のロギングを実行する場合は、`console.log()` を使用するのではなく、[Winston](https://www.npmjs.com/package/winston) や [Bunyan](https://www.npmjs.com/package/bunyan) などのロギング・ライブラリーを使用します。これらの 2 つのライブラリーの詳細な比較については、StrongLoop ブログ投稿の [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/) を参照してください。 +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. ### 例外を適切に処理する -Node アプリケーションは、キャッチされていない例外が発生すると、異常終了します。例外を処理せず、適切な処置を取らないと、Express アプリケーションは異常終了してオフラインになります。下記の『[アプリケーションが確実に自動再始動するようにする](#restart)』に記載されているアドバイスに従うと、アプリケーションは異常終了から復旧します。幸い、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. [アプリケーションが確実に自動再始動するようにする](#ensure-your-app-automatically-restarts) 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. 確実にすべての例外を処理するには、以下の技法を使用します。 -* [Try-catch の使用](#try-catch) -* [Promise の使用](#promises) +- [Try-catch の使用](#try-catch) +- [Promise の使用](#promises) -上記のトピックを読む前に、error-first コールバックの使用と、ミドルウェアへのエラーの伝搬という Node/Express エラー処理の基礎を理解しておく必要があります。Node は、非同期関数からエラーを返すために「error-first コールバック」という規則を使用します。この場合、コールバック関数への最初のパラメーターがエラー・オブジェクトで、その後に続くパラメーターに結果データがあります。エラーがないことを示すには、最初のパラメーターとして `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. 上記のトピックを読む前に、error-first コールバックの使用と、ミドルウェアへのエラーの伝搬という Node/Express エラー処理の基礎を理解しておく必要があります。Node は、非同期関数からエラーを返すために「error-first コールバック」という規則を使用します。この場合、コールバック関数への最初のパラメーターがエラー・オブジェクトで、その後に続くパラメーターに結果データがあります。エラーがないことを示すには、最初のパラメーターとして `null` を渡します。コールバック関数は、エラーを有意に処理するには、error-first コールバック規則に対応して従う必要があります。Express におけるベスト・プラクティスは、next() 関数を使用して、ミドルウェア・チェーンを介してエラーを伝搬することです。 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. エラー処理のその他の基礎については、下記を参照してください。 -* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (StrongLoop ブログ) - -#### 実行してはならないこと - -実行しては*ならない* ことの 1 つは、例外がイベント・ループまでたどり着いた場合に生成される `uncaughtException` イベントを listen することです。`uncaughtException` のイベント・リスナーを追加すると、例外が発生したプロセスのデフォルトの動作が変更されます。プロセスは、例外に関係なく実行し続けます。この方法でアプリケーションの異常終了を防止できそうに思えますが、キャッチされていない例外が発生した後にアプリケーションの実行を続けるのは危険な手法であり、お勧めしません。プロセスの状態の信頼性と予測可能性が低くなるためです。 - -さらに、`uncaughtException` の使用は、正式に[粗雑なもの](https://nodejs.org/api/process.html#process_event_uncaughtexception)として認められており、これをコアから削除するための[提案](https://github.com/nodejs/node-v0.x-archive/issues/2582)が出されています。したがって、`uncaughtException` を listen するのは悪い方法です。この理由から複数のプロセスとスーパーバイザーなどの使用をお勧めしています。異常終了と再始動は、場合によってはエラーから復旧するための最も信頼できる方法となります。 - -また、[domain](https://nodejs.org/api/domain.html) の使用もお勧めしません。このモジュールは概して問題を解決しないため、推奨されていません。 +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### Try-catch の使用 -Try-catch は、同期コードで例外をキャッチするために使用できる JavaScript 言語構造体です。Try-catch は、例えば、下記のように JSON 構文解析エラーを処理するために使用します。 - -[JSHint](http://jshint.com/) または [JSLint](http://www.jslint.com/) などのツールを使用して、[未定義変数の参照エラー](http://www.jshint.com/docs/options/#undef)などの暗黙的な例外を検出します。 +Try-catch は、同期コードで例外をキャッチするために使用できる JavaScript 言語構造体です。Try-catch は、例えば、下記のように JSON 構文解析エラーを処理するために使用します。 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) => { @@ -118,156 +106,126 @@ app.get('/search', (req, res) => { }) ``` -ただし、Try-catch は同期コードでのみ機能します。Node プラットフォームは主に (特に実稼働環境で) 非同期的であるため、Try-catch は多くの例外をキャッチしません。 +However, try-catch works only for synchronous code. ただし、Try-catch は同期コードでのみ機能します。Node プラットフォームは主に (特に実稼働環境で) 非同期的であるため、Try-catch は多くの例外をキャッチしません。 #### Promise の使用 -Promise は、`then()` を使用する非同期コード・ブロックのすべての例外 (明示的と暗黙的の両方) を処理します。単に、Promise チェーンの最後に `.catch(next)` を追加してください。次に例を示します。 +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -これで、非同期と同期のエラーがすべてエラー・ミドルウェアに伝搬されます。 - -ただし、注意点が 2 つあります。 - -1. すべての非同期コードが Promise を返す必要があります (エミッターを除く)。特定のライブラリーが Promise を返さない場合は、[Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html) などのヘルパー関数を使用して基本オブジェクトを変換します。 -2. イベント・エミッター (ストリームなど) により、例外がキャッチされないことがあります。そのため、必ずエラー・イベントを適切に処理してください。次に例を示します。 +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -Promise を使用するエラー処理の詳細については、下記を参照してください。 +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. -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +#### 実行してはならないこと -## 環境/セットアップで実行する処理 +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` の使用は、正式に[粗雑なもの](https://nodejs.org/api/process.html#process_event_uncaughtexception)として認められており、これをコアから削除するための[提案](https://github.com/nodejs/node-v0.x-archive/issues/2582)が出されています。したがって、`uncaughtException` を listen するのは悪い方法です。この理由から複数のプロセスとスーパーバイザーなどの使用をお勧めしています。異常終了と再始動は、場合によってはエラーから復旧するための最も信頼できる方法となります。 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. -* [NODE_ENV を「production」に設定する](#set-node_env-to-production) -* [アプリケーションが確実に自動再始動するようにする](#ensure-your-app-automatically-restarts) -* [アプリケーションをクラスターで実行する](#run-your-app-in-a-cluster) -* [要求の結果をキャッシュに入れる](#cache-request-results) -* [ロード・バランサーを使用する](#use-a-load-balancer) -* [リバース・プロキシーを使用する](#use-a-reverse-proxy) +また、[domain](https://nodejs.org/api/domain.html) の使用もお勧めしません。このモジュールは概して問題を解決しないため、推奨されていません。 It generally doesn't solve the problem and is a deprecated module. -### NODE_ENV を「production」に設定する +## Things to do in your environment / setup -NODE_ENV 環境変数は、アプリケーションが実行される環境 (通常は開発または実稼働) を指定します。パフォーマンスを向上させるために実行できる最も単純な処理の 1 つは、NODE_ENV を「production」に設定することです。 +{#in-environment} -NODE_ENV を「production」に設定すると、Express は次のようになります。 +以下に、アプリケーションのパフォーマンスを向上させるためにシステム環境で実行できる処理をいくつか挙げます。 -* ビュー・テンプレートをキャッシュに入れる。 -* CSS 拡張から生成された CSS ファイルをキャッシュに入れる。 -* 詳細度の低いエラー・メッセージを生成する。 +- [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) +- [Cache request results](#cache-request-results) +- [Use a load balancer](#use-a-load-balancer) +- [Use a reverse proxy](#use-a-reverse-proxy) -[テスト](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/)により、こうすると、アプリケーション・パフォーマンスが 3 倍も高くなることが示されています。 +### NODE_ENV を「production」に設定する -環境固有のコードを作成する必要がある場合は、`process.env.NODE_ENV` を使用して NODE_ENV の値を確認できます。どの環境変数の値を確認する場合でもパフォーマンスに悪影響が及ぶため、慎重に行ってください。 +NODE_ENV 環境変数は、アプリケーションが実行される環境 (通常は開発または実稼働) を指定します。パフォーマンスを向上させるために実行できる最も単純な処理の 1 つは、NODE_ENV を「production」に設定することです。 One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. -開発環境では、通常、対話式シェルで環境変数を設定します。例えば、`export` または `.bash_profile` ファイルを使用します。しかし、一般的には実動サーバーではそうしません。代わりに、OS の init システム (systemd または Upstart) を使用します。次のセクションでは、init システムの一般的な使用法について詳しく説明しています。ここで重点的に説明したのは、NODE_ENV の設定がパフォーマンスにとって極めて重要であるため (かつ簡単に実行できるため) です。 +NODE_ENV を「production」に設定すると、Express は次のようになります。 -Upstart では、ジョブ・ファイルで `env` キーワードを使用します。次に例を示します。 +- ビュー・テンプレートをキャッシュに入れる。 +- CSS 拡張から生成された CSS ファイルをキャッシュに入れる。 +- 詳細度の低いエラー・メッセージを生成する。 -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` +[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! + +環境固有のコードを作成する必要がある場合は、`process.env.NODE_ENV` を使用して NODE_ENV の値を確認できます。どの環境変数の値を確認する場合でもパフォーマンスに悪影響が及ぶため、慎重に行ってください。 Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. -詳細については、[Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables) を参照してください。 +開発環境では、通常、対話式シェルで環境変数を設定します。例えば、`export` または `.bash_profile` ファイルを使用します。しかし、一般的には実動サーバーではそうしません。代わりに、OS の init システム (systemd または Upstart) を使用します。次のセクションでは、init システムの一般的な使用法について詳しく説明しています。ここで重点的に説明したのは、NODE_ENV の設定がパフォーマンスにとって極めて重要であるため (かつ簡単に実行できるため) です。 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 では、unit ファイルで `Environment` ディレクティブを使用します。次に例を示します。 +systemd では、unit ファイルで `Environment` ディレクティブを使用します。次に例を示します。 For example: ```sh # /etc/systemd/system/myservice.service Environment=NODE_ENV=production ``` -詳細については、[Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html) を参照してください。 +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### アプリケーションが確実に自動再始動するようにする -実稼働環境では、アプリケーションを絶対にオフラインにしたくありません。つまり、アプリケーションが異常終了した場合も、サーバー自体が異常終了した場合も、アプリケーションが必ず再始動するようにする必要があります。いずれの事態も望ましくないことですが、現実的には以下の対策を通して両方の事態に備えておく必要があります。 +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: -* アプリケーション (および Node) が異常終了した場合にプロセス・マネージャーを使用してそれらを再始動する。 -* OS の異常終了時に、OS で提供されている init システムを使用してプロセス・マネージャーを再始動する。プロセス・マネージャーがなくても、init システムを使用することは可能です。 +- アプリケーション (および Node) が異常終了した場合にプロセス・マネージャーを使用してそれらを再始動する。 +- 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 アプリケーションは、キャッチされていない例外が発生すると、異常終了します。最初に実行する必要があることは、アプリケーションが十分にテストされていて、すべての例外を処理することを確認することです (詳細については、[例外を適切に処理する](#exceptions)を参照)。ただし、フェイルセーフ動作として、アプリケーションが異常終了した場合に確実に自動再始動するためのメカニズムを適用してください。 +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 server.js` などを使用してアプリケーションを開始しています。ただし、この方法を実稼働環境で実行すると、危険を招くことになります。アプリケーションが異常終了した場合、アプリケーションは再始動されるまでオフラインになります。アプリケーションが異常終了した場合に確実に再始動するようにするには、プロセス・マネージャーを使用します。プロセス・マネージャーは、デプロイメントを容易に行えるようにして、高可用性を実現し、アプリケーションを実行時に管理できるようにする、アプリケーションの「コンテナー」です。 +開発環境では、単にコマンド・ラインから `node server.js` などを使用してアプリケーションを開始しています。ただし、この方法を実稼働環境で実行すると、危険を招くことになります。アプリケーションが異常終了した場合、アプリケーションは再始動されるまでオフラインになります。アプリケーションが異常終了した場合に確実に再始動するようにするには、プロセス・マネージャーを使用します。プロセス・マネージャーは、デプロイメントを容易に行えるようにして、高可用性を実現し、アプリケーションを実行時に管理できるようにする、アプリケーションの「コンテナー」です。 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. アプリケーションを異常終了時に再始動することに加えて、プロセス・マネージャーでは以下が可能になります。 -* ランタイム・パフォーマンスとリソース使用量に関するインサイトを得る。 -* パフォーマンスを向上させるために設定を動的に変更する。 -* クラスタリングを制御する (StrongLoop PM および pm2)。 - -Node 向けの最も一般的なプロセス・マネージャーは次のとおりです。 - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -3 つのプロセス・マネージャーの各機能の比較については、[http://strong-pm.io/compare/](http://strong-pm.io/compare/) を参照してください。 +- ランタイム・パフォーマンスとリソース使用量に関するインサイトを得る。 +- パフォーマンスを向上させるために設定を動的に変更する。 +- Control clustering (pm2). -これらのプロセス・マネージャーのいずれかを使用すれば、時々異常終了してもアプリケーションの稼働状態を維持するのに十分です。 - -ただし、StrongLoop PM には、明確に実動でのデプロイメントを対象とした機能が数多くあります。このツールを関連する StrongLoop ツールとともに使用して、以下を実行できます。 - -* アプリケーションをローカル側で作成してパッケージし、実動システムのセキュアにデプロイする。 -* 何らかの理由で異常終了したアプリケーションを自動的に再始動する。 -* クラスターをリモート側で管理する。 -* CPU プロファイルとヒープ・スナップショットを表示して、パフォーマンスを最適化し、メモリー・リークを診断する。 -* アプリケーションのパフォーマンス・メトリックを表示する。 -* Nginx ロード・バランサーの制御が統合された複数のホストに容易に拡張する。 - -下記で説明するように、init システムを使用して、StrongLoop PM をオペレーティング・システム・サービスとしてインストールすると、システムの再始動時に自動的に再始動します。そのため、アプリケーション・プロセスとクラスターの稼働が永続的に維持されます。 +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 システムの使用 -次の信頼性の層は、サーバーの再始動時にアプリケーションが確実に再始動するようにすることです。システムもさまざまな理由でダウンすることがあります。サーバーが異常終了した場合にアプリケーションが確実に再始動するようにするには、OS に組み込まれている init システムを使用します。今日使用されている 2 つの主な init システムは、[systemd](https://wiki.debian.org/systemd) および [Upstart](http://upstart.ubuntu.com/) です。 +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 つあります。 -* プロセス・マネージャーでアプリケーションを実行し、init システムを使用してプロセス・マネージャーをサービスとしてインストールします。アプリケーションが異常終了した場合にプロセス・マネージャーが再始動して、OS の再始動時に init システムがプロセス・マネージャーを再始動します。この方法をお勧めします。 -* init システムで直接、アプリケーション (および Node) を実行します。この方法の方が単純ですが、プロセス・マネージャーを使用する場合に得られる利点は得られません。 +- 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. +- init システムで直接、アプリケーション (および Node) を実行します。この方法の方が単純ですが、プロセス・マネージャーを使用する場合に得られる利点は得られません。 This is somewhat simpler, but you don't get the additional advantages of using a process manager. ##### Systemd -Systemd は、Linux システムとサービス・マネージャーです。大半の主要な Linux ディストリビューションでは、Systemd がデフォルトの init システムとして採用されています。 +Systemd は、Linux システムとサービス・マネージャーです。大半の主要な Linux ディストリビューションでは、Systemd がデフォルトの init システムとして採用されています。 Most major Linux distributions have adopted systemd as their default init system. -Systemd サービス構成ファイルは、*unit ファイル* という名前で、ファイル名の末尾は .service です。次に、Node アプリケーションを直接管理するための unit ファイルの例を示します (太字のテキストを、ご使用のシステムとアプリケーションの値に置き換えてください)。 +Systemd サービス構成ファイルは、_unit ファイル_ という名前で、ファイル名の末尾は .service です。次に、Node アプリケーションを直接管理するための unit ファイルの例を示します (太字のテキストを、ご使用のシステムとアプリケーションの値に置き換えてください)。 Here's an example unit file to manage a Node app directly. Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -292,123 +250,23 @@ WantedBy=multi-user.target Systemd について詳しくは、[systemd の解説 (man ページ)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html) を参照してください。 -##### Systemd サービスとしての StrongLoop PM - -StrongLoop Process Manager を Systemd サービスとして簡単にインストールできます。インストール後、サーバーが再始動すると、StrongLoop PM が自動的に再始動され、管理対象アプリケーションのすべてが再始動されます。 - -StrongLoop PM を Systemd サービスとしてインストールするには、次のようにします。 - -```bash -$ sudo sl-pm-install --systemd -``` - -次に、サービスを開始します。 - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -詳しくは、[Setting up a production host (StrongLoop 資料)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10) を参照してください。 - -##### Upstart - -Upstart は、多くの Linux ディストリビューションで提供されているシステム・ツールです。システム始動時にタスクとサービスを開始して、シャットダウン時にそれらを停止するほか、監視するために使用されます。Express アプリケーションまたはプロセス・マネージャーをサービスとして構成すると、Upstart が異常終了時に自動的に再始動します。 - -Upstart サービスは、ファイル名が `.conf` で終わるジョブ構成ファイル (「ジョブ」とも呼ばれます) で定義されます。次の例は、`/projects/myapp/index.js` にあるメインファイルを使用して、「myapp」というアプリケーションの「myapp」というジョブを作成する方法を示しています。 - -以下の内容で `myapp.conf` というファイルを `/etc/init/` に作成します (太字のテキストを、ご使用のシステムとアプリケーションの値に置き換えてください)。 - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -注: このスクリプトには、Ubuntu 12.04-14.10 でサポートされる Upstart 1.4 以降が必要です。 - -ジョブは、システムの始動時に実行されるように構成されるため、アプリケーションは、オペレーティング・システムと並行して開始され、アプリケーションの異常終了時またはシステムの停止時に自動的に再始動されます。 - -アプリケーションの自動再始動のほか、Upstart では、以下のコマンドを使用できます。 - -* `start myapp` – アプリケーションの開始 -* `restart myapp` – アプリケーションの再始動 -* `stop myapp` – アプリケーションの停止 - -Upstart について詳しくは、[Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook) を参照してください。 - -##### Upstart サービスとしての StrongLoop PM - -StrongLoop Process Manager を Upstart サービスとして簡単にインストールできます。インストール後、サーバーが再始動すると、StrongLoop PM が自動的に再始動され、管理対象アプリケーションのすべてが再始動されます。 - -StrongLoop PM を Upstart 1.4 サービスとしてインストールするには、次のようにします。 - -```bash -$ sudo sl-pm-install -``` - -次に、サービスを実行します。 - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -注: Upstart 1.4 をサポートしないシステムでは、コマンドが若干異なります。詳しくは、[Setting up a production host (StrongLoop 資料)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) を参照してください。 - ### アプリケーションをクラスターで実行する -マルチコア・システムでは、プロセスのクラスターを起動することで、Node アプリケーションのパフォーマンスを数倍も向上させることができます。クラスターは、アプリケーションの複数インスタンスを実行して (理想的には CPU コアごとに 1 つのインスタンス)、負荷とタスクをインスタンス間で分散させます。 +マルチコア・システムでは、プロセスのクラスターを起動することで、Node アプリケーションのパフォーマンスを数倍も向上させることができます。クラスターは、アプリケーションの複数インスタンスを実行して (理想的には CPU コアごとに 1 つのインスタンス)、負荷とタスクをインスタンス間で分散させます。 A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances. ![クラスター API を使用したアプリケーション・インスタンス間のバランシング](/images/clustering.png) -重要: アプリケーション・インスタンスは別々のインスタンスとして実行されるため、同じメモリー・スペースを共有しません。つまり、オブジェクトは、アプリケーションの各インスタンスに対してローカル側にあります。そのため、アプリケーション・コードの状態を維持できません。ただし、[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](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. -クラスター・アプリケーションでは、ワーカー・プロセスは、残りのプロセスに影響を与えることなく、個々に異常終了することがあります。パフォーマンス上の利点の他に障害分離は、アプリケーション・プロセスのクラスターを実行するもう 1 つの理由です。ワーカー・プロセスが異常終了するたびに、必ず、イベントをログに記録して、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. クラスター・アプリケーションでは、ワーカー・プロセスは、残りのプロセスに影響を与えることなく、個々に異常終了することがあります。パフォーマンス上の利点の他に障害分離は、アプリケーション・プロセスのクラスターを実行するもう 1 つの理由です。ワーカー・プロセスが異常終了するたびに、必ず、イベントをログに記録して、cluster.fork() を使用して新規プロセスを作成してください。 #### Node のクラスター・モジュールの使用 -クラスタリングには、Node の[クラスター・モジュール](https://nodejs.org/api/cluster.html.)を使用します。このモジュールにより、マスター・プロセスは、ワーカー・プロセスを作成して、着信接続をワーカー間で分散させることができます。ただし、このモジュールを直接使用するよりも、[node-pm](https://www.npmjs.com/package/node-pm) や [cluster-service](https://www.npmjs.com/package/cluster-service) など、これらの処理を自動的に実行する多くのツールを使用する方がはるかに簡単です。 - -#### StrongLoop PM の使用 - -アプリケーションを StrongLoop Process Manager (PM) にデプロイする場合、アプリケーション・コードを変更*せずに*、クラスタリングを利用できます。 - -StrongLoop Process Manager (PM) は、アプリケーションを実行する際、システム上の CPU コアの数と等しい数のワーカーを使用するクラスターで自動的に実行します。クラスター内のワーカー・プロセスの数は、アプリケーションを停止することなく、slc コマンド・ライン・ツールを使用して手動で変更できます。 - -例えば、アプリケーションを prod.foo.com にデプロイして、StrongLoop PM がポート 8701 (デフォルト) で listen している場合は、slc を使用してクラスター・サイズを 8 に設定します。 - -```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 -``` - -StrongLoop PM を使用したクラスタリングについて詳しくは、StrongLoop 資料の [Clustering](https://docs.strongloop.com/display/SLC/Clustering) を参照してください。 +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 の使用 -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](http://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). +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). 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. @@ -416,9 +274,9 @@ To enable cluster mode, start your application like so: ```bash # Start 4 worker processes -$ pm2 start app.js -i 4 +$ pm2 start npm --name my-app -i 4 -- start # Auto-detect number of available CPUs and start that many worker processes -$ pm2 start app.js -i max +$ 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. @@ -427,9 +285,9 @@ Once running, a given application with the name `app` can be scaled like so: ```bash # Add 3 more workers -$ pm2 scale app +3 +$ pm2 scale my-app +3 # Scale to a specific number of workers -$ pm2 scale app 2 +$ 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. @@ -438,18 +296,18 @@ For more information on clustering with PM2, see [Cluster Mode](https://pm2.keym 実稼働環境のパフォーマンスを向上させるもう 1 つの戦略は、アプリケーションが同じ要求に何回も対応するために操作を繰り返すことがないように、要求の結果をキャッシュに入れることです。 -[Varnish](https://www.varnish-cache.org/) や [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) ([Nginx Caching](https://serversforhackers.com/nginx-caching/) も参照) などのキャッシュ・サーバーを使用すると、アプリケーションの速度とパフォーマンスを大幅に向上させることができます。 +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-load-balancer) -アプリケーションがどれだけ最適化されていても、単一インスタンスは、限られた量の負荷とトラフィックしか処理できません。アプリケーションを拡張する 1 つの方法は、複数インスタンスを実行して、ロード・バランサーを使用してトラフィックを分散させることです。ロード・バランサーをセットアップすると、アプリケーションのパフォーマンスと速度を向上させることができ、単一インスタンスよりも大規模に拡張できます。 +アプリケーションがどれだけ最適化されていても、単一インスタンスは、限られた量の負荷とトラフィックしか処理できません。アプリケーションを拡張する 1 つの方法は、複数インスタンスを実行して、ロード・バランサーを使用してトラフィックを分散させることです。ロード・バランサーをセットアップすると、アプリケーションのパフォーマンスと速度を向上させることができ、単一インスタンスよりも大規模に拡張できます。 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](http://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 に関連する要求が発信元のプロセスに接続することを確認する必要があります。これは、*セッション・アフィニティー* または*スティッキー・セッション* と呼ばれ、セッション・データに Redis などのデータ・ストアを使用する上記の提案によって対応できます (ご使用のアプリケーションによって異なります)。説明については、[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.com/) や [HAProxy](http://www.haproxy.org/) などのリバース・プロキシーの背後で実行することをお勧めします。 +アプリケーションの状態を知る必要のないタスクをリバース・プロキシーに引き渡すことで、Express が解放されて、特殊なアプリケーション・タスクを実行できるようになります。この理由から、実稼働環境で Express を [Nginx](https://www.nginx.com/) や [HAProxy](http://www.haproxy.org/) などのリバース・プロキシーの背後で実行することをお勧めします。 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. diff --git a/ja/advanced/best-practice-security.md b/ja/advanced/best-practice-security.md old mode 100755 new mode 100644 index 212c2391f3..1c3bac5eb2 --- a/ja/advanced/best-practice-security.md +++ b/ja/advanced/best-practice-security.md @@ -1,65 +1,114 @@ --- layout: page title: 実稼働環境における Express のセキュリティーに関するベスト・プラクティス +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: ja -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # 実稼働環境におけるベスト・プラクティス: セキュリティー ## 概説 -「*実稼働*」という用語は、ソフトウェアのライフサイクルにおいて、アプリケーションや API をエンド・ユーザーまたはコンシューマーが広く使用できる段階を指します。対照的に、「*開発*」段階では、まだコードの作成とテストを積極的に行っていて、アプリケーションへの外部アクセスは不可能です。対応するシステム環境は、それぞれ*実稼働* 環境と*開発* 環境と呼ばれています。 +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. -開発環境と実稼働環境は通常、別々にセットアップされ、それぞれの要件は大きく異なっています。開発環境では許可されることが、実稼働環境では許可されないことがあります。例えば、開発環境ではデバッグのためにエラーの詳細なロギングを実行できますが、同じ動作が実稼働環境ではセキュリティー上の問題となります。開発環境では、スケーラビリティー、信頼性、パフォーマンスについて心配する必要はありませんが、それらは実稼働環境では重大な問題となります。 +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. -{% include admonitions/note.html content="If you believe you have discovered a security vulnerability in Express, please see [Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures)." %} +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} 本番環境でのExpressアプリケーションのセキュリティのベスト・プラクティスは次のとおりです。 -- [非推奨バージョンや脆弱なバージョンの Express を使用しない](#dont-use-deprecated-or-vulnerable-versions-of-express) -- [TLS を使用する](#use-tls) -- [Helmet を使用する](#use-helmet) -- [Cookie をセキュアに使用する](#use-cookies-securely) -- [依存関係がセキュアであることを確認する](#ensure-your-dependencies-are-secure) -- [その他の既知の脆弱性を回避する](#avoid-other-known-vulnerabilities) -- [その他の考慮事項](#additional-considerations) +- [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) + - [TLS を使用する](#use-tls) + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [Helmet を使用する](#use-helmet) + - [Reduce fingerprinting](#reduce-fingerprinting) + - [Cookie をセキュアに使用する](#use-cookies-securely) + - 対照的に、[cookie-session](https://www.npmjs.com/package/cookie-session) ミドルウェアは、Cookie が支持するストレージを実装します。セッション・キーだけでなく、セッション全体を Cookie に対して直列化します。これは、セッション・データが比較的小規模で、(オブジェクトではなく) プリミティブ値として容易にエンコードできる場合にのみ使用してください。ブラウザーは Cookie 当たり最小 4096 バイトをサポートすることが想定されますが、その制限を必ず超えないようにするために、ドメイン当たり 4093 バイトのサイズを超えないようにしてください。また、Cookie データがクライアントに対して可視になることに注意してください。何らかの理由でデータを保護したり覆い隠したりする必要がある場合は、express-session を使用することをお勧めします。 + - デフォルトのセッション Cookie 名を使用すると、アプリケーションが攻撃を受けやすくなります。提起されているセキュリティー問題は `X-Powered-By` と似ています。潜在的なアタッカーがこれを使用して、サーバーに対して指紋認証し、攻撃の標的にする可能性があります。 + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [依存関係がセキュアであることを確認する](#ensure-your-dependencies-are-secure) + - [その他の既知の脆弱性を回避する](#avoid-other-known-vulnerabilities) + - [その他の考慮事項](#additional-considerations) ## 非推奨バージョンや脆弱なバージョンの Express を使用しない -Express 2.x および 3.x は保守されなくなりました。これらのバージョンにおけるセキュリティーとパフォーマンスの問題は修正されません。これらのバージョンを決して使用しないでください。まだバージョン 4 に移行していない場合は、[マイグレーション・ガイド](/{{ page.lang }}/guide/migrating-4.html)に従ってください。 +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](/{{ page.lang }}/guide/migrating-4.html) or consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). -また、[セキュリティー更新ページ](/{{ page.lang }}/advanced/security-updates.html)にリストされている脆弱な Express バージョンを使用していないことを確認してください。使用している場合は、安定しているリリース (最新を推奨します) に更新してください。 +また、[セキュリティー更新ページ](/{{ page.lang }}/advanced/security-updates.html)にリストされている脆弱な Express バージョンを使用していないことを確認してください。使用している場合は、安定しているリリース (最新を推奨します) に更新してください。 If you are, update to one of the stable releases, preferably the latest. ## TLS を使用する -アプリケーションが機密データを処理または送信する場合は、[Transport Layer Security](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)に対して脆弱です。 +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). -Secure Socket Layer (SSL) 暗号化については理解されていると思います。[TLS は、単に SSL が進化したものです](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx)。つまり、以前に SSL を使用していた場合は、TLS へのアップグレードを検討してください。一般に、TLS を処理するために Nginx を使用することをお勧めします。Nginx (およびその他のサーバー) で TLS を構成するための解説については、[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. Secure Socket Layer (SSL) 暗号化については理解されていると思います。[TLS は、単に SSL が進化したものです](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx)。つまり、以前に SSL を使用していた場合は、TLS へのアップグレードを検討してください。一般に、TLS を処理するために Nginx を使用することをお勧めします。Nginx (およびその他のサーバー) で TLS を構成するための解説については、[Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations) を参照してください。 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). また、[Let's Encrypt](https://letsencrypt.org/about/) は、無料の TLS 証明書を取得するための便利なツールです。このツールは、[Internet Security Research Group (ISRG)](https://letsencrypt.org/isrg/) が提供する、無料の自動的かつオープンな認証局 (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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## Helmet を使用する [Helmet](https://www.npmjs.com/package/helmet) は、HTTP ヘッダーを適切に設定することによって、いくつかの既知の Web の脆弱性からアプリケーションを保護します。 -Helmet は、実際には、セキュリティー関連の HTTP ヘッダーを設定する 9 個の小さなミドルウェア関数の単なる集合です。 +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: -* [csp](https://github.com/helmetjs/csp) は、クロスサイト・スクリプティング攻撃やその他のクロスサイト・インジェクションを防止するために `Content-Security-Policy` ヘッダーを設定します。 -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) は、`X-Powered-By` ヘッダーを削除します。 -* [hsts](https://github.com/helmetjs/hsts) は、サーバーへのセキュア (SSL/TLS を介して HTTP) 接続を適用する `Strict-Transport-Security` ヘッダーを設定します。 -* [ieNoOpen](https://github.com/helmetjs/ienoopen) は、IE8+ の `X-Download-Options` を設定します。 -* [noCache](https://github.com/helmetjs/nocache) は、クライアント側のキャッシュを無効にするために `Cache-Control` ヘッダーと Pragma ヘッダーを設定します。 -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) は、宣言されているコンテンツの種類からの応答をブラウザーが MIME スニッフィングしないように、`X-Content-Type-Options` を設定します。 -* [frameguard](https://github.com/helmetjs/frameguard) は、[クリックジャッキング](https://www.owasp.org/index.php/Clickjacking)保護を有効にするために `X-Frame-Options` ヘッダーを設定します。 -* [xssFilter](https://github.com/helmetjs/x-xss-protection) は、最新の Web ブラウザーでクロスサイト・スクリプティング (XSS) フィルターを有効にするために `X-XSS-Protection` を設定します。 +- `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 +- `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 +- `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 + +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. その他のモジュールと同様に Helmet をインストールします。 ```bash -$ npm install --save helmet +$ npm install helmet ``` 次に、コードで使用します。 @@ -73,9 +122,13 @@ app.use(helmet()) // ... ``` -### 少なくとも X-Powered-By ヘッダーを無効にする +## Reduce fingerprinting -Helmet を使用しない場合は、少なくとも `X-Powered-By` ヘッダーを無効にしてください。アタッカーが、(デフォルトで有効になっている) このヘッダーを使用して、Express を実行しているアプリケーションを検出し、具体的に対象を絞った攻撃を開始する可能性があります。 +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. そのため、`app.disable()` メソッドを使用してこのヘッダーをオフにすることがベスト・プラクティスです。 @@ -83,9 +136,37 @@ Helmet を使用しない場合は、少なくとも `X-Powered-By` ヘッダー app.disable('x-powered-by') ``` -`helmet.js` を使用する場合は、この操作が自動的に実行されます。 +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} -{% include admonitions/note.html content="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. "%} +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## Cookie をセキュアに使用する @@ -93,16 +174,16 @@ Cookie を介してアプリケーションが悪用されないように、デ 主なミドルウェア Cookie セッション・モジュールが 2 つあります。 -* [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` ミドルウェアに取って代わります。 +- [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` ミドルウェアに取って代わります。 -これらの 2 つのモジュールの主な違いは、Cookie セッション・データの保存方法です。[express-session](https://www.npmjs.com/package/express-session) ミドルウェアは、セッション・データをサーバーに保管します。セッション・データではなく、Cookie 自体の中にあるセッション ID のみを保存します。デフォルトで、メモリー内のストレージを使用し、実稼働環境向けには設計されていません。実稼働環境では、スケーラブルなセッション・ストアをセットアップする必要があります。[互換性のあるセッション・ストア](https://github.com/expressjs/session#compatible-session-stores)のリストを参照してください。 +The main difference between these two modules is how they save cookie session data. これらの 2 つのモジュールの主な違いは、Cookie セッション・データの保存方法です。[express-session](https://www.npmjs.com/package/express-session) ミドルウェアは、セッション・データをサーバーに保管します。セッション・データではなく、Cookie 自体の中にあるセッション ID のみを保存します。デフォルトで、メモリー内のストレージを使用し、実稼働環境向けには設計されていません。実稼働環境では、スケーラブルなセッション・ストアをセットアップする必要があります。[互換性のあるセッション・ストア](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) ミドルウェアは、Cookie が支持するストレージを実装します。セッション・キーだけでなく、セッション全体を Cookie に対して直列化します。これは、セッション・データが比較的小規模で、(オブジェクトではなく) プリミティブ値として容易にエンコードできる場合にのみ使用してください。ブラウザーは Cookie 当たり最小 4096 バイトをサポートすることが想定されますが、その制限を必ず超えないようにするために、ドメイン当たり 4093 バイトのサイズを超えないようにしてください。また、Cookie データがクライアントに対して可視になることに注意してください。何らかの理由でデータを保護したり覆い隠したりする必要がある場合は、express-session を使用することをお勧めします。 +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 名を使用しない -デフォルトのセッション Cookie 名を使用すると、アプリケーションが攻撃を受けやすくなります。提起されているセキュリティー問題は `X-Powered-By` と似ています。潜在的なアタッカーがこれを使用して、サーバーに対して指紋認証し、攻撃の標的にする可能性があります。 +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 名を使用します。例えば、[express-session](https://www.npmjs.com/package/express-session) ミドルウェアを使用します。 @@ -119,11 +200,11 @@ app.use(session({ セキュリティーを強化するために、以下の Cookie オプションを設定します。 -* `secure` - ブラウザーが確実に HTTPS のみを介して Cookie を送信するようにします。 -* `httpOnly` - Cookie がクライアント JavaScript ではなく、HTTP(S) のみを介して送信されるようにして、クロスサイト・スクリプティング攻撃から保護します。 -* `domain` - Cookie のドメインを指定します。URL が要求されているサーバーのドメインとの比較に使用します。一致する場合は、次にパス属性を確認します。 -* `path` - Cookie のパスを指定します。要求パスとの比較に使用します。このパスがドメインと一致する場合は、要求の Cookie を送信します。 -* `expires` - 永続的な Cookie の有効期限を設定するために使用します。 +- `secure` - ブラウザーが確実に HTTPS のみを介して Cookie を送信するようにします。 +- `httpOnly` - Cookie がクライアント JavaScript ではなく、HTTP(S) のみを介して送信されるようにして、クロスサイト・スクリプティング攻撃から保護します。 +- `domain` - Cookie のドメインを指定します。URL が要求されているサーバーのドメインとの比較に使用します。一致する場合は、次にパス属性を確認します。 If they match, then check the path attribute next. +- `path` - Cookie のパスを指定します。要求パスとの比較に使用します。このパスがドメインと一致する場合は、要求の Cookie を送信します。 If this and domain match, then send the cookie in the request. +- `expires` - 永続的な Cookie の有効期限を設定するために使用します。 次に、[cookie-session](https://www.npmjs.com/package/cookie-session) ミドルウェアの使用例を示します。 @@ -146,11 +227,22 @@ app.use(session({ })) ``` +## 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. + +[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) + ## 依存関係がセキュアであることを確認する -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 @@ -158,7 +250,7 @@ $ npm audit よりセキュアな状態を保ちたい場合は、[Snyk](https://snyk.io/)を検討してください。 -Snykは、[Snykのオープンソース脆弱性データベース](https://snyk.io/vuln/)に対して、依存関係の既知の脆弱性に対するアプリケーションをチェックする[コマンドラインツール](https://www.npmjs.com/package/snyk)と[Github integration](https://snyk.io/docs/github)を提供しています。 次のようにCLIをインストールします。 +Snykは、[Snykのオープンソース脆弱性データベース](https://snyk.io/vuln/)に対して、依存関係の既知の脆弱性に対するアプリケーションをチェックする[コマンドラインツール](https://www.npmjs.com/package/snyk)と[Github integration](https://snyk.io/docs/github)を提供しています。 次のようにCLIをインストールします。 Install the CLI as follows: ```bash $ npm install -g snyk @@ -171,19 +263,20 @@ $ cd your-app $ snyk test ``` -## その他の既知の脆弱性を回避する +### その他の既知の脆弱性を回避する -アプリケーションで使用する Express やその他のモジュールに影響を与える可能性がある [Node Security Project](https://npmjs.com/advisories) のアドバイザリーに常に注意してください。一般に、Node Security Project は、Node のセキュリティーに関する知識とツールの優れたリソースです。 +アプリケーションで使用する Express やその他のモジュールに影響を与える可能性がある [Node Security Project](https://npmjs.com/advisories) のアドバイザリーに常に注意してください。一般に、Node Security Project は、Node のセキュリティーに関する知識とツールの優れたリソースです。 In general, these databases are excellent resources for knowledge and tools about Node security. -最後に、Express アプリケーションは、その他の Web アプリケーションと同様、さまざまな Web ベースの攻撃に対して脆弱になりえます。既知の [Web の脆弱性](https://www.owasp.org/www-project-top-ten/)をよく理解して、それらを回避するための予防措置を取ってください。 +最後に、Express アプリケーションは、その他の Web アプリケーションと同様、さまざまな Web ベースの攻撃に対して脆弱になりえます。既知の [Web の脆弱性](https://www.owasp.org/www-project-top-ten/)をよく理解して、それらを回避するための予防措置を取ってください。 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 インジェクション攻撃に対して防衛してください。 +- オープン・ソースの [sqlmap](http://sqlmap.org/) ツールを使用して、アプリケーションの SQL インジェクションに対する脆弱性を検出してください。 +- [nmap](https://nmap.org/) ツールと [sslyze](https://github.com/nabla-c0d3/sslyze) ツールを使用して、SSL 暗号、鍵、再交渉の構成のほか、証明書の妥当性をテストしてください。 +- [safe-regex](https://www.npmjs.com/package/safe-regex) を使用して、使用している正規表現が[正規表現サービス妨害](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻撃を受けやすくなっていないことを確認してください。 -* 認証に対する総当たり攻撃を防止するために、回数制限を実装してください。そのための 1 つの方法では、[StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) を使用して回数制限ポリシーを適用します。あるいは、[express-limiter](https://www.npmjs.com/package/express-limiter) などのミドルウェアを使用できますが、そのためにはコードを若干変更する必要があります。 -* クロスサイト・スクリプティング (XSS) とコマンド・インジェクション攻撃から保護するために、必ず、ユーザー入力のフィルタリングとサニタイズを実行してください。 -* パラメーター化照会または作成済みステートメントを使用して、SQL インジェクション攻撃に対して防衛してください。 -* オープン・ソースの [sqlmap](http://sqlmap.org/) ツールを使用して、アプリケーションの SQL インジェクションに対する脆弱性を検出してください。 -* [nmap](https://nmap.org/) ツールと [sslyze](https://github.com/nabla-c0d3/sslyze) ツールを使用して、SSL 暗号、鍵、再交渉の構成のほか、証明書の妥当性をテストしてください。 -* [safe-regex](https://www.npmjs.com/package/safe-regex) を使用して、使用している正規表現が[正規表現サービス妨害](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻撃を受けやすくなっていないことを確認してください。 +[helmet]: <`helmet.js` を使用する場合は、この操作が自動的に実行されます。> \ No newline at end of file diff --git a/ja/advanced/developing-template-engines.md b/ja/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 8766bedb18..28b09b8e49 --- a/ja/advanced/developing-template-engines.md +++ b/ja/advanced/developing-template-engines.md @@ -1,15 +1,15 @@ --- layout: page title: 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. menu: advanced lang: ja -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. +redirect_from: " " --- # Express 用のテンプレート・エンジンの開発 -独自のテンプレート・エンジンを作成するには、`app.engine(ext, callback)` メソッドを使用します。`ext` はファイル拡張子を表し、`callback` はテンプレート・エンジン関数です。この関数は、ファイルのロケーション、options オブジェクト、およびコールバック関数の項目をパラメーターとして受け入れます。 +独自のテンプレート・エンジンを作成するには、`app.engine(ext, callback)` メソッドを使用します。`ext` はファイル拡張子を表し、`callback` はテンプレート・エンジン関数です。この関数は、ファイルのロケーション、options オブジェクト、およびコールバック関数の項目をパラメーターとして受け入れます。 `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. 次のコードは、`.ntl` ファイルをレンダリングするための極めて単純なテンプレート・エンジンを実装する例です。 @@ -19,7 +19,8 @@ app.engine('ntl', (filePath, options, callback) => { // define the template engi fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -28,12 +29,13 @@ app.set('views', './views') // specify the views directory app.set('view engine', 'ntl') // register the template engine ``` -これで、アプリケーションは `.ntl` ファイルをレンダリングできるようになります。以下のコンテンツで `index.ntl` というファイルを `views` ディレクトリーに作成します。 +Your app will now be able to render `.ntl` files. これで、アプリケーションは `.ntl` ファイルをレンダリングできるようになります。以下のコンテンツで `index.ntl` というファイルを `views` ディレクトリーに作成します。 ```pug #title# #message# ``` + 次に、アプリケーションで次のルートを作成します。 ```js @@ -41,4 +43,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -ホーム・ページに要求すると、`index.ntl` ファイルは HTML としてレンダリングされます。 + +ホーム・ページに要求すると、`index.ntl` ファイルは HTML としてレンダリングされます。 \ No newline at end of file diff --git a/ja/advanced/healthcheck-graceful-shutdown.md b/ja/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..6217c7d07a --- /dev/null +++ b/ja/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: ja +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### 例 + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/ja/advanced/security-updates.md b/ja/advanced/security-updates.md old mode 100755 new mode 100644 index fee979bc32..47c2bb3180 --- a/ja/advanced/security-updates.md +++ b/ja/advanced/security-updates.md @@ -1,70 +1,88 @@ --- layout: page title: Express のセキュリティー更新 +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: ja -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # セキュリティー更新
    - Node.js の脆弱性は Express に直接影響を与えます。そのため、[Node.js の脆弱性の監視を続けて](https://nodejs.org -/en/blog/vulnerability/)、必ず、安定した最新バージョンの Node.js を使用してください。 - +/en/blog/vulnerability/)、必ず、安定した最新バージョンの Node.js を使用してください。 Therefore, [keep a watch on Node.js vulnerabilities](https://nodejs.org/en/blog/vulnerability/) and make sure you are using the latest stable version of Node.js.
    次のリストに、示されているバージョンの更新で修正された Express の脆弱性を列挙します。 -**注意**: Expressでセキュリティ上の脆弱性を発見したと思われる場合は、[セキュリティポリシーと手順](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures)を参照してください。 +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} ## 4.x - * 4.16.0 - * 依存関係`forwarded`は、[脆弱性](https://npmjs.com/advisories/527)に対処するために更新されました。これは、`req.host`、`req.hostname`、`req.ip`、`req.ips`、`req.protocol`のAPIが使用されている場合、アプリケーションに影響を与える可能性があります。 - * 依存関係`mime`は[脆弱性](https://npmjs.com/advisories/535)に対処するために更新されましたが、この問題はExpressには影響しません。 - * 依存関係`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 - * 依存関係`debug`は[脆弱性](https://snyk.io/vuln/npm:debug:20170905)に対処するために更新されましたが、この問題はExpressには影響しません。 - * 依存関係`fresh`は、[脆弱性](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 - * 依存関係`ms`は、[脆弱性](https://snyk.io/vuln/npm:ms:20170412)に対処するために更新されました。`express.static`、`res.sendfile`、および`res.sendFile`のAPIで、信頼できない文字列が入力され`maxAge`オプションに渡されると、アプリケーションに影響を与える可能性があります。 - * 4.15.2 - * 依存関係`qs`は[脆弱性](https://snyk.io/vuln/npm:qs:20170213)に対処するために更新されましたが、この問題はExpressには影響しません。4.15.2へのアップデートは良い習慣ですが、この脆弱性に対処する必要はありません。 - * 4.11.1 - * `express.static`、`res.sendfile`、および `res.sendFile` のルート・パス開示の脆弱性を修正しました。 - * 4.10.7 - * `express.static` のオープン・リダイレクトの脆弱性を修正しました ([アドバイザリー](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))。 - * 4.8.8 - * `express.static` のディレクトリー・トラバーサルの脆弱性を修正しました ([アドバイザリー](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 は、特定の状況で `fd` をリークして、`express.static` および `res.sendfile` に影響を及ぼす可能性があります。悪意ある要求によって `fd` がリークされ、最終的に `EMFILE` エラーが発生したり、サーバーが応答しなくなったりする可能性があります。 - * 4.8.0 - * クエリストリングに極めて多数の索引が含まれる疎な配列により、プロセスがメモリー不足になり、サーバーが異常終了する可能性があります。 - * 過度にネストされたクエリストリング・オブジェクトにより、プロセスがサーバーをブロックして、サーバーが一時的に応答できなくなる可能性があります。 +- 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). +- 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`. +- 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. +- 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`. +- 4.16.0 + - The dependency `forwarded` has been updated to address a [vulnerability](https://npmjs.com/advisories/527). 依存関係`forwarded`は、[脆弱性](https://npmjs.com/advisories/527)に対処するために更新されました。これは、`req.host`、`req.hostname`、`req.ip`、`req.ips`、`req.protocol`のAPIが使用されている場合、アプリケーションに影響を与える可能性があります。 + - 依存関係`mime`は[脆弱性](https://npmjs.com/advisories/535)に対処するために更新されましたが、この問題はExpressには影響しません。 + - 依存関係`send`が更新され、[Node.js 8.5.0の脆弱性](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/)に対する保護が提供されています。これは特定のNode.jsバージョン8.5.0でExpressを実行する場合にのみ影響します。 This only impacts running Express on the specific Node.js version 8.5.0. +- 4.15.5 + - 依存関係`debug`は[脆弱性](https://snyk.io/vuln/npm:debug:20170905)に対処するために更新されましたが、この問題はExpressには影響しません。 + - The dependency `fresh` has been updated to address a [vulnerability](https://npmjs.com/advisories/526). 依存関係`fresh`は、[脆弱性](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). 依存関係`ms`は、[脆弱性](https://snyk.io/vuln/npm:ms:20170412)に対処するために更新されました。`express.static`、`res.sendfile`、および`res.sendFile`のAPIで、信頼できない文字列が入力され`maxAge`オプションに渡されると、アプリケーションに影響を与える可能性があります。 +- 4.15.2 + - 依存関係`qs`は[脆弱性](https://snyk.io/vuln/npm:qs:20170213)に対処するために更新されましたが、この問題はExpressには影響しません。4.15.2へのアップデートは良い習慣ですが、この脆弱性に対処する必要はありません。 Updating to 4.15.2 is a good practice, but not required to address the vulnerability. +- 4.11.1 + - `express.static`、`res.sendfile`、および `res.sendFile` のルート・パス開示の脆弱性を修正しました。 +- 4.10.7 + - `express.static` のオープン・リダイレクトの脆弱性を修正しました ([アドバイザリー](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))。 +- 4.8.8 + - `express.static` のディレクトリー・トラバーサルの脆弱性を修正しました ([アドバイザリー](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 は、特定の状況で `fd` をリークして、`express.static` および `res.sendfile` に影響を及ぼす可能性があります。悪意ある要求によって `fd` がリークされ、最終的に `EMFILE` エラーが発生したり、サーバーが応答しなくなったりする可能性があります。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 4.8.0 + - クエリストリングに極めて多数の索引が含まれる疎配列により、プロセスがメモリー不足になり、サーバーが異常終了する可能性があります。 + - 過度にネストされたクエリストリング・オブジェクトにより、プロセスがサーバーをブロックして、サーバーが一時的に応答できなくなる可能性があります。 ## 3.x
    + **Express 3.x は保守されなくなりました** - **Express 3.x はもうメンテナンスされていません** +3.xの既知および未知のセキュリティ問題は、最終更新(2015年8月1日)以降は対処されていません。3.x系を使用することは安全であると見なされるべきではありません。 It is highly recommended to use the latest version of Express. - 3.xの既知および未知のセキュリティ問題は、最終更新(2015年8月1日)以降は対処されていません。3.x系を使用することは安全であると見なされるべきではありません。 +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options).
    - * 3.19.1 - * `express.static`、`res.sendfile`、および `res.sendFile` のルート・パス開示の脆弱性を修正しました。 - * 3.19.0 - * `express.static` のオープン・リダイレクトの脆弱性を修正しました ([アドバイザリー](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))。 - * 3.16.10 - * `express.static` のディレクトリー・トラバーサルの脆弱性を修正しました。 - * 3.16.6 - * Node.js 0.10 は、特定の状況で `fd` をリークして、`express.static` および `res.sendfile` に影響を及ぼす可能性があります。悪意ある要求によって `fd` がリークされ、最終的に `EMFILE` エラーが発生したり、サーバーが応答しなくなったりする可能性があります。 - * 3.16.0 - * クエリストリングに極めて多数の索引が含まれる疎配列により、プロセスがメモリー不足になり、サーバーが異常終了する可能性があります。 - * 過度にネストされたクエリストリング・オブジェクトにより、プロセスがサーバーをブロックして、サーバーが一時的に応答できなくなる可能性があります。 - * 3.3.0 - * サポートされていないメソッドのオーバーライドの 404 応答は、クロスサイト・スクリプティングの攻撃を受ける可能性がありました。 +- 3.19.1 + - `express.static`、`res.sendfile`、および `res.sendFile` のルート・パス開示の脆弱性を修正しました。 +- 3.19.0 + - `express.static` のオープン・リダイレクトの脆弱性を修正しました ([アドバイザリー](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))。 +- 3.16.10 + - `express.static` のディレクトリー・トラバーサルの脆弱性を修正しました。 +- 3.16.6 + - Node.js 0.10 は、特定の状況で `fd` をリークして、`express.static` および `res.sendfile` に影響を及ぼす可能性があります。悪意ある要求によって `fd` がリークされ、最終的に `EMFILE` エラーが発生したり、サーバーが応答しなくなったりする可能性があります。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 3.16.0 + - クエリストリングに極めて多数の索引が含まれる疎な配列により、プロセスがメモリー不足になり、サーバーが異常終了する可能性があります。 + - 過度にネストされたクエリストリング・オブジェクトにより、プロセスがサーバーをブロックして、サーバーが一時的に応答できなくなる可能性があります。 +- 3.3.0 + - サポートされていないメソッドのオーバーライドの 404 応答は、クロスサイト・スクリプティングの攻撃を受ける可能性がありました。 \ No newline at end of file diff --git a/ja/api.md b/ja/api.md old mode 100755 new mode 100644 index 09b80cab6d..ba66ec1915 --- a/ja/api.md +++ b/ja/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - API リファレンス +version: 5x +title: Express 5.x - API リファレンス +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: ja -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    4.x API

    - - - {% include api/en/4x/express.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
    diff --git a/ja/changelog/index.md b/ja/changelog/index.md new file mode 100644 index 0000000000..d9f33a61d1 --- /dev/null +++ b/ja/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: ja +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) to address a [vulnerability](https://npmjs.com/advisories/527). 依存関係`forwarded`は、[脆弱性](https://npmjs.com/advisories/527)に対処するために更新されました。これは、`req.host`、`req.hostname`、`req.ip`、`req.ips`、`req.protocol`のAPIが使用されている場合、アプリケーションに影響を与える可能性があります。 +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) to address a [vulnerability](https://npmjs.com/advisories/526). 依存関係`fresh`は、[脆弱性](https://npmjs.com/advisories/526)に対処するために更新されました。これは、次のAPIが使用されている場合、アプリケーションに影響します:`express.static`、`req.fresh`、`res.json`、`res.jsonp`、`res.send`、`res.sendfile`、`res.sendFile`、`res.sendStatus` +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://snyk.io/vuln/npm:ms:20170412). 依存関係`ms`は、[脆弱性](https://snyk.io/vuln/npm:ms:20170412)に対処するために更新されました。`express.static`、`res.sendfile`、および`res.sendFile`のAPIで、信頼できない文字列が入力され`maxAge`オプションに渡されると、アプリケーションに影響を与える可能性があります。 +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/ja/guide/behind-proxies.md b/ja/guide/behind-proxies.md old mode 100755 new mode 100644 index 836d99a2af..36c185edcb --- a/ja/guide/behind-proxies.md +++ b/ja/guide/behind-proxies.md @@ -1,44 +1,44 @@ --- layout: page title: プロキシーの背後の Express +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. menu: guide lang: ja -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. +redirect_from: " " --- # プロキシーの背後の Express -Express アプリケーションをプロキシーの背後で実行する場合、([app.set()](/{{ page.lang }}/4x/api.html#app.set) を使用して) アプリケーション変数 `trust proxy` を次の表にリストされているいずれかの値に設定します。 +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.
    - -アプリケーション変数 `trust proxy` が設定されていない場合でもアプリケーションの実行は失敗しませんが、`trust proxy` が構成されていない限り、プロキシーの IP アドレスを誤ってクライアント 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.
    +The application setting `trust proxy` may be set to one of the values listed in the following table. + - - + - + - +
    真偽値 + Boolean`true` の場合、クライアントの IP アドレスは、`X-Forwarded-*` ヘッダーの左端の項目として理解されます。 -`true` の場合、クライアントの IP アドレスは、`X-Forwarded-*` ヘッダーの左端の項目として理解されます。 - -`false` の場合、アプリケーションはインターネットに直接接続されているものとして理解され、クライアントの IP アドレスは `req.connection.remoteAddress` から導き出されます。これはデフォルトの設定値です。 +`false` の場合、アプリケーションはインターネットに直接接続されているものとして理解され、クライアントの IP アドレスは `req.connection.remoteAddress` から導き出されます。これはデフォルトの設定値です。 This is the default setting. +
    +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. +
    IP アドレス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` +- 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` 以下のどの方法でも IP アドレスを設定できます。 @@ -49,21 +49,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -IP アドレスまたはサブネットは、指定されると、アドレス決定プロセスから除外されます。アプリケーション・サーバーに最も近い信頼できない IP アドレスがクライアントの IP アドレスに決定されます。 +IP アドレスまたはサブネットは、指定されると、アドレス決定プロセスから除外されます。アプリケーション・サーバーに最も近い信頼できない IP アドレスがクライアントの IP アドレスに決定されます。 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. +
    数字 +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. -プロキシー・サーバーから `n` 番目のホップをクライアントとして信頼します。 - +
    +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. +
    関数Function -カスタムの信頼実装。実行内容を理解している場合にのみ、これを使用してください。 +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -80,19 +83,10 @@ app.set('trust proxy', (ip) => { `trust proxy`を有効にすると、次の3つの重要な変更が起こります。
      -
    • - - [req.hostname](/{{ page.lang }}/api.html#req.hostname) の値は、クライアントまたはプロキシーが設定できる `X-Forwarded-Host` ヘッダーに設定された値から導き出されます。 -
    • -
    • - - `X-Forwarded-Proto` は、`https` と `http` のどちらであるか、または無効な名前であるかをアプリケーションに通知するためにリバース・プロキシーによって設定できます。この値は、[req.protocol](/{{ page.lang }}/api.html#req.protocol) に反映されます。 -
    • -
    • - - [req.ip](/{{ page.lang }}/api.html#req.ip) および [req.ips](/{{ page.lang }}/api.html#req.ips) の値は、`X-Forwarded-For` のアドレス・リストから取り込まれます。 +
    • [req.hostname](/{{ page.lang }}/api.html#req.hostname) の値は、クライアントまたはプロキシーが設定できる `X-Forwarded-Host` ヘッダーに設定された値から導き出されます。
    • +
    • `X-Forwarded-Proto` は、`https` と `http` のどちらであるか、または無効な名前であるかをアプリケーションに通知するためにリバース・プロキシーによって設定できます。この値は、[req.protocol](/{{ page.lang }}/api.html#req.protocol) に反映されます。 This value is reflected by [req.protocol](/{{ page.lang }}/api.html#req.protocol).
    • +
    • [req.ip](/{{ page.lang }}/api.html#req.ip) および [req.ips](/{{ page.lang }}/api.html#req.ips) の値は、`X-Forwarded-For` のアドレス・リストから取り込まれます。
    -`trust proxy` 設定は、[proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されます。詳細については、資料を参照してください。 - +`trust proxy` 設定は、[proxy-addr](https://www.npmjs.com/package/proxy-addr) パッケージを使用して実装されます。詳細については、資料を参照してください。 For more information, see its documentation. diff --git a/ja/guide/database-integration.md b/ja/guide/database-integration.md old mode 100755 new mode 100644 index 5b56cfa7bc..fa794833bb --- a/ja/guide/database-integration.md +++ b/ja/guide/database-integration.md @@ -1,41 +1,40 @@ --- layout: page title: Express でのデータベースの統合 +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: ja -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # データベースの統合 -データベースを Express アプリケーションに接続できるようにするには、単にデータベースに適切な Node.js ドライバーをアプリケーションにロードするだけですみます。本書では、データベース・システム用の最も一般的な Node.js モジュールを Express アプリケーションに追加して使用する方法について簡単に説明します。 - -* [Cassandra](#cassandra) -* [Couchbase](#couchbase) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongodb) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgresql) -* [Redis](#redis) -* [SQL Server](#sql-server) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +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: + +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongodb) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgresql) +- [Redis](#redis) +- [SQL Server](#sql-server) +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
    - -上記は、使用可能な多数のデータベース・ドライバーの一部です。その他のオプションについては、[npm](https://www.npmjs.com/) サイトで検索してください。 - +These database drivers are among many that are available. For other options, +search on the [npm](https://www.npmjs.com/) site.
    ## Cassandra **モジュール**: [cassandra-driver](https://github.com/datastax/nodejs-driver) -**インストール** +### **インストール** ```bash $ npm install cassandra-driver @@ -57,7 +56,7 @@ client.execute('select key from system.local', (err, result) => { **Module**: [couchnode](https://github.com/couchbase/couchnode) -### インストール +### **インストール** ```bash $ npm install couchbase @@ -94,7 +93,7 @@ bucket.query(query, [13], (err, result) => { **モジュール**: [nano](https://github.com/dscape/nano) -**インストール** +### **インストール** ```bash $ npm install nano @@ -130,7 +129,7 @@ books.list((err, body) => { **モジュール**: [levelup](https://github.com/rvagg/node-levelup) -### インストール +### **インストール** ```bash $ npm install level levelup leveldown @@ -157,7 +156,7 @@ db.put('name', 'LevelUP', (err) => { **モジュール**: [mysql](https://github.com/felixge/node-mysql/) -### インストール +### **インストール** ```bash $ npm install mysql @@ -189,13 +188,13 @@ connection.end() **モジュール**: [mongodb](https://github.com/mongodb/node-mongodb-native) -**インストール** +### **インストール** ```bash $ npm install mongodb ``` -### 例 (v2.*) +### 例 (v3.\*) ```js const MongoClient = require('mongodb').MongoClient @@ -211,7 +210,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { }) ``` -### 例 (v3.*) +### 例 (v2.\*) ```js const MongoClient = require('mongodb').MongoClient @@ -233,36 +232,40 @@ MongoDB 用のオブジェクト・モデル・ドライバーが必要な場合 ## Neo4j -**モジュール**: [apoc](https://github.com/hacksparrow/apoc) +データベースを Express アプリケーションに接続できるようにするには、単にデータベースに適切な Node.js ドライバーをアプリケーションにロードするだけですみます。本書では、データベース・システム用の最も一般的な Node.js モジュールを Express アプリケーションに追加して使用する方法について簡単に説明します。 -### インストール +### **インストール** ```bash -$ npm install apoc +$ npm install neo4j-driver ``` ### 例 ```js -const apoc = require('apoc') - -apoc.query('match (n) return n').exec().then( - (response) => { - console.log(response) - }, - (fail) => { - console.log(fail) - } -) +const neo4j = require('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) -### インストール +### **インストール** - NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation). +NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation). ```bash $ npm install oracledb @@ -306,7 +309,7 @@ getEmployee(101) **モジュール**: [pg-promise](https://github.com/vitaly-t/pg-promise) -### インストール +### **インストール** ```bash $ npm install pg-promise @@ -331,7 +334,7 @@ db.one('SELECT $1 AS value', 123) **モジュール**: [redis](https://github.com/mranney/node_redis) -### インストール +### **インストール** ```bash $ npm install redis @@ -366,7 +369,7 @@ client.hkeys('hash key', (err, replies) => { **モジュール**: [tedious](https://github.com/tediousjs/tedious) -### インストール +### **インストール** ```bash $ npm install tedious @@ -379,9 +382,14 @@ const Connection = require('tedious').Connection const Request = require('tedious').Request const config = { - userName: 'your_username', // update me - password: 'your_password', // update me - server: 'localhost' + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } } const connection = new Connection(config) @@ -422,7 +430,7 @@ function executeStatement () { **モジュール**: [sqlite3](https://github.com/mapbox/node-sqlite3) -### インストール +### **インストール** ```bash $ npm install sqlite3 @@ -456,7 +464,7 @@ db.close() **モジュール**: [elasticsearch](https://github.com/elastic/elasticsearch-js) -### インストール +### **インストール** ```bash $ npm install elasticsearch diff --git a/ja/guide/debugging.md b/ja/guide/debugging.md old mode 100755 new mode 100644 index a369492ca2..75fb5a7912 --- a/ja/guide/debugging.md +++ b/ja/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Express のデバッグ +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: ja -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # Express のデバッグ @@ -18,7 +18,7 @@ $ DEBUG=express:* node index.js Windows では、対応するコマンドを使用します。 ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` [express ジェネレーター](/{{ page.lang }}/starter/generator.html) で生成されるデフォルトのアプリケーションでこのコマンドを実行すると、以下の出力が表示されます。 @@ -59,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -87,7 +87,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` に設定します。その他についても同様に設定します。 Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on. ## `express` によって生成されるアプリケーション @@ -104,3 +104,27 @@ $ DEBUG=sample-app:* node ./bin/www ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/ja/guide/error-handling.md b/ja/guide/error-handling.md old mode 100755 new mode 100644 index 5198915b15..0dc3546afd --- a/ja/guide/error-handling.md +++ b/ja/guide/error-handling.md @@ -1,21 +1,24 @@ --- layout: page title: Express でのエラー処理 +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: ja -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # エラー処理 -_エラー処理_ は、Expressが同期的および非同期的に発生するエラーをキャッチして処理する方法です。Expressにはデフォルトのエラーハンドラが付属しているので、自分で作成する必要はありません。 +_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はそれをキャッチして処理します。 例えば: +ルート・ハンドラとミドルウェア内の同期コードで発生するエラーは、余分な作業を必要としません。同期コードがエラーをスローすると、Expressはそれをキャッチして処理します。 例えば: If synchronous code throws an error, then Express will +catch and process it. For example: ```js app.get('/', (req, res) => { @@ -23,7 +26,7 @@ app.get('/', (req, res) => { }) ``` -ルート・ハンドラとミドルウェアによって呼び出された非同期関数から返されたエラーについては、それらを`next()`関数に渡す必要があります。ここでExpressはそれらをキャッチして処理します。例えば: +ルート・ハンドラとミドルウェアによって呼び出された非同期関数から返されたエラーについては、それらを`next()`関数に渡す必要があります。ここでExpressはそれらをキャッチして処理します。例えば: For example: ```js app.get('/', (req, res, next) => { @@ -37,6 +40,23 @@ 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: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +`next()` 関数に (ストリング `'route'` を除く) 何らかを渡すと、Express は、現在のリクエストでエラーが発生したと想定して、エラーが発生していない残りのすべての処理のルーティングとミドルウェア関数をスキップします。そのエラーを何らかの方法で渡す場合は、次のセクションで説明するようにエラー処理ルートを作成する必要があります。 + シーケンス内のコールバックにデータがなく、エラーのみが発生する場合は、次のようにこのコードを単純化できます。 ```js @@ -50,9 +70,10 @@ app.get('/', [ ]) ``` -上記の例では`fs.writeFile`のコールバックとして`next`が提供されています。これはエラーの有無にかかわらず呼び出されます。エラーがなければ、2番目のハンドラが実行されます。それ以外の場合、Expressはエラーをキャッチして処理します。 +上記の例では`fs.writeFile`のコールバックとして`next`が提供されています。これはエラーの有無にかかわらず呼び出されます。エラーがなければ、2番目のハンドラが実行されます。それ以外の場合、Expressはエラーをキャッチして処理します。 If there is no error, the second +handler is executed, otherwise Express catches and processes the error. -ルート・ハンドラまたはミドルウェアによって呼び出された非同期コードで発生したエラーをキャッチして、Expressに渡して処理する必要があります。例えば: +ルート・ハンドラまたはミドルウェアによって呼び出された非同期コードで発生したエラーをキャッチして、Expressに渡して処理する必要があります。例えば: For example: ```js app.get('/', (req, res, next) => { @@ -68,7 +89,7 @@ app.get('/', (req, res, next) => { 上記の例では、`try ... catch`ブロックを使用して非同期コードのエラーを捕捉してExpressに渡しています。`try ... catch`ブロックが省略された場合、Expressは同期ハンドラ・コードの一部ではないため、エラーをキャッチしません。 -Promiseを使って`try..catch`ブロックのオーバーヘッドを避けるか、Promiseを返す関数を使うとき。例えば: +Promiseを使って`try..catch`ブロックのオーバーヘッドを避けるか、Promiseを返す関数を使うとき。例えば: For example: ```js app.get('/', (req, res, next) => { @@ -80,12 +101,12 @@ app.get('/', (req, res, next) => { Promiseは自動的に同期エラーと拒否されたPromiseをキャッチするので、catchハンドラに最初の引数としてエラーが与えられ、最終的なcatchハンドラとして`next`を指定するだけで、Expressはエラーをキャッチします。 -また、非同期コードを単純なものに減らすことで、同期エラーのキャッチに依存する一連のハンドラを使用することもできます。例えば: +また、非同期コードを単純なものに減らすことで、同期エラーのキャッチに依存する一連のハンドラを使用することもできます。例えば: For example: ```js app.get('/', [ function (req, res, next) { - fs.readFile('/maybe-valid-file', 'utf8', (err, data) => { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data next(err) }) @@ -97,21 +118,32 @@ app.get('/', [ ]) ``` -上の例は`readFile`呼び出しからの簡単なステートメントをいくつか持っています。`readFile`でエラーが発生した場合、エラーをExpressに渡します。そうでなければ、チェーン内の次のハンドラで同期エラー処理の世界に素早く戻ります。次に、上記の例ではデータを処理しようとしています。これが失敗すると、同期エラーハンドラはそれをキャッチします。 この処理を`readFile`コールバックの中で行った場合、アプリケーションは終了し、Expressのエラーハンドラは実行されません。 +The above example has a couple of trivial statements from the `readFile` +call. 上の例は`readFile`呼び出しからの簡単なステートメントをいくつか持っています。`readFile`でエラーが発生した場合、エラーをExpressに渡します。そうでなければ、チェーン内の次のハンドラで同期エラー処理の世界に素早く戻ります。次に、上記の例ではデータを処理しようとしています。これが失敗すると、同期エラーハンドラはそれをキャッチします。 この処理を`readFile`コールバックの中で行った場合、アプリケーションは終了し、Expressのエラーハンドラは実行されません。 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. どちらの方法を使用しても、Expressのエラーハンドラを呼び出す場合や、アプリケーションを存続させる場合は、Expressがエラーを受け取るようにする必要があります。 ## デフォルトのエラー処理 -Expressには、アプリケーションで発生する可能性のあるエラーを処理するビルトインエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの最後に追加されます。 +Expressには、アプリケーションで発生する可能性のあるエラーを処理するビルトインエラーハンドラが付属しています。 このデフォルトのエラー処理ミドルウェア関数は、ミドルウェア関数スタックの最後に追加されます。 This default error-handling middleware function is added at the end of the middleware function stack. -`next()`にエラーを渡し、カスタムエラーハンドラでそれを処理しない場合、それは組み込みのエラーハンドラによって処理されます。エラーはスタックトレースを使用してクライアントに書き込まれます。スタックトレースは本番環境には含まれていません。 +`next()`にエラーを渡し、カスタムエラーハンドラでそれを処理しない場合、それは組み込みのエラーハンドラによって処理されます。エラーはスタックトレースを使用してクライアントに書き込まれます。スタックトレースは本番環境には含まれていません。 The stack trace is not included +in the production environment. -
    +
    プロダクションモードでアプリケーションを実行するには、環境変数`NODE_ENV`を` production`に設定します。
    -プロダクションモードでアプリケーションを実行するには、環境変数`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. レスポンスの記述を開始した後でエラーを伴って`next()`を呼び出すと(例えば、クライアントへの応答をストリーミング中にエラーが発生した場合)、Expressのデフォルトエラーハンドラは接続を閉じてリクエストを失敗します。 @@ -129,9 +161,11 @@ function errorHandler (err, req, res, next) { カスタムエラー処理ミドルウェアが存在していても、コード内でエラーが2回以上発生したときに`next()`を呼び出すと、デフォルトのエラーハンドラがトリガされることに注意してください。 +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + ## エラー処理を記述する -エラー処理ミドルウェア関数は、その他のミドルウェア関数と同じ方法で定義しますが、エラー処理関数の引数が3つではなく、4つ `(err、req、res、next)` であることが例外です。次に例を示します。 +エラー処理ミドルウェア関数は、その他のミドルウェア関数と同じ方法で定義しますが、エラー処理関数の引数が3つではなく、4つ `(err、req、res、next)` であることが例外です。次に例を示します。 For example: ```js app.use((err, req, res, next) => { @@ -158,7 +192,8 @@ app.use((err, req, res, next) => { ミドルウェア関数の中からの応答は、HTML エラー・ページ、単純なメッセージ、または JSON ストリングなど、任意の形式にすることができます。 -組織的な (および高水準フレームワークの) 目的で、通常のミドルウェア関数と同じように、複数のエラー処理のミドルウェア関数を定義できます。例えば、`XHR` を使用する要求と、使用しない要求のためのエラー・ハンドラーを定義するには、以下のコマンドを使用します。 +組織的な (および高水準フレームワークの) 目的で、通常のミドルウェア関数と同じように、複数のエラー処理のミドルウェア関数を定義できます。例えば、`XHR` を使用する要求と、使用しない要求のためのエラー・ハンドラーを定義するには、以下のコマンドを使用します。 For example, to define an error-handler +for requests made by using `XHR` and those without: ```js const bodyParser = require('body-parser') @@ -185,7 +220,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) { @@ -206,9 +241,7 @@ function errorHandler (err, req, res, next) { } ``` -`next()` 関数に (ストリング `'route'` を除く) 何らかを渡すと、Express は、現在のリクエストでエラーが発生したと想定して、エラーが発生していない残りのすべての処理のルーティングとミドルウェア関数をスキップします。そのエラーを何らかの方法で渡す場合は、次のセクションで説明するようにエラー処理ルートを作成する必要があります。 - -複数のコールバック関数を使用するルート・ハンドラーがある場合、`route` パラメーターを使用して、次のルート・ハンドラーまでスキップできます。次に例を示します。 +複数のコールバック関数を使用するルート・ハンドラーがある場合、`route` パラメーターを使用して、次のルート・ハンドラーまでスキップできます。次に例を示します。 For example: ```js app.get('/a_route_behind_paywall', @@ -230,7 +263,5 @@ app.get('/a_route_behind_paywall', この例では、`getPaidContent` ハンドラーはスキップされますが、`/a_route_behind_paywall` の `app` にある残りのハンドラーはすべて引き続き実行されます。
    - -`next()` および `next(err)` の呼び出しは、現在のハンドラーが完了したことと、その状態を示します。`next(err)` は、上記のようにエラーを処理するようにセットアップされたハンドラーを除き、チェーン内の残りのハンドラーをすべてスキップします。 - +Calls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next()` および `next(err)` の呼び出しは、現在のハンドラーが完了したことと、その状態を示します。`next(err)` は、上記のようにエラーを処理するようにセットアップされたハンドラーを除き、チェーン内の残りのハンドラーをすべてスキップします。
    diff --git a/ja/guide/migrating-4.md b/ja/guide/migrating-4.md old mode 100755 new mode 100644 index 856e718198..ced9f8049c --- a/ja/guide/migrating-4.md +++ b/ja/guide/migrating-4.md @@ -1,17 +1,17 @@ --- layout: page title: 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. menu: guide lang: ja -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. +redirect_from: " " --- # Express 4 への移行

    概説

    -Express 4 では、Express 3 とは互換性の _ない_ 変更が行われています。つまり、依存関係にある Express のバージョンを更新すると、既存の Express 3 アプリケーションは機能しません。 +Express 4 では、Express 3 とは互換性の _ない_ 変更が行われています。つまり、依存関係にある Express のバージョンを更新すると、既存の Express 3 アプリケーションは機能しません。 That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies. この記事では以下の内容を扱います。 @@ -26,23 +26,26 @@ Express 4 では、Express 3 とは互換性の _ない_ 変更が行われて Express 4 では、いくつかの大きな変更が行われています。 以下も参照してください。 -* [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) +- [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)

    Express コアおよびミドルウェア・システムの変更

    -Express 4 は、Connect に依存しなくなり、`express.static` 関数を除くすべての標準装備ミドルウェアをコアから削除しました。つまり、Express は独立したルーティングおよびミドルウェアの Web フレームワークになり、Express のバージョン管理とリリースはミドルウェア更新の影響を受けません。 +Express 4 は、Connect に依存しなくなり、`express.static` 関数を除くすべての標準装備ミドルウェアをコアから削除しました。つまり、Express は独立したルーティングおよびミドルウェアの Web フレームワークになり、Express のバージョン管理とリリースはミドルウェア更新の影響を受けません。 This means that +Express is now an independent routing and middleware web framework, and +Express versioning and releases are not affected by middleware updates. -標準装備ミドルウェアがないため、アプリケーションの実行に必要なすべてのミドルウェアを明示的に追加する必要があります。そのためには、単に以下のステップを実行してください。 +標準装備ミドルウェアがないため、アプリケーションの実行に必要なすべてのミドルウェアを明示的に追加する必要があります。そのためには、単に以下のステップを実行してください。 Simply follow these steps: 1. モジュールをインストールします。`npm install --save ` 2. アプリケーションでモジュールを要求します。`require('module-name')` @@ -51,7 +54,7 @@ Express 4 は、Connect に依存しなくなり、`express.static` 関数を除 次の表に、Express 3 のミドルウェアと、それぞれに対応する Express 4 のミドルウェアをリストします。 - + @@ -83,16 +86,18 @@ Express 4 は、Connect に依存しなくなり、`express.static` 関数を除 -
    Express 3Express 4
    Express 3Express 4
    express.bodyParser body-parser + multer
    serve-index
    express.static serve-static
    +
    Express 4 のミドルウェアの完全なリストは、[ここ](https://github.com/senchalabs/connect#middleware)を参照してください。 -ほとんどの場合、旧バージョン 3 のミドルウェアを単に Express 4 のミドルウェアに置き換えるだけですみます。詳細については、GitHub でモジュールの資料を参照してください。 +ほとんどの場合、旧バージョン 3 のミドルウェアを単に Express 4 のミドルウェアに置き換えるだけですみます。詳細については、GitHub でモジュールの資料を参照してください。 For details, see the module documentation in +GitHub.

    app.use がパラメーターを受け入れます

    バージョン 4 では、変数パラメーターを使用して、ミドルウェア関数がロードされるパスを定義し、ルート・ハンドラーからパラメーターの値を読み取ることができます。 次に例を示します。 +For example: ```js app.use('/book/:id', (req, res, next) => { @@ -100,6 +105,7 @@ app.use('/book/:id', (req, res, next) => { next() }) ``` +

    ルーティング・システム

    @@ -109,12 +115,14 @@ app.use('/book/:id', (req, res, next) => { ルートの定義方法は変わりませんが、ルーティング・システムには、ルートの編成に役立つ 2 つの新機能があります。 {: .doclist } -* 新しいメソッド `app.route()` は、ルート・パスのチェーン可能なルート・ハンドラーを作成します。 -* 新しいクラス `express.Router` は、モジュール式のマウント可能なルート・ハンドラーを作成します。 + +- 新しいメソッド `app.route()` は、ルート・パスのチェーン可能なルート・ハンドラーを作成します。 +- 新しいクラス `express.Router` は、モジュール式のマウント可能なルート・ハンドラーを作成します。

    app.route() メソッド

    -新しい `app.route()` メソッドを使用すると、ルート・パスのチェーン可能なルート・ハンドラーを作成できます。パスは単一の場所で指定されるため、モジュール式のルートを作成すると、便利であるほか、冗長性とタイプミスを減らすことができます。ルートについて詳しくは、[`Router()` 資料](/{{ page.lang }}/4x/api.html#router)を参照してください。 +新しい `app.route()` メソッドを使用すると、ルート・パスのチェーン可能なルート・ハンドラーを作成できます。パスは単一の場所で指定されるため、モジュール式のルートを作成すると、便利であるほか、冗長性とタイプミスを減らすことができます。ルートについて詳しくは、[`Router()` 資料](/{{ page.lang }}/4x/api.html#router)を参照してください。 Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more +information about routes, see [`Router()` documentation](/{{ page.lang }}/4x/api.html#router). 次に、`app.route()` 関数を使用して定義された、チェーニングされたルート・ハンドラーの例を示します。 @@ -133,7 +141,8 @@ app.route('/book')

    express.Router クラス

    -ルートの編成に役立つもう 1 つの機能は、新しいクラス `express.Router` です。これを使用すると、モジュール式のマウント可能なルート・ハンドラーを作成できます。`Router` インスタンスは、完全なミドルウェアおよびルーティング・システムです。そのため、よく「ミニアプリケーション」と呼ばれます。 +ルートの編成に役立つもう 1 つの機能は、新しいクラス `express.Router` です。これを使用すると、モジュール式のマウント可能なルート・ハンドラーを作成できます。`Router` インスタンスは、完全なミドルウェアおよびルーティング・システムです。そのため、よく「ミニアプリケーション」と呼ばれます。 A `Router` instance is a complete middleware and +routing system; for this reason it is often referred to as a "mini-app". 次の例では、ルーターをモジュールとして作成し、その中にミドルウェアをロードして、いくつかのルートを定義し、それをメインアプリケーションのパスにマウントします。 @@ -179,7 +188,7 @@ app.use('/birds', birds) 次の表に、Express 4 におけるその他の小規模ながらも重要な変更点をリストします。 - + @@ -192,7 +201,10 @@ app.use('/birds', birds) `http.createServer()` @@ -200,7 +212,9 @@ app.use('/birds', birds) `app.configure()` @@ -280,15 +294,18 @@ app.use('/birds', birds) `res.setHeader('Set-Cookie', val)` -
    オブジェクト 説明
    + `http` モジュールは、このモジュールを直接処理する必要がある場合を除き、不要になりました (socket.io/SPDY/HTTPS)。アプリケーションは、`app.listen()` 関数を使用して開始できます。 + The app can be started by using the +`app.listen()` function.
    +The `app.configure()` function has been removed. `app.configure()` 関数は削除されました。環境を検出して、アプリケーションを適宜に構成するには、`process.env.NODE_ENV` 関数または `app.get('env')` 関数を使用してください。 +
    +Functionality is now limited to setting the basic cookie value. 機能が基本的な Cookie 値の設定に限定されるようになりました。機能を追加するには、`res.cookie()` を使用してください。 +
    +

    移行の例

    次に、Express 3 アプリケーションを Express 4 に移行する例を示します。 使用しているファイルは、`app.js` および `package.json` です。 +The files of interest are `app.js` and `package.json`.

    バージョン 3 アプリケーション @@ -363,9 +380,11 @@ $ npm install serve-favicon morgan method-override express-session body-parser m `app.js` に以下の変更を加えます。 -1. 標準装備の Express ミドルウェア関数 `express.favicon`、`express.logger`、`express.methodOverride`、`express.session`、`express.bodyParser`、および `express.errorHandler` は `express` オブジェクトで使用できなくなりました。代わりの関数を手動でインストールして、アプリケーションにロードする必要があります。 +1. 標準装備の Express ミドルウェア関数 `express.favicon`、`express.logger`、`express.methodOverride`、`express.session`、`express.bodyParser`、および `express.errorHandler` は `express` オブジェクトで使用できなくなりました。代わりの関数を手動でインストールして、アプリケーションにロードする必要があります。 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. + `app.router` 関数をロードする必要がなくなりました。この関数は有効な Express 4 アプリケーション・オブジェクトではないため、`app.use(app.router);` コードを削除してください。 3. ミドルウェア関数が正しい順序でロードされていることを確認してください。つまり、アプリケーション・ルートをロードした後で `errorHandler` をロードしてください。 @@ -399,7 +418,8 @@ $ 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 var http = require('http') @@ -449,9 +469,7 @@ server.listen(app.get('port'), () => { }) ``` -
    - -`http` モジュール (socket.io/SPDY/HTTPS) を直接処理する必要がある場合を除き、このモジュールをロードする必要はありません。次のようにして、アプリケーションを簡単に開始できます。 +
    `http` モジュール (socket.io/SPDY/HTTPS) を直接処理する必要がある場合を除き、このモジュールをロードする必要はありません。次のようにして、アプリケーションを簡単に開始できます。 ```js app.listen(app.get('port'), () => { @@ -459,9 +477,11 @@ app.listen(app.get('port'), () => { }) ``` +
    +

    アプリケーションの実行

    -これで移行プロセスは完了して、アプリケーションは Express 4 アプリケーションになりました。確認するには、次のコマンドを使用してアプリケーションを開始します。 +これで移行プロセスは完了して、アプリケーションは Express 4 アプリケーションになりました。確認するには、次のコマンドを使用してアプリケーションを開始します。 To confirm, start the app by using the following command: ```bash $ node . @@ -498,9 +518,10 @@ $ npm install -g express-generator コマンドのオプションと使用法の大部分は以前と同じですが、以下の例外があります。 {: .doclist } -* `--sessions` オプションを削除しました。 -* `--jshtml` オプションを削除しました。 -* [Hogan.js](http://twitter.github.io/hogan.js/) をサポートするために `--hogan` オプションを追加しました。 + +- `--sessions` オプションを削除しました。 +- `--jshtml` オプションを削除しました。 +- [Hogan.js](http://twitter.github.io/hogan.js/) をサポートするために `--hogan` オプションを追加しました。

    @@ -522,9 +543,13 @@ $ npm start `package.json` ファイルで npm start スクリプトを見ると、アプリケーションを開始する実際のコマンドは `node ./bin/www` であることが分かります。これは、Express 3 では `node app.js` でした。 -Express 4 ジェネレーターによって生成される `app.js` ファイルが Node.js モジュールになったため、(コードを変更しない限り) アプリケーションとして単独では開始できなくなりました。モジュールを Node.js ファイルにロードして、Node.js ファイルから開始する必要があります。この場合、Node.js ファイルは `./bin/www` です。 +Express 4 ジェネレーターによって生成される `app.js` ファイルが Node.js モジュールになったため、(コードを変更しない限り) アプリケーションとして単独では開始できなくなりました。モジュールを Node.js ファイルにロードして、Node.js ファイルから開始する必要があります。この場合、Node.js ファイルは `./bin/www` です。 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 アプリケーションの作成またはアプリケーションの開始のために、`bin` ディレクトリーも、拡張子のない `www` ファイルも必須ではありません。これらは単にジェネレーターが推奨するものであるため、ニーズに合わせて自由に変更してください。 +Express アプリケーションの作成またはアプリケーションの開始のために、`bin` ディレクトリーも、拡張子のない `www` ファイルも必須ではありません。これらは単にジェネレーターが推奨するものであるため、ニーズに合わせて自由に変更してください。 They are +just suggestions made by the generator, so feel free to modify them to suit your +needs. `www` ディレクトリーを削除して、処理を「Express 3 の方法」で実行するには、`app.js` ファイルの最後にある `module.exports = app;` という行を削除して、その場所に以下のコードを貼り付けます。 @@ -544,4 +569,5 @@ var debug = require('debug')('app4') 次に、`package.json` ファイル内の `"start": "node ./bin/www"` を `"start": "node app.js"` に変更します。 -これで、`./bin/www` の機能を `app.js` に戻しました。この変更は推奨されるものではありませんが、この演習により、`./bin/www` ファイルの仕組みと、`app.js` ファイルが単独で開始されなくなった理由を理解できます。 +You have now moved the functionality of `./bin/www` back to +`app.js`. これで、`./bin/www` の機能を `app.js` に戻しました。この変更は推奨されるものではありませんが、この演習により、`./bin/www` ファイルの仕組みと、`app.js` ファイルが単独で開始されなくなった理由を理解できます。 diff --git a/ja/guide/migrating-5.md b/ja/guide/migrating-5.md old mode 100755 new mode 100644 index 8386da9e24..2128071d9f --- a/ja/guide/migrating-5.md +++ b/ja/guide/migrating-5.md @@ -1,32 +1,45 @@ --- layout: page title: Express 5 への移行 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: ja -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # Express 5 への移行

    概説

    -Express 5.0 は、まだアルファ・リリースの段階ですが、ここでは本リリースにおける変更のプレビューを示し、Express 4 アプリケーションを Express 5 に移行する方法を説明します。 +Express 5 は Express 4 とあまり変わりません。API の変更は、3.0 から 4.0 への変更ほど大きいものではありません。基本的な API は同じままですが、それでも互換性のない変更が行われています。つまり、Express 5 を使用するように既存の Express 4 を更新すると、機能しなくなる可能性があります。 Therefore, an application built with Express 4 might not work if you update it to use Express 5. -Express 5 は Express 4 とあまり変わりません。API の変更は、3.0 から 4.0 への変更ほど大きいものではありません。基本的な API は同じままですが、それでも互換性のない変更が行われています。つまり、Express 5 を使用するように既存の Express 4 を更新すると、機能しなくなる可能性があります。 +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -最新のアルファをインストールして Express 5 をプレビューするには、アプリケーションのルート・ディレクトリーで次のコマンドを入力します。 +```sh +npm install "express@5" +``` + +その後、自動テストを実行して、どの機能が失敗するかを確認し、下記の更新に従って問題を修正することができます。テストの失敗に対応した後、アプリケーションを実行して、どのようなエラーが発生するかを確認します。サポートされていないメソッドまたはプロパティーをアプリケーションが使用している場合は、すぐに判明します。 After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported. + +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: -```bash -$ npm install "express@5" --save +```sh +npx @expressjs/codemod upgrade ``` -その後、自動テストを実行して、どの機能が失敗するかを確認し、下記の更新に従って問題を修正することができます。テストの失敗に対応した後、アプリケーションを実行して、どのようなエラーが発生するかを確認します。サポートされていないメソッドまたはプロパティーをアプリケーションが使用している場合は、すぐに判明します。 +If you want to run a specific codemod, you can run the following command: -

    Express 5 における変更点

    +```sh +npx @expressjs/codemod name-of-the-codemod +``` -次に、Express のユーザーに影響を与える (アルファ 2 リリースの時点での) 変更のリストを示します。 -予定されているすべての機能のリストについては、[プル要求](https://github.com/expressjs/express/pull/2237)を参照してください。 +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

    Express 5 における変更点

    **削除されたメソッドとプロパティー** @@ -38,96 +51,455 @@ $ npm install "express@5" --save
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
  • -**変更** +**改善** -**改善** +**変更** -

    削除されたメソッドとプロパティー

    +### 削除されたメソッドとプロパティー -アプリケーションで以下のいずれかのメソッドまたはプロパティーを使用すると、異常終了します。そのため、バージョン 5 に更新した後で、アプリケーションを変更する必要があります。 +If you use any of these methods or properties in your app, it will crash. アプリケーションで以下のいずれかのメソッドまたはプロパティーを使用すると、異常終了します。そのため、バージョン 5 に更新した後で、アプリケーションを変更する必要があります。

    app.del()

    -Express 5 は、`app.del()` 関数をサポートしなくなりました。この関数を使用すると、エラーがスローされます。HTTP DELETE ルートを登録するには、代わりに `app.delete()` 関数を使用してください。 +Express 5 は、`app.del()` 関数をサポートしなくなりました。この関数を使用すると、エラーがスローされます。HTTP DELETE ルートを登録するには、代わりに `app.delete()` 関数を使用してください。 If you use this function, an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead. + +最初は `del` が `delete` の代わりに使用されていました。`delete` は、JavaScript で予約されているキーワードであるためです。しかし、ECMAScript 6 以降では、`delete` およびその他の予約済みキーワードを正式にプロパティー名として使用できます。ここで、`app.del` 関数の非推奨につながった議論を読むことができます。 However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` -最初は `del` が `delete` の代わりに使用されていました。`delete` は、JavaScript で予約されているキーワードであるためです。しかし、ECMAScript 6 以降では、`delete` およびその他の予約済みキーワードを正式にプロパティー名として使用できます。ここで、`app.del` 関数の非推奨につながった議論を読むことができます。 +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

    app.param(fn)

    -`app.param(fn)` シグニチャーは、`app.param(name, fn)` 関数の動作を変更するために使用されていました。v4.11.0 以降では非推奨になったため、Express 5 は完全にサポートしなくなりました。 +`app.param(fn)` シグニチャーは、`app.param(name, fn)` 関数の動作を変更するために使用されていました。v4.11.0 以降では非推奨になったため、Express 5 は完全にサポートしなくなりました。 It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.

    メソッド名の複数化

    -以下のメソッド名は複数形になりました。Express 4 では、以前のメソッドを使用すると、非推奨の警告が出されていました。Express 5 では、完全にサポートされなくなりました。 +The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all: + +`req.acceptsLanguage()` は `req.acceptsLanguages()` に置き換えられます。 `req.acceptsCharset()` は `req.acceptsCharsets()` に置き換えられます。 `req.acceptsEncoding()` は `req.acceptsEncodings()` に置き換えられます。 -`req.acceptsLanguage()` は `req.acceptsLanguages()` に置き換えられます。 +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    app.param(name, fn) の name の先頭コロン (:)

    -`app.param(name, fn)` 関数の name の先頭コロン文字 (:) は、Express 3 の残余物であり、Express 4 では後方互換性のためにサポートされていましたが、非推奨の通知が出されてました。Express 5 では、サイレントに無視して、先頭にコロンを付けない name パラメーターを使用します。 +`app.param(name, fn)` 関数の name の先頭コロン文字 (:) は、Express 3 の残余物であり、Express 4 では後方互換性のためにサポートされていましたが、非推奨の通知が出されてました。Express 5 では、サイレントに無視して、先頭にコロンを付けない name パラメーターを使用します。 Express 5 will silently ignore it and use the name parameter without prefixing it with a colon. [app.param](/{{ page.lang }}/4x/api.html#app.param) に関する Express 4 の資料では、先頭のコロンについて言及していないため、この資料に従う場合には、コードに影響は及ばないはずです。

    req.param(name)

    -この混乱を招く可能性がある危険なメソッドは、フォーム・データを取得するためのものでしたが、削除されました。今後は、実行依頼されたパラメーター名を `req.params`、`req.body`、または `req.query` オブジェクトで具体的に見つける必要があります。 +This potentially confusing and dangerous method of retrieving form data has been removed. この混乱を招く可能性がある危険なメソッドは、フォーム・データを取得するためのものでしたが、削除されました。今後は、実行依頼されたパラメーター名を `req.params`、`req.body`、または `req.query` オブジェクトで具体的に見つける必要があります。 + +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +```

    res.json(obj, status)

    -Express 5 は、シグニチャー `res.json(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).json(obj)` のように `res.json()` メソッドにチェーニングします。 +Express 5 は、シグニチャー `res.json(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).json(obj)` のように `res.json()` メソッドにチェーニングします。 Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +```

    res.jsonp(obj, status)

    -Express 5 は、シグニチャー `res.jsonp(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).jsonp(obj)` のように `res.jsonp()` メソッドにチェーニングします。 +Express 5 は、シグニチャー `res.jsonp(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).jsonp(obj)` のように `res.jsonp()` メソッドにチェーニングします。 Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    + +Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +```

    res.send(body, status)

    -Express 5 は、シグニチャー `res.send(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).send(obj)` のように `res.send()` メソッドにチェーニングします。 +Express 5 は、シグニチャー `res.send(obj, status)` をサポートしなくなりました。代わりに、状況を設定してから、`res.status(status).send(obj)` のように `res.send()` メソッドにチェーニングします。 Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +```

    res.send(status)

    -Express 5 は、シグニチャー res.send(status) をサポートしなくなりました。ここで、*`status`* は数値です。代わりに、`res.sendStatus(statusCode)` 関数を使用します。この関数は、HTTP 応答ヘッダーの状況コードを設定して、コードのテキスト版 (「Not Found」、「Internal Server Error」など) を送信します。 -`res.send()` 関数を使用して数値を送信する必要がある場合は、数値を引用してストリングに変換し、Express によって、サポートされない以前のシグニチャーを使用しようとしていると解釈されないようにします。 +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. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +```

    res.sendfile()

    `res.sendfile()` 関数は、Express 5 ではキャメルケース版の `res.sendFile()` に置き換えられます。 +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. + +

    express.static.mime

    + +In Express 5, `mime` is no longer an exported property of the `static` field. +Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    変更

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. For example: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +For example: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    -`app.router` オブジェクトは、Express 4 で削除されましたが、Express 5 で復帰しました。アプリケーションが明示的にロードする必要があった Express 3 とは異なり、新しいバージョンでは、このオブジェクトは基本の Express ルーターの単なる参照です。 +`app.router` オブジェクトは、Express 4 で削除されましたが、Express 5 で復帰しました。アプリケーションが明示的にロードする必要があった Express 3 とは異なり、新しいバージョンでは、このオブジェクトは基本の Express ルーターの単なる参照です。 In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it. + +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default.

    req.host

    -Express 4 では、`req.host` 関数は、ポート番号が存在する場合に、ポート番号を誤って削除していました。Express 5 では、ポート番号は維持されます。 +Express 4 では、`req.host` 関数は、ポート番号が存在する場合に、ポート番号を誤って削除していました。Express 5 では、ポート番号は維持されます。 In Express 5, the port number is maintained.

    req.query

    -Express 4.7 および Express 5 以降では、照会ストリング解析ロジックで独自の関数を使用する場合に、照会パーサー・オプションは `false` を受け入れて、照会ストリングの解析を無効にすることができます。 +The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from "extended" to "simple". -

    改善

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### 改善

    res.render()

    このメソッドは、すべてのビュー・エンジンに非同期動作を適用するようになり、同期実装を使用して推奨インターフェースに違反していたビュー・エンジンに起因するバグを回避します。 + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/ja/guide/overriding-express-api.md b/ja/guide/overriding-express-api.md new file mode 100644 index 0000000000..3c43815e2f --- /dev/null +++ b/ja/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: ja +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/ja/guide/routing.md b/ja/guide/routing.md old mode 100755 new mode 100644 index 9d42f78f6f..c4a4dd149a --- a/ja/guide/routing.md +++ b/ja/guide/routing.md @@ -1,23 +1,26 @@ --- layout: page title: Express でのルーティング +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: ja -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # ルーティング -*ルーティング* とは、アプリケーション・エンドポイント (URI) と、クライアントリクエストに対するそれらのレスポンスの定義のことです。 -ルーティングの概要については、[基本的なルーティング](/{{ page.lang }}/starter/basic-routing.html)を参照してください。 +_Routing_ refers to how an application's endpoints (URIs) respond to client requests. +For an introduction to routing, see [Basic routing](/{{ page.lang }}/starter/basic-routing.html). ルーティングはHTTPメソッドに対応するExpressの`app`オブジェクトのメソッドを使用して定義します。たとえば、GETリクエストを処理する`app.get()`やPOSTリクエストを処理する`app.post`があります。 完全なリストについては、[app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD)を参照してください。 -また、すべてのHTTPメソッドを制御するために[app.all()](/{{ page.lang }}/4x/api.html#app.all)を、ミドルウェアを指定するために[app.use()](/{{ page.lang }}/4x/api.html#app.use)をコールバック関数として使用することができます(詳細については、[Using middleware](/{{ page.lang }}/guide/using-middleware.html)を参照してください)。 +また、すべてのHTTPメソッドを制御するために[app.all()](/{{ page.lang }}/4x/api.html#app.all)を、ミドルウェアを指定するために[app.use()](/{{ page.lang }}/4x/api.html#app.use)をコールバック関数として使用することができます(詳細については、[Using middleware](/{{ page.lang }}/guide/using-middleware.html)を参照してください)。 For a full list, +see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) for details). -これらのルーティングメソッドは、アプリケーションが指定されたルート(エンドポイント)とHTTPメソッドへのリクエストを受け取ったときに呼び出されるコールバック関数(ハンドラ関数とも呼ばれます)を指定します。 つまり、アプリケーションは指定されたルートとメソッドに一致するリクエストをリッスンし、一致を検出すると指定されたコールバック関数を呼び出します。 +これらのルーティングメソッドは、アプリケーションが指定されたルート(エンドポイント)とHTTPメソッドへのリクエストを受け取ったときに呼び出されるコールバック関数(ハンドラ関数とも呼ばれます)を指定します。 つまり、アプリケーションは指定されたルートとメソッドに一致するリクエストをリッスンし、一致を検出すると指定されたコールバック関数を呼び出します。 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. 実際、ルーティングメソッドは複数のコールバック関数を引数として持つことができます。 複数のコールバック関数では、コールバック関数に引数として`next`を指定し、次のコールバックに制御を渡す関数の本体内で`next()`を呼び出すことが重要です。 @@ -53,8 +56,9 @@ app.post('/', (req, res) => { Expressは、すべてのHTTPリクエストメソッドに対応するメソッド(`get`、`post`など)をサポートしています。 完全なリストについては、[app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD)を参照して下さい。 +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -_すべての_ HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用される特別なルーティングメソッド、`app.all()`があります。 たとえば、GET、POST、PUT、DELETE、または[httpモジュール](https://nodejs.org/api/http.html#http_http_methods)でサポートされているその他のHTTPリクエストメソッドを使用するかどうかにかかわらず、"/secret"ルートへのリクエストに対して次のハンドラが実行されます。 +_すべての_ HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用される特別なルーティングメソッド、`app.all()`があります。 たとえば、GET、POST、PUT、DELETE、または[httpモジュール](https://nodejs.org/api/http.html#http_http_methods)でサポートされているその他のHTTPリクエストメソッドを使用するかどうかにかかわらず、"/secret"ルートへのリクエストに対して次のハンドラが実行されます。 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) => { @@ -65,21 +69,34 @@ app.all('/secret', (req, res, next) => {

    ルート・パス

    -ルート・パスは、リクエストメソッドとの組み合わせにより、リクエストを実行できるエンドポイントを定義します。ルート・パスは、ストリング、ストリング・パターン、または正規表現にすることができます。 +ルート・パスは、リクエストメソッドとの組み合わせにより、リクエストを実行できるエンドポイントを定義します。ルート・パスは、ストリング、ストリング・パターン、または正規表現にすることができます。 Route paths can be strings, string patterns, or regular expressions. -文字`?`、`+`、`*`、`()`は正規表現の部分集合です。 ハイフン(`-`)とドット(`.`)は、文字列ベースのパスによって文字通り解釈されます。 +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -パス文字列でドル文字(`$`)を使用する必要がある場合は、`([`と`])`の中にエスケープして囲みます。たとえば、"/data/$book"でのリクエストのパス文字列は"`/data /([\$])book`"となります。 +{% include admonitions/caution.html content=caution-character %} -
    -Express は、ルート・パスのマッチングに [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) を使用します。ルート・パスの定義におけるすべての可能性については、path-to-regexp 資料を参照してください。[Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) は、パターン・マッチングをサポートしていませんが、基本的な Express ルートをテストするための便利なツールです。 -
    +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} -
    -クエリ文字列は、ルート・パスの一部ではありません。 -
    +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. -次に、ストリングに基づくルート・パスの例を示します。 +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### 次に、ストリングに基づくルート・パスの例を示します。 このルート・パスは、リクエストをルートのルート `/` にマッチングします。 @@ -105,7 +122,11 @@ app.get('/random.text', (req, res) => { }) ``` -次に、ストリング・パターンに基づくルート・パスの例を示します。 +### 次に、ストリング・パターンに基づくルート・パスの例を示します。 + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} このルート・パスは、`acd` および `abcd` をマッチングします。 @@ -139,7 +160,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -次に、正規表現に基づくルート・パスの例を示します。 +### 次に、正規表現に基づくルート・パスの例を示します。 このルート・パスは、ルート名に「a」が含まれるすべてのものをマッチングします。 @@ -157,13 +178,13 @@ app.get(/.*fly$/, (req, res) => { }) ``` -

    ルート・パラメータ

    +

    ルート・パラメータ

    -ルート・パラメータは、URL内の指定された値を取得するために使用されるURLセグメントのことを言います。捕捉された値は`req.params`オブジェクトの中で、パスに指定されたルート・パラメータの名前をそれぞれのキーとして設定されます。 +Route parameters are named URL segments that are used to capture the values specified at their position in the URL. ルート・パラメータは、URL内の指定された値を取得するために使用されるURLセグメントのことを言います。捕捉された値は`req.params`オブジェクトの中で、パスに指定されたルート・パラメータの名前をそれぞれのキーとして設定されます。 ``` -ルート・パス: /users/:userId/books/:bookId -リクエストURL: http://localhost:3000/users/34/books/8989 +Route path: /users/:userId/books/:bookId +Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" } ``` @@ -182,40 +203,53 @@ app.get('/users/:userId/books/:bookId', (req, res) => { ハイフン(`-`)とドット(`.`)は文字通りに解釈されるので、有用な目的のためにルート・パラメータとともに使用することができます。 ``` -ルート・パス: /flights/:from-:to -リクエストURL: http://localhost:3000/flights/LAX-SFO +Route path: /flights/:from-:to +Request URL: http://localhost:3000/flights/LAX-SFO req.params: { "from": "LAX", "to": "SFO" } ``` ``` -ルート・パス: /plantae/:genus.:species -リクエストURL: http://localhost:3000/plantae/Prunus.persica +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica req.params: { "genus": "Prunus", "species": "persica" } ``` +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + ルート・パラメータで一致させることができる正確な文字列をより詳細に制御するために、括弧(`()`)内で正規表現を追加できます: ``` -ルート・パス: /user/:userId(\d+) -リクエストURL: http://localhost:3000/user/42 +Route path: /user/:userId(\d+) +Request URL: http://localhost:3000/user/42 req.params: {"userId": "42"} ``` -
    -正規表現は通常リテラル文字列の一部なので、\\d+のように\文字をバックスラッシュでエスケープしてください。 -
    +{% capture escape-advisory %} -
    -Express 4.xでは、正規表現の*文字は通常の方法で解釈されません。回避策として、*の代わりに{0,}を使用してください。これは、Express 5で修正される可能性があります。 -
    +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %}

    ルート・ハンドラー

    -リクエストを処理するために、[ミドルウェア](/{{ page.lang }}/guide/using-middleware.html)のように動作する複数のコールバック関数を指定できます。唯一の例外は、これらのコールバックが `next('route')` を呼び出して、残りのルート・コールバックをバイパスすることです。このメカニズムを使用して、ルートに事前条件を適用し、現在のルートで続行する理由がない場合に後続のルートに制御を渡すことができます。 +リクエストを処理するために、[ミドルウェア](/{{ page.lang }}/guide/using-middleware.html)のように動作する複数のコールバック関数を指定できます。唯一の例外は、これらのコールバックが `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. 次の例に示すように、ルート・ハンドラーの形式は、関数、関数の配列、または両方の組み合わせにすることができます。 -単一のコールバック関数で 1 つのルートを処理できます。次に例を示します。 +単一のコールバック関数で 1 つのルートを処理できます。次に例を示します。 For example: ```js app.get('/example/a', (req, res) => { @@ -223,7 +257,7 @@ app.get('/example/a', (req, res) => { }) ``` -複数のコールバック関数で1つのルートを処理できます (必ず、`next` オブジェクトを指定してください)。次に例を示します。 +複数のコールバック関数で1つのルートを処理できます (必ず、`next` オブジェクトを指定してください)。次に例を示します。 For example: ```js app.get('/example/b', (req, res, next) => { @@ -234,7 +268,7 @@ app.get('/example/b', (req, res, next) => { }) ``` -コールバック関数の配列で 1 つのルートを処理できます。次に例を示します。 +コールバック関数の配列で 1 つのルートを処理できます。次に例を示します。 For example: ```js const cb0 = function (req, res, next) { @@ -254,7 +288,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -独立した関数と、関数の配列の組み合わせで1つのルートを処理できます。次に例を示します。 +独立した関数と、関数の配列の組み合わせで1つのルートを処理できます。次に例を示します。 For example: ```js const cb0 = function (req, res, next) { @@ -277,24 +311,24 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => {

    レスポンスメソッド

    -次の表に示すレスポンスオブジェクト (`res`) のメソッドは、レスポンスをクライアントに送信して、リクエストとレスポンスのサイクルを終了することができます。これらのメソッドのいずれもルート・ハンドラーから呼び出されない場合、クライアントリクエストはハングしたままになります。 +次の表に示すレスポンスオブジェクト (`res`) のメソッドは、レスポンスをクライアントに送信して、リクエストとレスポンスのサイクルを終了することができます。これらのメソッドのいずれもルート・ハンドラーから呼び出されない場合、クライアントリクエストはハングしたままになります。 If none of these methods are called from a route handler, the client request will be left hanging. -| メソッド | 説明 -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | ファイルのダウンロードのプロンプトを出します。 -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | レスポンスプロセスを終了します。 -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | JSON レスポンスを送信します。 -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | JSONP をサポートする JSON レスポンスを送信します。 -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | リクエストをリダイレクトします。 -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | ビュー・テンプレートをレンダリングします。 -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | さまざまなタイプのレスポンスを送信します。 -| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | ファイルをオクテット・ストリームとして送信します。 -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | レスポンスのステータスコードを設定して、そのストリング表現をレスポンス本文として送信します。 +| メソッド | 説明 | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | ファイルのダウンロードのプロンプトを出します。 | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | レスポンスプロセスを終了します。 | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | JSON レスポンスを送信します。 | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | JSONP をサポートする JSON レスポンスを送信します。 | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | リクエストをリダイレクトします。 | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | ビュー・テンプレートをレンダリングします。 | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | さまざまなタイプのレスポンスを送信します。 | +| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | ファイルをオクテット・ストリームとして送信します。 | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | レスポンスのステータスコードを設定して、そのストリング表現をレスポンス本文として送信します。 |

    app.route()

    -`app.route()` を使用して、ルート・パスの連結可能なルート・ハンドラーを作成できます。 -パスは単一の場所で指定されるため、モジュール式のルートを作成すると、便利であるほか、冗長性とタイプミスを減らすことができます。ルートについて詳しくは、[Router() 資料](/{{ page.lang }}/4x/api.html#router)を参照してください。 +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](/{{ page.lang }}/5x/api.html#router). 次に、`app.route()` を使用して定義された、チェーニングされたルート・ハンドラーの例を示します。 @@ -313,7 +347,7 @@ app.route('/book')

    express.Router

    -モジュール式のマウント可能なルート・ハンドラーを作成するには、`express.Router` クラスを使用します。`Router` インスタンスは、完全なミドルウェアおよびルーティング・システムです。そのため、よく「ミニアプリケーション」と呼ばれます。 +モジュール式のマウント可能なルート・ハンドラーを作成するには、`express.Router` クラスを使用します。`Router` インスタンスは、完全なミドルウェアおよびルーティング・システムです。そのため、よく「ミニアプリケーション」と呼ばれます。 A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app". 次の例では、ルーターをモジュールとして作成し、その中にミドルウェア関数をロードして、いくつかのルートを定義し、ルート・モジュールをメインアプリケーションのパスにマウントします。 @@ -324,10 +358,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -344,8 +380,16 @@ module.exports = router ```js const birds = require('./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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/ja/guide/using-middleware.md b/ja/guide/using-middleware.md old mode 100755 new mode 100644 index f16940d113..1b61da360d --- a/ja/guide/using-middleware.md +++ b/ja/guide/using-middleware.md @@ -1,45 +1,47 @@ --- layout: page title: Express ミドルウェアの使用 +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: ja -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # ミドルウェアの使用 Express は、それ自体では最小限の機能を備えたルーティングとミドルウェアの Web フレームワークです。Express アプリケーションは基本的に一連のミドルウェア関数呼び出しです。 -*ミドルウェア* 関数は、[requestオブジェクト](/{{ page.lang }}/4x/api.html#req) (`req`)、[responseオブジェクト](/{{ page.lang }}/4x/api.html#res) (`res`)、およびアプリケーションのリクエストレスポンスサイクルにおける次のミドルウェア関数に対するアクセス権限を持つ関数です。次のミドルウェア関数は一般的に、`next` という変数で表されます。 +_ミドルウェア_ 関数は、[requestオブジェクト](/{{ page.lang }}/4x/api.html#req) (`req`)、[responseオブジェクト](/{{ page.lang }}/4x/api.html#res) (`res`)、およびアプリケーションのリクエストレスポンスサイクルにおける次のミドルウェア関数に対するアクセス権限を持つ関数です。次のミドルウェア関数は一般的に、`next` という変数で表されます。 The next middleware function is commonly denoted by a variable named `next`. ミドルウェア関数は以下のタスクを実行できます。 -* 任意のコードを実行する。 -* リクエストオブジェクトとレスポンスオブジェクトを変更する。 -* リクエストレスポンスサイクルを終了する。 -* スタック内の次のミドルウェア関数を呼び出す。 +- 任意のコードを実行する。 +- リクエストオブジェクトとレスポンスオブジェクトを変更する。 +- リクエストレスポンスサイクルを終了する。 +- スタック内の次のミドルウェア関数を呼び出す。 -現在のミドルウェア関数がリクエストレスポンスサイクルを終了しない場合は、`next()` を呼び出して、次のミドルウェア関数に制御を渡す必要があります。そうしないと、リクエストはハングしたままになります。 +現在のミドルウェア関数がリクエストレスポンスサイクルを終了しない場合は、`next()` を呼び出して、次のミドルウェア関数に制御を渡す必要があります。そうしないと、リクエストはハングしたままになります。 Otherwise, the request will be left hanging. Express アプリケーションは、以下のタイプのミドルウェアを使用できます。 - - [アプリケーション・レベルのミドルウェア](#middleware.application) - - [ルーター・レベルのミドルウェア](#middleware.router) - - [エラー処理ミドルウェア](#middleware.error-handling) - - [標準装備のミドルウェア](#middleware.built-in) - - [サード・パーティー・ミドルウェア](#middleware.third-party) +- [アプリケーション・レベルのミドルウェア](#middleware.application) +- [ルーター・レベルのミドルウェア](#middleware.router) +- [エラー処理ミドルウェア](#middleware.error-handling) +- [標準装備のミドルウェア](#middleware.built-in) +- [サード・パーティー・ミドルウェア](#middleware.third-party) アプリケーション・レベルとルーター・レベルのミドルウェアは、オプションのマウント・パスを指定してロードできます。 また、一連のミドルウェア関数を一緒にロードできます。こうすると、マウント・ポイントにミドルウェア・システムのサブスタックが作成されます。 +You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.

    アプリケーション・レベルのミドルウェア

    `app.use()` 関数と `app.METHOD()` 関数を使用して、アプリケーション・レベルのミドルウェアを [appオブジェクト](/{{ page.lang }}/4x/api.html#app) のインスタンスにバインドします。ここで、`METHOD` は、ミドルウェア関数が小文字で処理するリクエスト (GET、PUT、POST など) の HTTP メソッドです。 -次の例は、マウント・パスを指定しないミドルウェア関数を示しています。この関数は、アプリケーションがリクエストを受け取るたびに実行されます。 +This example shows a middleware function with no mount path. The function is executed every time the app receives a request. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -48,7 +50,7 @@ app.use((req, res, next) => { }) ``` -次の例は、`/user/:id` パスにマウントされたミドルウェア関数を示しています。この関数は、`/user/:id` パスに対するすべてのタイプの HTTP リクエストで実行されます。 +This example shows a middleware function mounted on the `/user/:id` path. 次の例は、`/user/:id` パスにマウントされたミドルウェア関数を示しています。この関数は、`/user/:id` パスに対するすべてのタイプの HTTP リクエストで実行されます。 ```js app.use('/user/:id', (req, res, next) => { @@ -57,7 +59,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -次の例は、ルートとそのハンドラー関数 (ミドルウェア・システム) を示しています。この関数は、`/user/:id` パスへの GET リクエストを処理します。 +This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. ```js app.get('/user/:id', (req, res, next) => { @@ -65,8 +67,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('/user/:id', (req, res, next) => { @@ -78,7 +80,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -ルート・ハンドラーを使用すると、パスに複数のルートを定義できます。下記の例では、`/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 リクエストを処理するミドルウェア・サブスタックを示しています。 @@ -92,29 +94,58 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` ルーター・ミドルウェア・スタックの残りのミドルウェア関数をスキップするには、`next('route')` を呼び出して、次のルートに制御を渡します。 **注**: `next('route')` は、`app.METHOD()` 関数または `router.METHOD()` 関数を使用してロードされたミドルウェア関数でのみ機能します。 +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} + 次の例は、`/user/:id` パスへの GET リクエストを処理するミドルウェア・サブスタックを示しています。 ```js app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route - if (Number(req.params.id) === 0) next('route') + if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +次の例は、ルートとそのハンドラー関数 (ミドルウェア・システム) を示しています。この関数は、`/user/:id` パスへの GET リクエストを処理します。 + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -131,6 +162,7 @@ const router = express.Router() 次のコードの例では、ルーター・レベルのミドルウェアを使用して、上記のアプリケーション・レベルのミドルウェアで示されているミドルウェア・システムを複製します。 ```js +const express = require('express') const app = express() const router = express.Router() @@ -152,7 +184,7 @@ router.use('/user/:id', (req, res, 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 (Number(req.params.id) === 0) next('route') + if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next() }, (req, res, next) => { @@ -172,9 +204,10 @@ app.use('/', router) ルータのミドルウェア機能の残りの部分をスキップするには、`next('router')`を呼び出してルータインスタンスから制御を戻します。 -この例は、`/user/:id`パスに対するGET要求を処理するミドルウェアサブスタックを示しています。 +次の例は、`/user/:id` パスへの GET リクエストを処理するミドルウェア・サブスタックを示しています。 ```js +const express = require('express') const app = express() const router = express.Router() @@ -184,7 +217,7 @@ router.use((req, res, next) => { next() }) -router.get('/', (req, res) => { +router.get('/user/:id', (req, res) => { res.send('hello, user!') }) @@ -197,8 +230,7 @@ app.use('/admin', router, (req, res) => {

    エラー処理ミドルウェア

    - -エラー処理ミドルウェアは常に *4つ* の引数を使用します。エラー処理ミドルウェア関数として識別されるように 4 つの引数を指定する必要があります。`next` オブジェクトは、使用する必要がない場合でも、シグニチャーを維持するために指定する必要があります。指定しないと、`next` オブジェクトは通常のミドルウェアとして解釈され、エラーを処理できなくなります。 +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.
    エラー処理ミドルウェア関数は、その他のミドルウェア関数と同じ方法で定義しますが、例外として、シグニチャーで3つではなく4つの引数 `(err、req、res、next)`) を明示的に指定します。 @@ -212,17 +244,17 @@ app.use((err, req, res, next) => { エラー処理ミドルウェアについて詳しくは、[エラー処理](/{{ page.lang }}/guide/error-handling.html)を参照してください。 -

    標準装備のミドルウェア

    +

    Built-in middleware

    -バージョン 4.x 以降、Express は [Connect](https://github.com/senchalabs/connect) に依存しなくなりました。以前に Express に組み込まれていたすべてのミドルウェア関数は個別のモジュールになりました。[ミドルウェア関数のリスト](https://github.com/senchalabs/connect#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) に依存しなくなりました。以前に Express に組み込まれていたすべてのミドルウェア関数は個別のモジュールになりました。[ミドルウェア関数のリスト](https://github.com/senchalabs/connect#middleware)を参照してください。 Expressには、次のミドルウェア機能が組み込まれています。 - [express.static](/en/4x/api.html#express.static) は、HTMLファイルや画像などの静的リソースを提供します -- [express.json](/en/4x/api.html#express.json) はJSONペイロードで受信したリクエストを解析します。**注:Express 4.16.0以降で利用可能** -- [express.urlencoded](/en/4x/api.html#express.urlencoded) は、URLエンコードされたペイロードで受信したリクエストを解析します。**注:Express 4.16.0以降で利用可能** +- [express.json](/en/4x/api.html#express.json) はJSONペイロードで受信したリクエストを解析します。**注:Express 4.16.0以降で利用可能** **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) は、URLエンコードされたペイロードで受信したリクエストを解析します。**注:Express 4.16.0以降で利用可能** **NOTE: Available with Express 4.16.0+** -

    サード・パーティー・ミドルウェア

    +

    Third-party middleware

    Express アプリケーションに機能を追加するには、サード・パーティー・ミドルウェアを使用します。 diff --git a/ja/guide/using-template-engines.md b/ja/guide/using-template-engines.md old mode 100755 new mode 100644 index d376878fc4..257552800b --- a/ja/guide/using-template-engines.md +++ b/ja/guide/using-template-engines.md @@ -1,30 +1,24 @@ --- layout: page title: Express でのテンプレート・エンジンの使用 +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: ja -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- # Express でのテンプレート・エンジンの使用 -_テンプレートエンジン_ を使用すると、アプリケーションで静的なテンプレートファイルを使用できます。実行時に、テンプレートエンジンはテンプレートファイルの変数を実際の値に置き換え、テンプレートをクライアントに送信するHTMLファイルに変換します。このアプローチにより、HTMLページの設計が容易になります。 +A _template engine_ enables you to use static template files in your application. _テンプレートエンジン_ を使用すると、アプリケーションで静的なテンプレートファイルを使用できます。実行時に、テンプレートエンジンはテンプレートファイルの変数を実際の値に置き換え、テンプレートをクライアントに送信するHTMLファイルに変換します。このアプローチにより、HTMLページの設計が容易になります。 +This approach makes it easier to design an HTML page. Expressで動作する一般的なテンプレートエンジンには、[Pug](https://pugjs.org/api/getting-started.html)、[Mustache](https://www.npmjs.com/package/mustache)、[EJS](https://www.npmjs.com/package/ejs)があります。[Expressアプリケーションジェネレータ](/{{ page.lang }}/starter/generator.html)は[Jade](https://www.npmjs.com/package/jade)をデフォルトとして使用しますが、いくつかの他のものもサポートしています。 -Expressで使用できるテンプレートエンジンのリストについては、[テンプレートエンジン (Express wiki)](https://github.com/expressjs/express/wiki#template-engines)を参照してください。また、[JavaScript テンプレートエンジンの比較: Jade, Mustache, Dust など](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-javascript-templates-jade-mustache-dust/)も参照してください。 - -
    - -**注**:Jadeは[Pug](https://www.npmjs.com/package/pug)に改名されました。あなたはアプリで引き続きJadeを使うことができ、うまく動くでしょう。しかしながら、テンプレートエンジンを最新のバージョンにアップデートしたい場合は、アプリでJadeをPugに置き換える必要があります。 - -
    - テンプレートファイルをレンダリングするには、次の[アプリケーション設定プロパティ](/{{ page.lang }}/4x/api.html#app.set)を設定し、ジェネレータで作成されたデフォルトアプリの`app.js`にセットします。 -* `views`はテンプレートファイルが置かれているディレクトリ。例:`app.set('views', './views')`。これは、デフォルトではアプリケーションのルートディレクトリ内の`views`ディレクトリになります -* `view engine`は使用するテンプレートエンジン。たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使用します +- `views`, the directory where the template files are located. `views`はテンプレートファイルが置かれているディレクトリ。例:`app.set('views', './views')`。これは、デフォルトではアプリケーションのルートディレクトリ内の`views`ディレクトリになります + This defaults to the `views` directory in the application root directory. +- `view engine`, the template engine to use. `view engine`は使用するテンプレートエンジン。たとえば、Pugテンプレートエンジンを使用するには、`app.set('view engine', 'pug')`を使用します 次に、対応するテンプレートエンジンnpmパッケージをインストールします。たとえばPugをインストールするには: @@ -32,11 +26,12 @@ Expressで使用できるテンプレートエンジンのリストについて $ npm install pug --save ``` -
    - -Pug などの Express 対応テンプレート・エンジンは、`__express(filePath, options, callback)` という関数をエクスポートします。この関数は、テンプレート・コードをレンダリングするために `res.render()` 関数によって呼び出されます。 +
    Pug などの Express 対応テンプレート・エンジンは、`__express(filePath, options, callback)` という関数をエクスポートします。この関数は、テンプレート・コードをレンダリングするために `res.render()` 関数によって呼び出されます。 一部のテンプレート・エンジンは、この規則に従いません。[Consolidate.js](https://www.npmjs.org/package/consolidate) ライブラリーは、すべての一般的な Node.js テンプレート・エンジンをマップすることで、この規則に従います。そのため、Express 内でシームレスに動作します。 +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. +
    ビュー・エンジンが設定された後は、アプリケーションでエンジンを指定したり、テンプレート・エンジンをロードしたりする必要はありません。(上記の例に対応した) 下記のように、Express がモジュールを内部的にロードします。 @@ -55,7 +50,8 @@ html h1= message ``` -次に、`index.pug` ファイルをレンダリングするためのルートを作成します。`view engine` プロパティーが設定されていない場合は、`view` ファイルの拡張子を指定する必要があります。そうでない場合は、省略できます。 +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. ```js app.get('/', (req, res) => { @@ -65,6 +61,4 @@ app.get('/', (req, res) => { ホーム・ページに要求すると、`index.pug` ファイルは HTML としてレンダリングされます。 -注:view engine のキャッシュは、テンプレートの出力内容をキャッシュしません。基本となるテンプレート自体だけです。このビューは、キャッシュがオンの場合でも、すべてのリクエストで再レンダリングされます。 - -Express でのテンプレート・エンジンの動作について詳しくは、[Express 用のテンプレート・エンジンの開発](/{{ page.lang }}/advanced/developing-template-engines.html)を参照してください。 +注:view engine のキャッシュは、テンプレートの出力内容をキャッシュしません。基本となるテンプレート自体だけです。このビューは、キャッシュがオンの場合でも、すべてのリクエストで再レンダリングされます。 The view is still re-rendered with every request even when the cache is on. diff --git a/ja/guide/writing-middleware.md b/ja/guide/writing-middleware.md old mode 100755 new mode 100644 index 3ce558e551..61958e2c0e --- a/ja/guide/writing-middleware.md +++ b/ja/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: Express アプリケーションで使用するミドルウェアの作成 +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: ja -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- # Express アプリケーションで使用するミドルウェアの作成

    概説

    -*ミドルウェア* 関数は、[リクエストオブジェクト](/{{ page.lang }}/4x/api.html#req) (`req`)、[レスポンスオブジェクト](/{{ page.lang }}/4x/api.html#res) (`res`)、およびアプリケーションのリクエストレスポンスサイクルにおける次のミドルウェア関数に対するアクセス権限を持つ関数です。次のミドルウェア関数は一般的に、`next` という変数で表されます。 +_ミドルウェア_ 関数は、[リクエストオブジェクト](/{{ page.lang }}/4x/api.html#req) (`req`)、[レスポンスオブジェクト](/{{ page.lang }}/4x/api.html#res) (`res`)、およびアプリケーションのリクエストレスポンスサイクルにおける次のミドルウェア関数に対するアクセス権限を持つ関数です。次のミドルウェア関数は一般的に、`next` という変数で表されます。 The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. ミドルウェア関数は以下のタスクを実行できます。 -* 任意のコードを実行する。 -* リクエストオブジェクトとレスポンスオブジェクトを変更する。 -* リクエストレスポンスサイクルを終了する。 -* スタック内の次のミドルウェアを呼び出す。 +- 任意のコードを実行する。 +- リクエストオブジェクトとレスポンスオブジェクトを変更する。 +- リクエストレスポンスサイクルを終了する。 +- スタック内の次のミドルウェアを呼び出す。 -現在のミドルウェア関数がリクエストレスポンスサイクルを終了しない場合は、`next()` を呼び出して、次のミドルウェア関数に制御を渡す必要があります。そうしないと、リクエストはハングしたままになります。 +現在のミドルウェア関数がリクエストレスポンスサイクルを終了しない場合は、`next()` を呼び出して、次のミドルウェア関数に制御を渡す必要があります。そうしないと、リクエストはハングしたままになります。 Otherwise, the request will be left hanging. 次の例は、ミドルウェア関数呼び出しの要素を示しています。 -
    ミドルウェア関数が適用されるパス (ルート)。
    @@ -43,9 +43,14 @@ description: Learn how to write custom middleware functions for Express.js appli
    +
    Elements of a middleware function call -
    ミドルウェア関数が適用される HTTP メソッド。
    +
    ミドルウェア関数が適用される HTTP メソッド。
    +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. +

    -次に、簡単な「Hello World」Expressアプリケーションの例を示します。 この記事の残りの部分では、アプリケーションに2つのミドルウェア関数、つまり単純なログメッセージを出力する`myLogger`と、HTTP要求のタイムスタンプを表示する`requestTime`という2つのミドルウェア関数を定義して追加します。 +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. ```js const express = require('express') @@ -59,8 +64,7 @@ app.listen(3000) ```

    ミドルウェア関数 myLogger

    - -次に、"myLogger"というミドルウェア関数の簡単な例を示します。この関数は、アプリケーションへのリクエストがそれを通過するときに、単に "LOGGED"を出力します。ミドルウェア関数は、`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`という名前の変数に割り当てられます。 ```js const myLogger = function (req, res, next) { @@ -70,11 +74,12 @@ const myLogger = function (req, res, next) { ```
    - -上記の `next()` の呼び出しに注意してください。この関数を呼び出すと、アプリケーション内の次のミドルウェア関数が呼び出されます。 -`next()` 関数は、Node.js または 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.
    +To load the middleware function, call `app.use()`, specifying the middleware function. ミドルウェア関数をロードするには、ミドルウェア関数を指定して `app.use()` を呼び出します。 例えば、次のコードは、ルート・パス (/) へのルートの前に `myLogger` ミドルウェア関数をロードします。 @@ -115,7 +120,7 @@ const requestTime = function (req, res, next) { } ``` -これで、アプリケーションが `requestTime` ミドルウェア関数を使用するようになります。また、ルート・パス・ルートのコールバック関数は、ミドルウェア関数が `req` (リクエストオブジェクト) に追加するプロパティーを使用します。 +The app now uses the `requestTime` middleware function. これで、アプリケーションが `requestTime` ミドルウェア関数を使用するようになります。また、ルート・パス・ルートのコールバック関数は、ミドルウェア関数が `req` (リクエストオブジェクト) に追加するプロパティーを使用します。 ```js const express = require('express') @@ -139,6 +144,52 @@ app.listen(3000) アプリケーションのルートにリクエストすると、アプリケーションは、リクエストのタイムスタンプをブラウザーに表示します。 +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + リクエストオブジェクト、レスポンスオブジェクト、スタック内の次のミドルウェア関数、および Node.js API を利用できるため、ミドルウェア関数が持つ可能性は無限です。 Express ミドルウェアについて詳しくは、[Express ミドルウェアの使用](/{{ page.lang }}/guide/using-middleware.html)を参照してください。 diff --git a/ja/resources/community.md b/ja/resources/community.md old mode 100755 new mode 100644 index 428e242135..2bc4cae37f --- a/ja/resources/community.md +++ b/ja/resources/community.md @@ -1,23 +1,89 @@ --- layout: page title: Express のコミュニティー +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: ja -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # コミュニティー -## 例 +## Technical committee -API の設計や認証からテンプレート・エンジンの統合まで、あらゆるものを扱っている数十の Express アプリケーションの[例](https://github.com/expressjs/express/tree/master/examples)をリポジトリーでご覧ください。 +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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +この活気あるコミュニティーでは、さまざまな拡張機能、[ミドルウェア・モジュール](/{{ page.lang }}/resources/middleware.html)、高水準のフレームワークが作成されています。[Wiki](https://github.com/expressjs/express/wiki) で確認してください。 + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## 問題 バグに思われるものが見つかったり、単に機能を要求したりする場合は、[問題のキュー](https://github.com/expressjs/express/issues)でチケットをオープンしてください。 -## サード・パーティー +## 例 -この活気あるコミュニティーでは、さまざまな拡張機能、[ミドルウェア・モジュール](/{{ page.lang }}/resources/middleware.html)、高水準のフレームワークが作成されています。[Wiki](https://github.com/expressjs/express/wiki) で確認してください。 +API の設計や認証からテンプレート・エンジンの統合まで、あらゆるものを扱っている数十の 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. + +# Branding of Express.js + +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/ja/resources/contributing.md b/ja/resources/contributing.md new file mode 100644 index 0000000000..f1e70e060b --- /dev/null +++ b/ja/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: ja +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/ja/resources/glossary.md b/ja/resources/glossary.md old mode 100755 new mode 100644 index 16a0687bb7..bb3d873f84 --- a/ja/resources/glossary.md +++ b/ja/resources/glossary.md @@ -1,57 +1,65 @@ --- layout: page title: Express の用語集 +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. menu: resources lang: ja -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. +redirect_from: " " --- # 用語集 ### アプリケーション -一般に、特定の目的で操作を実行するよう設計された 1 つ以上のプログラム。Express のコンテキストでは、Node.js プラットフォームで稼働する Express API を使用するプログラム。[アプリケーション・オブジェクト](/{{ page.lang }}/api.html#express)と呼ばれることもある。 +In general, one or more programs that are designed to carry out operations for a specific purpose. 一般に、特定の目的で操作を実行するよう設計された 1 つ以上のプログラム。Express のコンテキストでは、Node.js プラットフォームで稼働する Express API を使用するプログラム。[アプリケーション・オブジェクト](/{{ page.lang }}/api.html#express)と呼ばれることもある。 Might also refer to an [app object](/{{ page.lang }}/api.html#express). ### API -アプリケーション・プログラミング・インターフェース。最初に使用するときは、略語のスペルを略さない。 +Application programming interface. Spell out the abbreviation when it is first used. ### Express -特定の意見に固執しない、Node.js アプリケーション向けの高速で最小限の Web フレームワーク。一般に、「Express」の望ましい呼び方は「Express.js」であるが、後者でも問題はない。 +特定の意見に固執しない、Node.js アプリケーション向けの高速で最小限の Web フレームワーク。一般に、「Express」の望ましい呼び方は「Express.js」であるが、後者でも問題はない。 In general, "Express" is preferred to "Express.js," though the latter is acceptable. ### libuv 主に Node.js で使用するために開発された、非同期入出力に重点を置いたマルチプラットフォーム・サポート・ライブラリー。 -### ミドルウェア +### middleware -最後のリクエストハンドラーの前に Express ルーティング層によって呼び出される関数。そのため、未加工要求と最後の目的のルートの間に配置される。ミドルウェアの用語に関しては、微妙な点がいくつかある。 +最後のリクエストハンドラーの前に Express ルーティング層によって呼び出される関数。そのため、未加工要求と最後の目的のルートの間に配置される。ミドルウェアの用語に関しては、微妙な点がいくつかある。 A few fine points of terminology around middleware: - * `var foo = require('middleware')` は、Node.js モジュールを*要求* または*使用* することで呼び出される。その後、通常はステートメント `var mw = foo()` がミドルウェアを返す。 - * `app.use(mw)` は、*グローバル処理スタックにミドルウェアを追加* することで呼び出される。 - * `app.get('/foo', mw, function (req, res) { ... })` は、*「GET /foo」処理スタックにミドルウェアを追加* することで呼び出される。 +- `var foo = require('middleware')` は、Node.js モジュールを_要求_ または_使用_ することで呼び出される。その後、通常はステートメント `var mw = foo()` がミドルウェアを返す。 Then the statement `var mw = foo()` typically returns the middleware. +- `app.use(mw)` は、_グローバル処理スタックにミドルウェアを追加_ することで呼び出される。 +- `app.get('/foo', mw, function (req, res) { ... })` は、_「GET /foo」処理スタックにミドルウェアを追加_ することで呼び出される。 ### Node.js -スケーラブルなネットワーク・アプリケーションを作成するために使用されるソフトウェア・プラットフォーム。Node.js は、スクリプト言語として JavaScript を使用し、ノンブロッキング入出力と単一スレッドのイベント・ループを通して高スループットを実現する。[nodejs.org](http://nodejs.org/) を参照。**使用上の注意**: 初回は「Node.js」を使用し、その後は「Node」を使用する。 +A software platform that is used to build scalable network applications. スケーラブルなネットワーク・アプリケーションを作成するために使用されるソフトウェア・プラットフォーム。Node.js は、スクリプト言語として JavaScript を使用し、ノンブロッキング入出力と単一スレッドのイベント・ループを通して高スループットを実現する。[nodejs.org](http://nodejs.org/) を参照。**使用上の注意**: 初回は「Node.js」を使用し、その後は「Node」を使用する。 See [nodejs.org](https://nodejs.org/en/). **Usage note**: Initially, "Node.js," thereafter "Node". ### オープン・ソース -形容詞として使用する場合は、ハイフンを付ける (例:「This is open-source software.」)。[Wikipedia の「Open-source software」](http://en.wikipedia.org/wiki/Open-source_software)を参照。注: 一般的にはこの用語にハイフンを付けないが、ここでは複合形容詞にハイフンを付けるという標準英語の規則に従う。 +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). + +{% capture english-rules %} + +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. + +{% endcapture %} + +{% include admonitions/note.html content=english-rules %} ### リクエスト -HTTP リクエスト。クライアントは HTTP リクエストメッセージをサーバーに送信して、サーバーはレスポンスを返す。リクエストでは、いずれかの[リクエストメソッド](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) (GET、POST など) を使用する必要がある。 +An HTTP request. HTTP レスポンス。サーバーは、HTTP レスポンスメッセージをクライアントに返す。レスポンスにはリクエストの完了状況情報が含まれ、リクエストされた内容がメッセージの本文に入っている場合もある。 HTTP リクエスト。クライアントは HTTP リクエストメッセージをサーバーに送信して、サーバーはレスポンスを返す。リクエストでは、いずれかの[リクエストメソッド](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) (GET、POST など) を使用する必要がある。 ### レスポンス -HTTP レスポンス。サーバーは、HTTP レスポンスメッセージをクライアントに返す。レスポンスにはリクエストの完了状況情報が含まれ、リクエストされた内容がメッセージの本文に入っている場合もある。 +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. ### ルート -リソースを識別する URL の一部。例えば、`http://foo.com/products/id` の中では「/products/id」がルートである。 +Part of a URL that identifies a resource. リソースを識別する URL の一部。例えば、`http://foo.com/products/id` の中では「/products/id」がルートである。 ### ルーター diff --git a/ja/resources/middleware.md b/ja/resources/middleware.md old mode 100755 new mode 100644 index 50a1706387..559685bd50 --- a/ja/resources/middleware.md +++ b/ja/resources/middleware.md @@ -1,64 +1,45 @@ --- -layout: page +layout: middleware title: Express のミドルウェア +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. menu: resources lang: ja -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. +redirect_from: " " +module: mw-home --- -# サード・パーティー・ミドルウェア +## Express のミドルウェア -下記に、いくつかの Express ミドルウェア・モジュールを挙げます。 +The Express middleware modules listed here are maintained by the +[Expressjs team](https://github.com/orgs/expressjs/people). - - [body-parser](https://github.com/expressjs/body-parser): 以前の `express.bodyParser`、`json`、`urlencoded`。以下も参照してください。 - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression): 以前の `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): 最適なイメージ・サービス提供を実現する Connect/Express ミドルウェア・モジュール。可能な場合は、イメージを `.webp` または `.jxr` に切り替えてください。 - - [connect-timeout](https://github.com/expressjs/timeout): 以前の `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser): 以前の `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session): 以前の `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler): 以前の `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug): テンプレート変数 (ローカル)、現行セッション、有用な要求データなどに関する情報を示すタブをアプリケーションに追加する小規模な開発ツール。 - - [express-partial-response](https://github.com/nemtsov/express-partial-response): Google API の Partial Response を使用することで、`fields` 照会ストリングに基づいて JSON 応答の一部をフィルターで除去するための Express ミドルウェア・モジュール。 - - [express-session](https://github.com/expressjs/session): 以前の `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): 複数ホストのサポート (例えば、cdn1.host.com、cdn2.host.com) を備え、静的資産に CDN を使用するための Express ミドルウェア・モジュール。 - - [express-slash](https://github.com/ericf/express-slash): 末尾スラッシュを厳密に処理するユーザー向けの Express ミドルウェア・モジュール。 - - [express-stormpath](https://github.com/stormpath/stormpath-express): ユーザー・ストレージ、認証、許可、SSO、データ・セキュリティーのための Express ミドルウェア・モジュール。 - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): 大文字を含む HTTP 要求を正規の小文字形式に変換するためのミドルウェア・モジュール。 - - [helmet](https://github.com/helmetjs/helmet): さまざまな HTTP ヘッダーを設定することでアプリケーションを保護する上で役立つモジュール。 - - [join-io](https://github.com/coderaiser/join-io "join-io"): 要求数を減らすために処理中にファイルを結合するモジュール。 - - [method-override](https://github.com/expressjs/method-override): 以前の `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan): 以前の `logger` - - [passport](https://github.com/jaredhanson/passport): 認証のための Express ミドルウェア・モジュール。 - - [response-time](https://github.com/expressjs/response-time): 以前の `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon): 以前の `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index): 以前の `express.directory` - - [serve-static](https://github.com/expressjs/serve-static): 静的コンテンツを提供するためのモジュール。 - - [static-expiry](https://github.com/paulwalker/connect-static-expiry): 1 つ以上の外部ドメインに対するサポートを含む、静的資産の指紋認証 URL またはキャッシング・ヘッダー。 - - [vhost](https://github.com/expressjs/vhost): 以前の `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers): ビューに共通ヘルパー・メソッドを提供する Express ミドルウェア・モジュール。 - - [sriracha-admin](https://github.com/hdngr/siracha): Mongoose 用の管理サイトを動的に生成する Express ミドルウェア・モジュール。 +| Middleware module | 説明 | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -以前は Connect に組み込まれていた一部のミドルウェア・モジュールは、Connect/Express チームによってサポートされなくなっています。これらのモジュールは、代替のモジュールに置き換えられているか、より優れたモジュールに置き換えられる必要があります。以下のいずれかの代替モジュールを使用してください。 +## Additional middleware modules - - express.cookieParser - - [cookies](https://github.com/jed/cookies) および [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -その他のミドルウェア・モジュールについては、下記を参照してください。 +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| Middleware module | 説明 | +| ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet): さまざまな HTTP ヘッダーを設定することでアプリケーションを保護する上で役立つモジュール。 | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport): 認証のための Express ミドルウェア・モジュール。 | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/ja/resources/middleware/body-parser.md b/ja/resources/middleware/body-parser.md new file mode 100644 index 0000000000..b559999c91 --- /dev/null +++ b/ja/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: ja +redirect_from: " " +module: body-parser +--- diff --git a/ja/resources/middleware/compression.md b/ja/resources/middleware/compression.md new file mode 100644 index 0000000000..bd253f78ec --- /dev/null +++ b/ja/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: ja +redirect_from: " " +module: compression +--- diff --git a/ja/resources/middleware/connect-rid.md b/ja/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..fa3decc4b7 --- /dev/null +++ b/ja/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: ja +redirect_from: " " +module: connect-rid +--- diff --git a/ja/resources/middleware/cookie-parser.md b/ja/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..2e4a06dc73 --- /dev/null +++ b/ja/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: ja +redirect_from: " " +module: cookie-parser +--- diff --git a/ja/resources/middleware/cookie-session.md b/ja/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..0b56e2909a --- /dev/null +++ b/ja/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: ja +redirect_from: " " +module: cookie-session +--- diff --git a/ja/resources/middleware/cors.md b/ja/resources/middleware/cors.md new file mode 100644 index 0000000000..a09c1fccbb --- /dev/null +++ b/ja/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: ja +redirect_from: " " +module: cors +--- diff --git a/ja/resources/middleware/errorhandler.md b/ja/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..e27e784a43 --- /dev/null +++ b/ja/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: ja +redirect_from: " " +module: errorhandler +--- diff --git a/ja/resources/middleware/method-override.md b/ja/resources/middleware/method-override.md new file mode 100644 index 0000000000..bad4b7f9a7 --- /dev/null +++ b/ja/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: ja +redirect_from: " " +module: method-override +--- diff --git a/ja/resources/middleware/morgan.md b/ja/resources/middleware/morgan.md new file mode 100644 index 0000000000..b9e249bd37 --- /dev/null +++ b/ja/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: ja +redirect_from: " " +module: morgan +--- diff --git a/ja/resources/middleware/multer.md b/ja/resources/middleware/multer.md new file mode 100644 index 0000000000..da1682f2b1 --- /dev/null +++ b/ja/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: ja +redirect_from: " " +module: multer +--- diff --git a/ja/resources/middleware/response-time.md b/ja/resources/middleware/response-time.md new file mode 100644 index 0000000000..cf251119eb --- /dev/null +++ b/ja/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: ja +redirect_from: " " +module: response-time +--- diff --git a/ja/resources/middleware/serve-favicon.md b/ja/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..e5d95457ee --- /dev/null +++ b/ja/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: ja +redirect_from: " " +module: serve-favicon +--- diff --git a/ja/resources/middleware/serve-index.md b/ja/resources/middleware/serve-index.md new file mode 100644 index 0000000000..33ae36a10c --- /dev/null +++ b/ja/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: ja +redirect_from: " " +module: serve-index +--- diff --git a/ja/resources/middleware/serve-static.md b/ja/resources/middleware/serve-static.md new file mode 100644 index 0000000000..df10ec2fd9 --- /dev/null +++ b/ja/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: ja +redirect_from: " " +module: serve-static +--- diff --git a/ja/resources/middleware/session.md b/ja/resources/middleware/session.md new file mode 100644 index 0000000000..e09e920c4a --- /dev/null +++ b/ja/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: ja +redirect_from: " " +module: session +--- diff --git a/ja/resources/middleware/timeout.md b/ja/resources/middleware/timeout.md new file mode 100644 index 0000000000..61e04f32af --- /dev/null +++ b/ja/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: ja +redirect_from: " " +module: timeout +--- diff --git a/ja/resources/middleware/vhost.md b/ja/resources/middleware/vhost.md new file mode 100644 index 0000000000..78a8042b21 --- /dev/null +++ b/ja/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: ja +redirect_from: " " +module: vhost +--- diff --git a/ja/resources/utils.md b/ja/resources/utils.md new file mode 100644 index 0000000000..50e259ca9a --- /dev/null +++ b/ja/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: ja +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | 説明 | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/ja/starter/basic-routing.md b/ja/starter/basic-routing.md old mode 100755 new mode 100644 index 0142b98587..5869a23483 --- a/ja/starter/basic-routing.md +++ b/ja/starter/basic-routing.md @@ -1,25 +1,25 @@ --- layout: page title: Express の基本的なルーティング +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. menu: starter lang: ja -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. +redirect_from: " " --- # 基本的なルーティング -*ルーティング* とは、アプリケーションが特定のエンドポイントに対するクライアント要求に応答する方法として、URI (またはパス) と特定の HTTP 要求メソッド (GET、POST など) を決定することです。 +_ルーティング_ とは、アプリケーションが特定のエンドポイントに対するクライアント要求に応答する方法として、URI (またはパス) と特定の HTTP 要求メソッド (GET、POST など) を決定することです。 各ルートには、1 つ以上のハンドラー関数があり、それらはルートが一致したときに実行されます。 ルート定義では、次の構造を使用します。 + ```js app.METHOD(PATH, HANDLER) ``` -各部分の意味は次のとおりです。 +Where: - `app` は、`express` のインスタンスです。 - `METHOD` は、[HTTP 要求メソッド](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) です。 @@ -27,7 +27,9 @@ app.METHOD(PATH, HANDLER) - `HANDLER` は、ルートが一致したときに実行される関数です。
    +This tutorial assumes that an instance of `express` named `app` is created and the server is running. このチュートリアルでは、`app` という名前の `express` のインスタンスが作成されていて、サーバーが稼働中であることを想定しています。アプリケーションの作成と開始に慣れていない場合は、[Hello World の例](/{{ page.lang }}/starter/hello-world.html) を参照してください。 +
    以下の例は、単純なルートの定義を示しています。 @@ -65,3 +67,5 @@ app.delete('/user', (req, res) => { ``` ルーティングについて詳しくは、[ルーティング・ガイド](/{{ page.lang }}/guide/routing.html)を参照してください。 + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/ja/starter/examples.md b/ja/starter/examples.md new file mode 100644 index 0000000000..7a668cf0de --- /dev/null +++ b/ja/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: ja +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/ja/starter/faq.md b/ja/starter/faq.md old mode 100755 new mode 100644 index 6b18c77677..487df0aaaa --- a/ja/starter/faq.md +++ b/ja/starter/faq.md @@ -1,56 +1,74 @@ --- layout: page title: Express に関する FAQ +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: ja -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # FAQ ## どのようにしてアプリケーションを構成するのですか? -この質問に対する決定的な答えはありません。ご使用のアプリケーションや関与するチームの規模によって答えは異なります。可能な限り柔軟であるために、Express には、構造に関する前提がありません。 +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. -ルートやその他のアプリケーション固有のロジックは、必要な数だけのファイルや、任意のディレクトリー構造に存在できます。参考のために、以下の例を参照してください。 +ルートやその他のアプリケーション固有のロジックは、必要な数だけのファイルや、任意のディレクトリー構造に存在できます。参考のために、以下の例を参照してください。 View the following +examples for inspiration: -* [ルートのリスト](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [ルートのマップ](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [MVC スタイルのコントローラー](https://github.com/expressjs/express/tree/master/examples/mvc) +- [ルートのリスト](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [ルートのマップ](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [MVC スタイルのコントローラー](https://github.com/expressjs/express/tree/master/examples/mvc) また、これらのパターンを簡素化する、サード・パーティー製の Express 拡張版があります。 -* [Resourceful ルーティング](https://github.com/expressjs/express-resource) +- [Resourceful ルーティング](https://github.com/expressjs/express-resource) ## どのようにしてモデルを定義するのですか? -Express には、データベースの概念がありません。この概念はサード・パーティーの Node モジュールに任せられているため、ほとんどのデータベースとやりとりできます。 +Express には、データベースの概念がありません。この概念はサード・パーティーの Node モジュールに任せられているため、ほとんどのデータベースとやりとりできます。 This concept is +left up to third-party Node modules, allowing you to +interface with nearly any database. モデルに関する Express ベースのフレームワークについては、[LoopBack](http://loopback.io) を参照してください。 ## どのようにしてユーザーを認証するのですか? +Authentication is another opinionated area that Express does not +venture into. You may use any authentication scheme you wish. 認証は、Express が足を踏み入れていないもう 1 つの分野です。任意の認証スキームを使用できます。 単純なユーザー名/パスワードのスキームについては、[この例](https://github.com/expressjs/express/tree/master/examples/auth)を参照してください。 - ## Express はどのテンプレート・エンジンをサポートしているのですか? Express は、`(パス、ロケール、コールバック)` シグニチャーに準拠するすべてのテンプレート・エンジンをサポートします。 テンプレート・エンジンのインターフェースとキャッシングを正規化するには、[consolidate.js](https://github.com/visionmedia/consolidate.js) プロジェクトでサポートを参照してください。リストされていないテンプレート・エンジンでも Express シグニチャーをサポートしている可能性があります。 +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. + +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). ## どのようにして 404 応答に対応するのですか? -Express では、404 応答はエラーの結果ではありません。そのため、エラー・ハンドラー・ミドルウェアはそれらをキャプチャーしません。このように動作するのは、404 応答は単に追加の処理が存在しないことを示しているためです。つまり、Express は、すべてのミドルウェア関数とルートを実行して、そのいずれも応答しなかったことを検出したということです。404 応答に対応するには、スタックの最下部 (他のすべての関数の下) にミドルウェア関数を追加するだけですみます。 +Express では、404 応答はエラーの結果ではありません。そのため、エラー・ハンドラー・ミドルウェアはそれらをキャプチャーしません。このように動作するのは、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, +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: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## どのようにしてエラー・ハンドラーをセットアップするのですか? エラー処理ミドルウェアの定義方法は、他のミドルウェアと同じですが、引数の数が 3 つではなく 4 つである点が異なります。具体的には、シグニチャー `(err、req、res、next)` です。 @@ -66,6 +84,16 @@ app.use((err, req, res, next) => { ## どのようにしてプレーン HTML をレンダリングするのですか? -レンダリングしません。`res.render()` 関数で HTML を「レンダリング」する必要はありません。 +You don't! レンダリングしません。`res.render()` 関数で HTML を「レンダリング」する必要はありません。 特定のファイルがある場合は、`res.sendFile()` 関数を使用します。 ディレクトリーから多数の資産を提供する場合は、`express.static()` ミドルウェア関数を使用します。 +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. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/ja/starter/generator.md b/ja/starter/generator.md old mode 100755 new mode 100644 index 65c87fced3..5e936dcbab --- a/ja/starter/generator.md +++ b/ja/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Express のアプリケーション生成プログラム +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: ja -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Express のアプリケーション生成プログラム アプリケーション生成プログラム・ツールの `express` を使用すると、アプリケーション・スケルトンを素早く作成できます。 -次のコマンドを使用して、`express` をインストールします。 +You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash -$ npm install express-generator -g +$ npx express-generator +``` + +For earlier Node versions, install the application generator as a global npm package and then launch it: + +```bash +$ npm install -g express-generator +$ express ``` `-h` オプションを指定してコマンド・オプションを表示します。 @@ -22,7 +29,7 @@ $ npm install express-generator -g ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -例えば、以下のコマンドでは、現行作業ディレクトリーに _myapp_ という Express アプリケーションを作成します。 +例えば、以下のコマンドでは、現行作業ディレクトリーに _myapp_ という Express アプリケーションを作成します。 The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -70,18 +77,24 @@ $ cd myapp $ npm install ``` -MacOS または Linux では、次のコマンドによってアプリケーションを実行します。 +Windows では、次のコマンドを使用します。 ```bash $ DEBUG=myapp:* npm start ``` -Windows では、次のコマンドを使用します。 +On Windows Command Prompt, use this command: ```bash > set DEBUG=myapp:* & npm start ``` +On Windows PowerShell, use this command: + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + 次に、ブラウザーに `http://localhost:3000/` をロードして、アプリケーションにアクセスします。 生成されたアプリケーションには、以下のディレクトリー構造があります。 @@ -109,5 +122,7 @@ Windows では、次のコマンドを使用します。 ```
    -ここで生成プログラムによって作成されたアプリケーション構造は、Express アプリケーションを作成するための数多くの方法の 1 つにすぎません。この構造を自由に使用したり、ニーズに合わせて変更したりしてください。 +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.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/ja/starter/hello-world.md b/ja/starter/hello-world.md old mode 100755 new mode 100644 index 1fe953302b..630fe79e50 --- a/ja/starter/hello-world.md +++ b/ja/starter/hello-world.md @@ -1,22 +1,18 @@ --- layout: page title: Express の「Hello World」の例 +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: ja -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Hello World の例
    -ここで紹介するのは基本的に、作成できる最も単純な Express アプリケーションです。このアプリケーションは単一ファイル・アプリケーションであり、[Express ジェネレーター](/{{ page.lang }}/starter/generator.html) を使用して得られるものでは *ありません* 。このジェネレーターは、さまざまな目的で多数の JavaScript ファイル、Jade テンプレート、サブディレクトリーを使用する完全なアプリケーション用のスキャフォールディングを作成します。 +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](/{{ page.lang }}/starter/generator.html), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.
    -最初に、`myapp` という名前のディレクトリーを作成して、そのディレクトリーに移動し、`npm init` を実行します。次に、[インストール・ガイド](/{{ page.lang }}/starter/installing.html)に従い、依存関係として `express` をインストールします。 - -`myapp` ディレクトリーで、`app.js` というファイルを作成して、以下のコードを追加します。 - ```js const express = require('express') const app = express() @@ -31,7 +27,13 @@ app.listen(port, () => { }) ``` -アプリケーションは、サーバーを始動して、ポート 3000 で接続を listen します。アプリケーションは、ルート URL (`/`) または*ルート* に対する要求に「Hello World!」と応答します。その他すべてのパスについては、「**404 Not Found**」と応答します。 +This app starts a server and listens on port 3000 for connections. アプリケーションは、サーバーを始動して、ポート 3000 で接続を listen します。アプリケーションは、ルート URL (`/`) または_ルート_ に対する要求に「Hello World!」と応答します。その他すべてのパスについては、「**404 Not Found**」と応答します。 For every other path, it will respond with a **404 Not Found**. + +### Running Locally + +最初に、`myapp` という名前のディレクトリーを作成して、そのディレクトリーに移動し、`npm init` を実行します。次に、[インストール・ガイド](/{{ page.lang }}/starter/installing.html)に従い、依存関係として `express` をインストールします。 Then, install `express` as a dependency, as per the [installation guide](/{{ page.lang }}/starter/installing.html). + +`myapp` ディレクトリーで、`app.js` というファイルを作成して、以下のコードを追加します。
    `req` (要求) と `res` (応答) は、Node が提供するのとまったく同じオブジェクトであるため、Express が関与しない場合と同じように、`req.pipe()`、`req.on('data', callback)` などを呼び出すことができます。 @@ -45,3 +47,4 @@ $ node app.js 次に、ブラウザーに [http://localhost:3000/](http://localhost:3000/) をロードして、出力を確認します。 +### ここで紹介するのは基本的に、作成できる最も単純な Express アプリケーションです。このアプリケーションは単一ファイル・アプリケーションであり、[Express ジェネレーター](/{{ page.lang }}/starter/generator.html) を使用して得られるものでは _ありません_ 。このジェネレーターは、さまざまな目的で多数の JavaScript ファイル、Jade テンプレート、サブディレクトリーを使用する完全なアプリケーション用のスキャフォールディングを作成します。 diff --git a/ja/starter/installing.md b/ja/starter/installing.md old mode 100755 new mode 100644 index 7905005d09..f961057368 --- a/ja/starter/installing.md +++ b/ja/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: Express のインストール +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: ja -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # インストール 既に [Node.js](https://nodejs.org/) をインストールしてあることを想定して、ここではアプリケーションを作成するディレクトリーを作り、それを作業ディレクトリーにします。 +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -18,21 +21,22 @@ $ cd myapp `npm init` コマンドを使用して、アプリケーション用の `package.json` ファイルを作成します。 `package.json` の機能について詳しくは、[Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json) を参照してください。 +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 ``` -次のコマンドは、アプリケーションの名前やバージョンなど、いくつかのことを要求します。 -ここでは、以下の例外を除いて、RETURN キーを押して単にそれらのデフォルトのほとんどを受け入れることができます。 +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: -```bash +``` entry point: (index.js) ``` -`app.js` と入力するか、メインファイルの名前にしたいものを何か入力してください。もしそれを `index.js` にしたいのなら、RETURN キーを押して提案されたデフォルトのファイル名を受け入れてください。 +`app.js` と入力するか、メインファイルの名前にしたいものを何か入力してください。もしそれを `index.js` にしたいのなら、RETURN キーを押して提案されたデフォルトのファイル名を受け入れてください。 If you want it to be `index.js`, hit RETURN to accept the suggested default file name. -Expressを `myapp` ディレクトリにインストールし、それを依存関係リストに保存してください。例えば: +Expressを `myapp` ディレクトリにインストールし、それを依存関係リストに保存してください。例えば: For example: ```bash $ npm install express @@ -45,7 +49,9 @@ $ npm install express --no-save ```
    + npm 5.0 以降のデフォルトでは、npm install はモジュールを `package.json` ファイルの `dependencies` リストに追加します。以前のバージョンの npm では、`--save` オプションを明示的に指定しなければなりません。その後、app ディレクトリで `npm install` を実行すると、依存関係リストにモジュールが自動的にインストールされます。 + Then, afterwards, running `npm install` in the app directory will automatically install modules in the dependencies list.
    -### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/ja/starter/static-files.md b/ja/starter/static-files.md old mode 100755 new mode 100644 index 9432671a12..8326969599 --- a/ja/starter/static-files.md +++ b/ja/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: Express での静的ファイルの提供 +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: ja -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # Express での静的ファイルの提供 イメージ、CSS ファイル、JavaScript ファイルなどの静的ファイルを提供するには、Express に標準実装されている `express.static` ミドルウェア関数を使用します。 -静的アセットファイルを格納しているディレクトリーの名前を `express.static` ミドルウェア関数に渡して、ファイルの直接提供を開始します。例えば、`public` というディレクトリー内のイメージ、CSS ファイル、JavaScript ファイルを提供するには、次のコードを使用します。 +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](/{{page.lang}}/4x/api.html#express.static). + +For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`: ```js app.use(express.static('public')) @@ -40,6 +49,11 @@ app.use(express.static('files')) Express は、`express.static` ミドルウェア関数に静的ディレクトリーが設定された順序でファイルを検索します。 +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + `express.static` 関数によって提供されるファイルの仮想パスのプレフィックス (パスは実際にはファイル・システムに存在しません) を作成するには、次に示すように、静的ディレクトリーの[マウント・パスを指定](/{{ page.lang }}/4x/api.html#app.use)します。 ```js @@ -56,9 +70,13 @@ http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html ``` -ただし、`express.static` 関数に指定するパスは、`node` プロセスを起動するディレクトリーに対して相対的です。別のディレクトリーから Express アプリケーションを実行する場合は、提供するディレクトリーの絶対パスを使用する方が安全です。 +ただし、`express.static` 関数に指定するパスは、`node` プロセスを起動するディレクトリーに対して相対的です。別のディレクトリーから Express アプリケーションを実行する場合は、提供するディレクトリーの絶対パスを使用する方が安全です。 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 const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/ja/support/index.md b/ja/support/index.md index c4f5149af8..b8b5846ae9 100644 --- a/ja/support/index.md +++ b/ja/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: ja --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/ko/3x/api.md b/ko/3x/api.md old mode 100755 new mode 100644 index e5b7779cc6..db7a643be8 --- a/ko/3x/api.md +++ b/ko/3x/api.md @@ -2,25 +2,28 @@ layout: api version: 3x title: Express 3.x - API 참조 +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: ko -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x은 더 이상 유지보수되지 않습니다.** - 3.x의 알려진 또는 알려지지 않은 보안 및 성능 문제는 마지막 업데이트(2015년 8월 1일) 이후로 처리되지 않고 있습니다. 최신 버전의 Express를 사용할 것을 강력히 권장합니다. +3.x의 알려진 또는 알려지지 않은 보안 및 성능 문제는 마지막 업데이트(2015년 8월 1일) 이후로 처리되지 않고 있습니다. 최신 버전의 Express를 사용할 것을 강력히 권장합니다. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). +

    3.x API

    - {% include api/en/3x/express.md %} - {% include api/en/3x/app.md %} - {% include api/en/3x/req.md %} - {% include api/en/3x/res.md %} - {% include api/en/3x/middleware.md %} +{% include api/en/3x/express.md %} +{% include api/en/3x/app.md %} +{% include api/en/3x/req.md %} +{% include api/en/3x/res.md %} +{% include api/en/3x/middleware.md %}
    diff --git a/ko/4x/api.md b/ko/4x/api.md old mode 100755 new mode 100644 index 0ec3a549c0..778dca6f93 --- a/ko/4x/api.md +++ b/ko/4x/api.md @@ -2,18 +2,29 @@ layout: api version: 4x title: Express 4.x - API 참조 +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: ko -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +

    4.x API

    - {% include api/en/4x/express.md %} - {% include api/en/4x/app.md %} - {% include api/en/4x/req.md %} - {% include api/en/4x/res.md %} - {% include api/en/4x/router.md %} +{% capture node-version %} + +``` +Express 4.0 requires Node.js 0.10 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} + +{% include api/en/4x/express.md %} +{% include api/en/4x/app.md %} +{% include api/en/4x/req.md %} +{% include api/en/4x/res.md %} +{% include api/en/4x/router.md %}
    diff --git a/ko/5x/api.md b/ko/5x/api.md index 1ceaba2ccc..b9c9d26fa0 100644 --- a/ko/5x/api.md +++ b/ko/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - API 참조 +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: ko -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/ko/advanced/best-practice-performance.md b/ko/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 73cb675275..46dd320b3e --- a/ko/advanced/best-practice-performance.md +++ b/ko/advanced/best-practice-performance.md @@ -1,47 +1,40 @@ --- layout: page title: 프로덕션 환경에서의 Express 사용을 위한 성능 우수 사례 +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: ko -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # 프로덕션 우수 사례: 성능 및 신뢰성 -## 개요 - 이 문서에서는 프로덕션 환경에 배치된 Express 애플리케이션을 위한 성능 및 신뢰성 관련 우수 사례에 대해 논의합니다. 이 주제는 명백하게 "DevOps" 분야로 구분할 수 있으며 종래의 개발 및 운영 모두를 다룹니다. 따라서, 정보는 다음과 같은 두 개의 파트로 나뉘어 있습니다. - -* [코드에서 수행할 항목](#code) (개발 파트): - * [gzip 압축 사용](#use-gzip-compression) - * [동기식 함수 사용하지 않기](#dont-use-synchronous-functions) - * [정확한 로깅](#do-logging-correctly) - * [올바른 예외 처리](#handle-exceptions-properly) -* [환경/설정에서 수행할 항목](#env) (운영 파트): - * [NODE_ENV를 "production"으로 설정](#set-node_env-to-production) - * [앱이 자동으로 다시 시작되도록 보장](#ensure-your-app-automatically-restarts) - * [앱을 클러스터에서 실행](#run-your-app-in-a-cluster) - * [요청 결과를 캐싱](#cache-request-results) - * [로드 밸런서 사용](#use-a-load-balancer) - * [역방향 프록시 사용](#use-a-reverse-proxy) - - - -## 코드에서 수행할 항목 +- [코드에서 수행할 항목](#code) (개발 파트): + - [gzip 압축 사용](#use-gzip-compression) + - [동기식 함수 사용하지 않기](#dont-use-synchronous-functions) + - [정확한 로깅](#do-logging-correctly) + - [올바른 예외 처리](#exceptions) +- [환경/설정에서 수행할 항목](#env) (운영 파트): + - [NODE_ENV를 "production"으로 설정](#set-node_env-to-production) + - [앱이 자동으로 다시 시작되도록 보장](#ensure-your-app-automatically-restarts) + - [앱을 클러스터에서 실행](#run-your-app-in-a-cluster) + - [요청 결과를 캐싱](#cache-request-results) + - [로드 밸런서 사용](#use-a-load-balancer) + - [역방향 프록시 사용](#proxy) + +## Things to do in your code {#in-code} 애플리케이션의 성능을 향상시키기 위해서 코드를 통해 할 수 있는 몇 가지는 다음과 같습니다. - * [gzip 압축 사용](#use-gzip-compression) - * [동기식 함수 사용하지 않기](#dont-use-synchronous-functions) - * [정확한 로깅](#do-logging-correctly) - * [올바른 예외 처리](#exceptions) - +- [gzip 압축 사용](#use-gzip-compression) +- [동기식 함수 사용하지 않기](#dont-use-synchronous-functions) +- [정확한 로깅](#do-logging-correctly) +- [올바른 예외 처리](#exceptions) - ### gzip 압축 사용 Gzip 압축을 사용하면 응답 본문의 크기를 크게 줄일 수 있으며, 따라서 웹 앱의 속도를 높일 수 있습니다. Express 앱에서 gzip 압축을 사용하려면 [compression](https://www.npmjs.com/package/compression) 미들웨어를 사용하십시오. 예를 들면 다음과 같습니다. @@ -50,35 +43,31 @@ Gzip 압축을 사용하면 응답 본문의 크기를 크게 줄일 수 있으 const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` 많은 트래픽이 발생하는 프로덕션 환경의 웹사이트의 경우, 압축을 실행하는 가장 좋은 방법은 역방향 프록시 레벨에서 압축을 구현하는 것입니다([역방향 프록시 사용](#proxy) 참조). 그러한 경우에는 compression 미들웨어를 사용할 필요가 없습니다. Nginx에서 gzip 압축을 사용하는 방법에 대한 자세한 내용은 Nginx 문서의 [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html)을 참조하십시오. - - ### 동기식 함수 사용하지 않기 동기식 함수 및 메소드는 리턴될 때까지 실행 프로세스를 묶어 둡니다. 동기식 함수에 대한 한 건의 호출은 몇 마이크로초 또는 밀리초 내에 리턴될 수도 있지만, 많은 트래픽이 발생하는 웹사이트에서 이러한 동기식 호출들이 합산되면 앱의 성능이 낮아집니다. 프로덕션 환경에서는 동기식 함수의 사용을 피하십시오. Node 및 다수의 모듈은 동기식 및 비동기식 버전의 함수를 제공하지만, 프로덕션 환경에서는 항상 비동기식 버전을 사용하십시오. 동기식 함수의 사용이 정당화되는 유일한 경우는 초기 시작 시에 사용되는 경우입니다. -Node.js 4.0 이상 또는 io.js 2.1.0 이상을 사용하는 경우, `--trace-sync-io` 명령행 플래그를 사용하면 애플리케이션이 동기식 API를 사용할 때마다 경고 및 스택 추적이 출력되도록 수 있습니다. 물론, 프로덕션 환경에서 이러한 플래그를 실제로 사용해서는 안 되며, 이는 코드가 프로덕션 환경에서 사용될 준비가 되었다는 것을 보장하기 위한 것입니다. 자세한 정보는 [node 커맨드라인 옵션 문서](https://nodejs.org/api/cli.html#cli_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. 물론, 프로덕션 환경에서 이러한 플래그를 실제로 사용해서는 안 되며, 이는 코드가 프로덕션 환경에서 사용될 준비가 되었다는 것을 보장하기 위한 것입니다. 자세한 정보는 [node 커맨드라인 옵션 문서](https://nodejs.org/api/cli.html#cli_trace_sync_io)를 참조하십시오. - -### 정확한 로깅 +### Do logging correctly -일반적으로 앱은 디버깅 그리고 앱 활동 로깅(사실상 디버깅 이외의 모든 것)이라는 두 가지 이유로 인해 로깅을 실행합니다. `console.log()` 또는 `console.err()`을 사용하여 터미널에 로그 메시지를 출력하는 것이 일반적인 개발 작업 방식입니다. 그러나 대상이 터미널 또는 파일인 경우 [이들 함수는 동기식으로 작동하며](https://nodejs.org/api/console.html#console_console_1), 따라서 다른 프로그램으로 출력을 전송하는 경우가 아니라면 이러한 함수는 프로덕션 환경에 적합하지 않습니다. +일반적으로 앱은 디버깅 그리고 앱 활동 로깅(사실상 디버깅 이외의 모든 것)이라는 두 가지 이유로 인해 로깅을 실행합니다. `console.log()` 또는 `console.err()`을 사용하여 터미널에 로그 메시지를 출력하는 것이 일반적인 개발 작업 방식입니다. 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.err()`로 전송되는지 제어할 수 있습니다. 앱을 순수한 비동기식으로 유지하려면 `console.err()`을 다른 프로그램으로 전송해야 합니다. 그러나 아마도 프로덕션 단계에서 디버그를 수행할 필요는 없을 것입니다. -#### 앱 활동에 대한 로깅 - -앱 활동을 로깅하는 경우(예: 트래픽 또는 API 호출을 추적)에는 `console.log()`를 사용하는 대신 [Winston](https://www.npmjs.com/package/winston) 또는 [Bunyan](https://www.npmjs.com/package/bunyan)과 같은 로깅 라이브러리를 사용하십시오. 이 두 라이브러리에 대한 자세한 비교는 StrongLoop 블로그 게시물 [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/)을 참조하십시오. +#### 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. ### 올바른 예외 처리 @@ -86,32 +75,19 @@ Node 앱은 처리되지 않은 예외가 발생할 때 충돌이 발생합니 모든 예외를 처리하도록 보장하려면 다음의 기법을 사용하십시오. -* [try-catch 사용](#try-catch) -* [프로미스 사용](#promises) +- [try-catch 사용](#try-catch) +- [프로미스 사용](#promises) 이 주제에 대해 자세히 살펴보기 전에 먼저 Node/Express의 오류 처리, 즉 오류 우선(error-first) 콜백의 사용 및 미들웨어를 통한 오류의 전파에 대한 기본적인 사항을 이해해야 합니다. Node는 비동기식 함수로부터 오류를 리턴하기 위해 "오류 우선 콜백" 방식을 사용하며, 여기서 콜백 함수의 첫 번째 매개변수는 오류 오브젝트이고 그 후속 매개변수에 결과 데이터가 뒤따릅니다. 오류가 없음을 나타낼 때는 첫 번째 매개변수로 널(null)을 전달합니다. 의미 있는 방식으로 오류를 처리하려면 콜백 함수는 이에 맞게 오류 우선 콜백 방식을 따라야 합니다. 그리고 Express에서의 우수 사례는 next() 함수를 사용하여 미들웨어 체인을 통해 오류를 전파하는 것입니다. 오류 처리의 기본사항 대한 자세한 내용은 다음을 참조하십시오. -* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/)(StrongLoop 블로그) - -#### 수행하지 않아야 하는 항목 - -수행하지 *않아야* 할 한 가지 항목은 예외가 이벤트 루프에까지 발생할 때 생성되는 `uncaughtException` 이벤트를 청취하는 것입니다. `uncaughtException`에 대한 이벤트 리스너를 추가하면 예외가 발생하는 프로세스의 기본 작동을 변경할 수 있으며, 해당 프로세스는 예외가 발생하더라도 계속하여 실행될 것입니다. 이러한 방법은 앱에서 충돌이 발생하는 것을 방지하는 좋은 방법인 것처럼 보일 수 있지만, 처리되지 않은 예외가 발생한 후에도 앱이 계속하여 실행되면 프로세스가 불안정하고 예측할 수 없는 상태가 되므로 이러한 방법은 위험한 작업 방식이며 권장되지 않습니다. - -또한 `uncaughtException`을 사용하는 것은 [세련되지 못한 방식](https://nodejs.org/api/process.html#process_event_uncaughtexception)인 것으로 공식적으로 인식되고 있으며, 코어로부터 이러한 방식을 제거하는 방법이 [제안](https://github.com/nodejs/node-v0.x-archive/issues/2582)되어 있습니다. 따라서 `uncaughtException`을 청취하는 것은 좋은 생각이 아닙니다. 따라서 여러 프로세스 및 수퍼바이저의 사용 등을 권장하며, 오류로부터 복구되는 가장 안정적인 방법은 충돌이 발생한 후 다시 시작하는 것인 경우가 많습니다. - -[도메인](https://nodejs.org/api/domain.html)의 사용 또한 권장하지 않습니다. 일반적으로 도메인은 문제를 해결하지 못하며, 더 이상 사용되지 않는 모듈입니다. - - +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### try-catch 사용 Try-catch는 동기식 코드에서 예외를 처리하는 데 사용할 수 있는 JavaScript 언어 구조체입니다. 예를 들면, try-catch를 사용하여 아래와 같이 JSON 구문 분석 오류를 처리할 수 있습니다. -[JSHint](http://jshint.com/) 또는 [JSLint](http://www.jslint.com/)와 같은 도구를 사용하면 [정의되지 않은 변수에 대한 참조 오류](http://www.jshint.com/docs/options/#undef)와 같은 암시적인 예외를 발견하는 데 도움이 됩니다. - 아래에는 try-catch를 사용하여 잠재적인 프로세스 충돌 예외를 처리하는 예가 표시되어 있습니다. 이 미들웨어 함수는 JSON 오브젝트이자 "params"라는 이름을 갖는 조회 필드를 수락합니다. @@ -132,89 +108,70 @@ app.get('/search', (req, res) => { 그러나 try-catch는 동기식 코드에 대해서만 작동합니다. Node 플랫폼은 기본적으로 비동기식이므로(특히, 프로덕션 환경의 경우), try-catch를 통해 많은 예외를 처리할 수는 없을 것입니다. - - #### 프로미스 사용 -`then()`을 사용하는 비동기식 코드 블록 내에서는 프로미스를 통해 모든 예외(명시적 예외 및 암시적 예외 모두)를 처리할 수 있습니다. 프로미스 체인의 끝에 `.catch(next)`만 추가하면 됩니다. 예를 들면 다음과 같습니다. +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -이제 모든 비동기식 오류 및 동기식 오류는 error 미들웨어로 전파됩니다. - -그러나 주의해야 할 사항이 두 가지 있습니다. - -1. 모든 비동기식 코드는 프로미스를 리턴해야 합니다(이미터 제외). 특정한 라이브러리가 프로미스를 리턴하지 않는 경우에는 [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html)과 같은 헬퍼 함수를 사용하여 기본 오브젝트를 변환하십시오. -2. 이벤트 이미터(스트림 등)는 여전히 처리되지 않은 예외를 발생시킬 수 있습니다. 따라서 오류 이벤트를 올바르게 처리하고 있는지 확인하십시오. 예를 들면 다음과 같습니다. +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` +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. -`wrap()` 함수는 거부된 프로미스를 캐치해서 에러를 첫번째 인수로 두고 `next()`를 호출합니다. 자세한 정보는 다음을 참조하십시오. -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) +#### What not to do + +수행하지 _않아야_ 할 한 가지 항목은 예외가 이벤트 루프에까지 발생할 때 생성되는 `uncaughtException` 이벤트를 청취하는 것입니다. `uncaughtException`에 대한 이벤트 리스너를 추가하면 예외가 발생하는 프로세스의 기본 작동을 변경할 수 있으며, 해당 프로세스는 예외가 발생하더라도 계속하여 실행될 것입니다. 이러한 방법은 앱에서 충돌이 발생하는 것을 방지하는 좋은 방법인 것처럼 보일 수 있지만, 처리되지 않은 예외가 발생한 후에도 앱이 계속하여 실행되면 프로세스가 불안정하고 예측할 수 없는 상태가 되므로 이러한 방법은 위험한 작업 방식이며 권장되지 않습니다. + +또한 `uncaughtException`을 사용하는 것은 [세련되지 못한 방식](https://nodejs.org/api/process.html#process_event_uncaughtexception)인 것으로 공식적으로 인식되고 있으며, 코어로부터 이러한 방식을 제거하는 방법이 [제안](https://github.com/nodejs/node-v0.x-archive/issues/2582)되어 있습니다. 따라서 `uncaughtException`을 청취하는 것은 좋은 생각이 아닙니다. 따라서 여러 프로세스 및 수퍼바이저의 사용 등을 권장하며, 오류로부터 복구되는 가장 안정적인 방법은 충돌이 발생한 후 다시 시작하는 것인 경우가 많습니다. -프로미스를 사용한 오류 처리에 대한 자세한 정보는 다음을 참조하십시오. -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +[도메인](https://nodejs.org/api/domain.html)의 사용 또한 권장하지 않습니다. 일반적으로 도메인은 문제를 해결하지 못하며, 더 이상 사용되지 않는 모듈입니다. - +## Things to do in your environment / setup -## 환경/설정에서 수행할 항목 +{#in-environment} 앱의 성능을 향상시키기 위해서 시스템 환경에서 할 수 있는 몇 가지는 다음과 같습니다. -* [NODE_ENV를 "production"으로 설정](#set-node_env-to-production) -* [앱이 자동으로 다시 시작되도록 보장](#ensure-your-app-automatically-restarts) -* [앱을 클러스터에서 실행](#run-your-app-in-a-cluster) -* [요청 결과를 캐싱](#cache-request-results) -* [로드 밸런서 사용](#use-a-load-balancer) -* [역방향 프록시 사용](#proxy) +- [NODE_ENV를 "production"으로 설정](#set-node_env-to-production) +- [앱이 자동으로 다시 시작되도록 보장](#ensure-your-app-automatically-restarts) +- [앱을 클러스터에서 실행](#run-your-app-in-a-cluster) +- [요청 결과를 캐싱](#cache-request-results) +- [로드 밸런서 사용](#use-a-load-balancer) +- [역방향 프록시 사용](#proxy) - ### NODE_ENV를 "production"으로 설정 -NODE_ENV 환경 변수는 애플리케이션이 실행되는 환경(일반적으로 개발 환경 또는 프로덕션 환경)을 지정합니다. 성능을 향상시키기 위해 할 수 있는 가장 간단한 일 중 하나는 NODE_ENV를 "production"으로 설정하는 것입니다. +NODE_ENV 환경 변수는 애플리케이션이 실행되는 환경(일반적으로 개발 환경 또는 프로덕션 환경)을 지정합니다. One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. NODE_ENV를 "production"으로 설정하면 Express는 다음과 같이 동작합니다. -* 보기 템플리트를 캐싱. -* CSS 확장기능을 통해 생성된 CSS 파일을 캐싱. -* 더 간결한 오류 메시지를 생성. +- 보기 템플리트를 캐싱. +- CSS 확장기능을 통해 생성된 CSS 파일을 캐싱. +- 더 간결한 오류 메시지를 생성. -[테스트 결과,](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) NODE_ENV를 "production"으로 설정하기만 해도 앱 성능이 3배 향상되는 것으로 나타났습니다! +[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! 특정한 환경을 위한 코드를 작성하는 경우, `process.env.NODE_ENV`를 통해 NODE_ENV의 값을 확인할 수 있습니다. 환경 변수의 값을 확인하는 작업은 성능 저하를 유발하므로 이러한 작업은 낮은 빈도로 실행해야 한다는 점에 주의하십시오. -일반적으로 개발 시에는, 예를 들면 `export` 또는 `.bash_profile` 파일을 이용하여 대화식 쉘에서 환경 변수를 설정할 수 있습니다. 그러나 일반적으로 프로덕션 서버에서 이러한 방식을 이용해서는 안 되며, 대신 해당 OS의 init 시스템(systemd 또는 Upstart)을 사용해야 합니다. 다음 섹션에서 일반적인 init 시스템의 사용에 대한 자세한 내용을 확인할 수 있지만, NODE_ENV를 설정하는 것은 성능에 매우 중요하므로(또한 쉽게 실행할 수 있으므로) NODE_ENV의 설정을 여기서 강조합니다. - -Upstart를 이용하는 경우, 작업 파일에 `env` 키워드를 사용하십시오. 예를 들면 다음과 같습니다. - - -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` - -자세한 정보는 [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables)를 참조하십시오. +일반적으로 개발 시에는, 예를 들면 `export` 또는 `.bash_profile` 파일을 이용하여 대화식 쉘에서 환경 변수를 설정할 수 있습니다. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). 다음 섹션에서 일반적인 init 시스템의 사용에 대한 자세한 내용을 확인할 수 있지만, NODE_ENV를 설정하는 것은 성능에 매우 중요하므로(또한 쉽게 실행할 수 있으므로) NODE_ENV의 설정을 여기서 강조합니다. systemd를 이용하는 경우, 유닛 파일에 `Environment` 지시문을 사용하십시오. 예를 들면 다음과 같습니다. @@ -223,17 +180,14 @@ systemd를 이용하는 경우, 유닛 파일에 `Environment` 지시문을 사 Environment=NODE_ENV=production ``` -자세한 정보는 [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html)를 참조하십시오. - -StrongLoop Process Manager를 이용하는 경우에는 [StrongLoop PM을 서비스로 설치할 때 환경 변수를 설정](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables)할 수도 있습니다. +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). - ### 앱이 자동으로 다시 시작되도록 보장 프로덕션 환경에서 애플리케이션이 오프라인 상태가 되어서는 절대로 안 됩니다. 따라서 앱에서 충돌이 발생하거나 서버 자체에서 충돌이 발생하는 경우 모두 앱이 다시 시작되도록 해야 합니다. 이러한 일 중 어느 하나라도 발생하지 않는 것이 바람직하지만, 현실적으로는 다음과 같은 방법을 통해 이 두 가지 만일의 사태를 처리해야 합니다. -* 앱에서 충돌이 발생하는 경우 프로세스 관리자를 사용하여 앱(및 Node)을 다시 시작. -* OS에서 충돌이 발생하는 경우 해당 OS에서 제공하는 init 시스템을 사용하여 프로세스 관리자를 다시 시작. 프로세스 관리자 없이도 init 시스템을 사용할 수 있습니다. +- 앱에서 충돌이 발생하는 경우 프로세스 관리자를 사용하여 앱(및 Node)을 다시 시작. +- OS에서 충돌이 발생하는 경우 해당 OS에서 제공하는 init 시스템을 사용하여 프로세스 관리자를 다시 시작. 프로세스 관리자 없이도 init 시스템을 사용할 수 있습니다. 처리되지 않은 예외가 발생하는 경우 Node 애플리케이션에서 충돌이 발생합니다. 가장 먼저 해야 할 일은 앱의 테스트가 잘 이루어지도록 하고 앱이 모든 예외를 처리하도록 하는 것입니다(자세한 내용은 [올바른 예외 처리](#exceptions)를 참조). 그러나 하나의 안전 장치로서, 앱에서 충돌이 발생하는 경우에 앱이 자동으로 다시 시작되도록 하는 메커니즘을 실행하십시오. @@ -243,54 +197,35 @@ StrongLoop Process Manager를 이용하는 경우에는 [StrongLoop PM을 서비 앱에서 충돌이 발생할 때 앱이 다시 시작되도록 하는 것 이외에도, 프로세스 관리자를 통해 다음을 실행할 수 있습니다. -* 런타임 성능 및 자원 소비에 대한 통찰력을 획득. -* 성능 향상을 위해 설정을 동적으로 수정. -* 클러스터링을 제어(StrongLoop PM 및 pm2). - -가장 널리 사용되는 Node용 프로세스 관리자는 다음과 같습니다. - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -위 세 개의 프로세스 관리자에 대한 기능별 비교를 확인하려면 [http://strong-pm.io/compare/](http://strong-pm.io/compare/)를 참조하십시오. - -이러한 프로세스 관리자 중 어느 하나를 사용하면, 때때로 앱에서 충돌이 발생하는 경우에도, 충분히 앱이 지속적으로 작동하도록 할 수 있습니다. +- 런타임 성능 및 자원 소비에 대한 통찰력을 획득. +- 성능 향상을 위해 설정을 동적으로 수정. +- Control clustering (pm2). -그러나 StrongLoop PM은 구체적으로 프로덕션 배치 환경을 대상으로 하는 여러 기능을 갖추고 있습니다. StrongLoop PM 및 관련된 StrongLoop 도구를 사용하면 다음을 실행할 수 있습니다. - -* 로컬 환경에서 앱을 빌드 및 패키징한 후 프로덕션 시스템에 안전하게 앱을 배치. -* 어떠한 이유로라도 앱에서 충돌이 발생할 경우 앱을 자동으로 다시 시작. -* 클러스터를 원격으로 관리. -* CPU 프로파일 및 힙 스냅샷을 확인하여 성능을 최적화하고 메모리 누수를 진단. -* 애플리케이션에 대한 성능 지표를 확인. -* Nginx 로드 밸런서에 대한 내장된 제어 기능을 통해 여러 호스트로 쉽게 확장. - -아래에 설명된 것과 같이, init 시스템을 이용해 StrongLoop PM을 운영 체제 시스템으로서 설치하면 StrongLoop PM은 시스템이 다시 시작될 때 자동으로 다시 시작됩니다. 따라서 애플리케이션 프로세스 및 클러스터는 항상 작동 상태를 유지할 수 있습니다. +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 시스템 사용 -신뢰성의 다음 단계는 서버가 다시 시작될 때 애플리케이션이 다시 시작되도록 하는 것입니다. 시스템은 여전히 여러 이유로 작동이 중단될 수 있습니다. 서버에서 충돌이 발생할 때 앱이 다시 시작되도록 하려면 OS에 내장된 init 시스템을 사용하십시오. 현재 사용되고 있는 두 가지 주요 init 시스템은 [systemd](https://wiki.debian.org/systemd) 및 [Upstart](http://upstart.ubuntu.com/)입니다. +신뢰성의 다음 단계는 서버가 다시 시작될 때 애플리케이션이 다시 시작되도록 하는 것입니다. 시스템은 여전히 여러 이유로 작동이 중단될 수 있습니다. 서버에서 충돌이 발생할 때 앱이 다시 시작되도록 하려면 OS에 내장된 init 시스템을 사용하십시오. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Express 앱에 init 시스템을 사용하는 데에는 다음과 같은 두 가지 방법이 있습니다. -* 프로세스 관리자에서 앱을 실행한 후, init 시스템을 통해 프로세스 관리자를 서비스로서 설치하십시오. 프로세스 관리자는 앱에서 충돌이 발생할 때 앱을 자동으로 시작하고, init 시스템은 OS가 다시 시작될 때 프로세스 관리자를 다시 시작할 것입니다. 이러한 접근법은 권장되는 접근법입니다. -* init 시스템을 통해 직접 앱(및 Node)을 실행하십시오. 이 방법은 조금 더 간편하지만, 프로세스 관리자의 사용을 통한 추가적인 이점을 얻을 수 없습니다. +- 프로세스 관리자에서 앱을 실행한 후, init 시스템을 통해 프로세스 관리자를 서비스로서 설치하십시오. 프로세스 관리자는 앱에서 충돌이 발생할 때 앱을 자동으로 시작하고, init 시스템은 OS가 다시 시작될 때 프로세스 관리자를 다시 시작할 것입니다. 이러한 접근법은 권장되는 접근법입니다. +- init 시스템을 통해 직접 앱(및 Node)을 실행하십시오. 이 방법은 조금 더 간편하지만, 프로세스 관리자의 사용을 통한 추가적인 이점을 얻을 수 없습니다. ##### Systemd Systemd는 Linux용 시스템 및 서비스 관리자입니다. 대부분의 주요 Linux 배포판은 systemd를 기본 init 시스템으로 도입했습니다. -systemd 서비스 구성 파일은 *유닛 파일(unit file)*로 불리며, 파일 이름이 .service로 끝납니다. Node 앱을 직접 관리하기 위한 유닛 파일의 예는 다음과 같습니다(굵은체로 표시된 텍스트를 해당 시스템 및 앱에 대한 값으로 바꾸십시오). +systemd 서비스 구성 파일은 \*유닛 파일(unit file)\*로 불리며, 파일 이름이 .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] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -312,103 +247,14 @@ Restart=always [Install] WantedBy=multi-user.target ``` -systemd에 대한 자세한 정보는 [systemd 참조 자료(man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)를 참조하십시오. - -##### systemd의 서비스로서의 StrongLoop PM - -StrongLoop Process Manager는 쉽게 systemd의 서비스로서 설치할 수 있습니다. StrongLoop PM을 systemd의 서비스로서 설치한 후 서버가 다시 시작되면 StrongLoop PM이 자동으로 다시 시작되며, 이후 StrongLoop PM이 관리 중인 모든 앱이 다시 시작됩니다. - -StrongLoop PM을 systemd의 서비스로서 설치하는 방법은 다음과 같습니다. - -```bash -$ sudo sl-pm-install --systemd -``` - -이후 다음과 같이 서비스를 시작하십시오. - -```bash -$ sudo sl-pm-install --systemd -``` - -자세한 정보는 [Setting up a production host(StrongLoop 문서)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10)를 참조하십시오. - -##### Upstart - -Upstart는 시스템 시작 시에 태스크 및 서비스를 시작하고, 시스템 종료 시에 태스크 및 서비스를 중지하고, 태스크 및 서비스를 감시할 수 있는 시스템 도구이며, 여러 Linux 배포판에서 사용할 수 있습니다. Express 앱 또는 프로세스 관리자를 서비스로서 구성하면, Express 앱 또는 프로세스 관리자에서 충돌이 발생할 때 Upstart가 Express 앱 또는 프로세스 관리자를 자동으로 다시 시작할 수 있습니다. - -Upstart 서비스는 파일 이름이 `.conf`로 끝나는 작업 구성 파일("작업(job)"으로도 불림)에 정의됩니다. 다음 예는 기본 파일의 위치가 `/projects/myapp/index.js`인 "myapp"이라는 이름의 앱에 대해 "myapp"이라는 이름의 작업을 작성하는 방법을 나타냅니다. - -다음의 내용이 입력된 `myapp.conf`라는 이름의 파일을 `/etc/init/`에 작성하십시오(굵은체로 표시된 텍스트를 해당 시스템 및 앱에 대한 값으로 바꾸십시오). - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -참고: 이 스크립트를 실행하려면 Ubuntu 12.04-14.10에서 지원되는 Upstart 1.4 이상이 필요합니다. - -이 작업은 시스템이 시작될 때 실행되도록 구성되었으므로 앱은 운영 체제와 함께 시작되며, 앱에서 충돌이 발생하거나 시스템의 작동이 중단되는 경우 앱이 자동으로 다시 시작됩니다. - -앱을 자동으로 다시 시작하는 것 이외에도, Upstart를 이용하면 다음과 같은 명령을 사용할 수 있습니다. - -* `start myapp` – 앱을 시작 -* `restart myapp` – 앱을 다시 시작 -* `stop myapp` – 앱을 중지 - -Upstart에 대한 자세한 정보는 [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook)를 참조하십시오. - -##### Upstart의 서비스로서의 StrongLoop PM - -StrongLoop Process Manager는 쉽게 Upstart의 서비스로 설치할 수 있습니다. StrongLoop PM을 Upstart의 서비스로 설치한 후 서버가 다시 시작되면 StrongLoop PM이 자동으로 다시 시작되며, 이후 StrongLoop PM이 관리 중인 모든 앱이 다시 시작됩니다. - -StrongLoop PM을 Upstart 1.4의 서비스로서 설치하는 방법은 다음과 같습니다. - - -```bash -$ sudo sl-pm-install -``` - -이후 다음과 같이 서비스를 실행하십시오. - - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -참고: Upstart 1.4를 지원하지 않는 시스템에서는 약간 다른 명령이 사용됩니다. 자세한 정보는 [Setting up a production host(StrongLoop 문서)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10)를 참조하십시오. +systemd에 대한 자세한 정보는 [systemd 참조 자료(man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)를 참조하십시오. - ### 앱을 클러스터에서 실행 멀티코어 시스템에서는 프로세스 클러스터를 실행하여 Node 앱의 성능을 여러 배 높일 수 있습니다. 클러스터는 해당 앱의 인스턴스를 여러 개 실행하여(이상적인 경우 각 CPU 코어에서 하나의 인스턴스를 실행) 인스턴스들 사이에서 로드 및 태스크를 분배합니다. - +![Balancing between application instances using the cluster API](/images/clustering.png) 중요: 앱 인스턴스들은 별도의 프로세스로서 실행되므로 이러한 인스턴스들은 동일한 메모리 공간을 공유하지 않습니다. 즉, 오브젝트는 해당 앱의 각 인스턴스에 대한 로컬 오브젝트입니다. 따라서 애플리케이션 코드 내의 상태를 유지보수할 수 없습니다. 그러나 [Redis](http://redis.io/)와 같은 인메모리 데이터 저장소를 사용하면 세션과 관련된 데이터 및 상태를 저장할 수 있습니다. 이러한 주의사항은 기본적으로 여러 프로세스를 이용한 클러스터링 또는 여러 대의 실제 서버를 이용한 클러스터링 등 모든 형태의 수평적 확장에 적용됩니다. @@ -416,25 +262,11 @@ $ sudo /sbin/initctl start strong-pm #### Node의 cluster 모듈 사용 -Node의 [cluster 모듈](https://nodejs.org/docs/latest/api/cluster.html)을 사용하면 클러스터링이 가능합니다. 이러한 클러스터링을 통해 마스터 프로세스는 여러 작업자 프로세스를 복제생성하고, 수신되는 연결을 여러 작업자 사이에서 분배할 수 있습니다. 그러나 이러한 모듈을 직접 사용하는 대신, 이를 자동으로 실행하는 여러 도구 중 하나를 사용하는 것이 훨씬 더 좋습니다. 이러한 도구의 예로는 [node-pm](https://www.npmjs.com/package/node-pm) 또는 [cluster-service](https://www.npmjs.com/package/cluster-service)가 있습니다. - -#### StrongLoop PM 사용 - -애플리케이션을 StrongLoop Process Manager(PM)에 배치하면, 애플리케이션 코드를 수정하지 *않고도* 클러스터링을 활용할 수 있습니다. - -StrongLoop Process Manager(PM)가 애플리케이션으로서 실행되면, StrongLoop PM은 시스템의 CPU 코어 수와 같은 수의 작업자를 갖는 클러스터 내에서 자신을 실행합니다. 사용자는 앱을 중지시키지 않고도 slc 명령행 도구를 이용해 수동으로 클러스터 내의 작업자 프로세스의 수를 변경할 수 있습니다. - -예를 들어 prod.foo.com에 앱을 배치했으며 StrongLoop PM이 포트 8701(기본값)에서 청취하는 경우를 가정하면, 다음과 같이 slc를 이용해 클러스터의 크기를 8로 설정할 수 있습니다. - -```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 -``` - -StrongLoop PM을 이용한 클러스터링에 대한 자세한 정보는 StrongLoop 문서 내의 [Clustering](https://docs.strongloop.com/display/SLC/Clustering)을 참조하십시오. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). 이러한 클러스터링을 통해 마스터 프로세스는 여러 작업자 프로세스를 복제생성하고, 수신되는 연결을 여러 작업자 사이에서 분배할 수 있습니다. #### PM2 사용 -애플리케이션을 PM2에 배치하면, 애플리케이션 코드를 수정하지 *않고도* 클러스터링을 활용할 수 있습니다. 먼저 여러분의 [애플리케이션이 stateless인지](http://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) 확실하게 해야합니다. 어떠한 로컬 데이터도 프로세스에 저장되지 않아야 합니다. (세션이나 웹소켓 같은 것들 말입니다). +애플리케이션을 PM2에 배치하면, 애플리케이션 코드를 수정하지 _않고도_ 클러스터링을 활용할 수 있습니다. 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` 커맨드라인 명령을 이용해 클러스터에 있는 프로세스의 수를 직접 바꿀 수도 있습니다. @@ -442,9 +274,9 @@ PM2로 애플리케이션을 실행하고 있을 때, 특정한 수의 인스턴 ```bash # Start 4 worker processes -$ pm2 start app.js -i 4 +$ pm2 start npm --name my-app -i 4 -- start # Auto-detect number of available CPUs and start that many worker processes -$ pm2 start app.js -i max +$ pm2 start npm --name my-app -i max -- start ``` 이 수는 PM2 프로세스 파일 (`ecosystem.config.js`나 그와 유사한 파일) 안의 `exec_mode`를 `cluster`나 `instances`를 설정해서 수정될 수 있습니다. @@ -453,37 +285,29 @@ $ pm2 start app.js -i max ```bash # Add 3 more workers -$ pm2 scale app +3 +$ pm2 scale my-app +3 # Scale to a specific number of workers -$ pm2 scale app 2 +$ pm2 scale my-app 2 ``` PM2의 클러스터링에 관한 추가 정보는 PM2 문서의 [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/)를 참고해주세요. - ### 요청 결과를 캐싱 프로덕션 환경 내에서의 성능을 향상시키기 위한 또 다른 전략은 요청의 결과를 캐싱하여 앱이 동일한 요청을 반복적으로 제공하는 작업을 반복하지 않도록 하는 것입니다. -[Varnish](https://www.varnish-cache.org/) 또는 [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/)([Nginx Caching](https://serversforhackers.com/nginx-caching/) 또한 참조)와 같은 캐싱 서버를 이용하면 앱의 속도 및 성능을 크게 향상시킬 수 있습니다. - +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. - ### 로드 밸런서 사용 앱의 최적화 수준에 상관없이, 하나의 인스턴스는 제한된 양의 로드 및 트래픽만을 처리할 수 있습니다. 앱을 확장하는 방법 중 하나는 해당 앱의 인스턴스를 여러 개 실행하고 로드 밸런서를 통해 트래픽을 분배하는 것입니다. 로드 밸런서를 설정하면 앱의 성능 및 속도를 향상시킬 수 있으며, 하나의 인스턴스를 이용할 때보다 훨씬 더 높은 수준으로 확장할 수 있습니다. -로드 밸런서는 일반적으로 여러 애플리케이션 인스턴스 및 서버에 대한 트래픽을 오케스트레이션하는 역방향 프록시입니다. [Nginx](http://nginx.org/en/docs/http/load_balancing.html) 또는 [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts)를 이용하면 앱에 대한 로드 밸런서를 쉽게 설정할 수 있습니다. - -로드 밸런싱을 이용하는 경우, 특정한 세션 ID와 연관된 요청이 해당 요청을 발생시킨 프로세스에 연결되도록 해야 할 수도 있습니다. 이러한 경우는 *세션 선호도(session affinity)* 또는 *스티키 세션(sticky session)*으로 알려져 있으며, 세션 데이터를 위해 Redis와 같은 데이터 저장소를 사용하는 위의 제안을 통해 처리할 수도 있습니다(애플리케이션에 따라 다름). 토론을 위해서는 [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/)를 참조하십시오. - -#### Nginx 로드 밸런서와 함께 StrongLoop PM 사용 +로드 밸런서는 일반적으로 여러 애플리케이션 인스턴스 및 서버에 대한 트래픽을 오케스트레이션하는 역방향 프록시입니다. 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). -[StrongLoop Process Manager](http://strong-pm.io/)는 Nginx Controller와 통합될 수 있으며, 이를 통해 여러 호스트로 이루어진 프로덕션 환경 구성을 쉽게 구성할 수 있습니다. 자세한 정보는 [Scaling to multiple servers](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers)(StrongLoop 문서)를 참조하십시오. - +로드 밸런싱을 이용하는 경우, 특정한 세션 ID와 연관된 요청이 해당 요청을 발생시킨 프로세스에 연결되도록 해야 할 수도 있습니다. 이러한 경우는 _세션 선호도(session affinity)_ 또는 \*스티키 세션(sticky session)\*으로 알려져 있으며, 세션 데이터를 위해 Redis와 같은 데이터 저장소를 사용하는 위의 제안을 통해 처리할 수도 있습니다(애플리케이션에 따라 다름). 토론을 위해서는 [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/)를 참조하십시오. ### 역방향 프록시 사용 역방향 프록시는 웹 앱의 프론트에 위치하며, 요청이 앱으로 전달되도록 할 뿐만 아니라 요청에 대한 지원 연산을 수행합니다. 이는 오류 페이지, 압축, 캐싱, 파일 제공, 로드 밸런싱 및 기타 여러 작업을 처리할 수 있습니다. -애플리케이션 상태를 알아야 할 필요가 없는 태스크를 역방향 프록시로 이양하면 Express는 더 적은 자원을 차지하게 되어 특성화된 애플리케이션 태스크를 수행할 수 있습니다. 따라서 프로덕션 환경에서는 [Nginx](https://www.nginx.com/) 또는 [HAProxy](http://www.haproxy.org/)와 같은 역방향 프록시 뒤에서 Express를 실행할 것을 권장합니다. +애플리케이션 상태를 알아야 할 필요가 없는 태스크를 역방향 프록시로 이양하면 Express는 더 적은 자원을 차지하게 되어 특성화된 애플리케이션 태스크를 수행할 수 있습니다. 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. diff --git a/ko/advanced/best-practice-security.md b/ko/advanced/best-practice-security.md old mode 100755 new mode 100644 index b6d34ec7cc..c7e82f9d0c --- a/ko/advanced/best-practice-security.md +++ b/ko/advanced/best-practice-security.md @@ -1,75 +1,117 @@ --- layout: page title: 프로덕션 환경의 Express를 위한 보안 우수 사례 +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: ko -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # 프로덕션 우수 사례: 보안 ## 개요 -__"프로덕션 (production)"__ 이라는 용어는 소프트웨어 라이프사이클 중 애플리케이션 또는 API가 최종 사용자 또는 소비자에게 정식으로 제공되는 단계를 말합니다. 이와 반대로 *"개발(development)"* 단계에서는 아직 코드가 활발하게 작성 및 테스트되며 애플리케이션은 외부 액세스에 개방되지 않습니다. 이에 대응하는 시스템 환경은 각각 *프로덕션* 환경 및 *개발* 환경이라고 부릅니다. +**"프로덕션 (production)"** 이라는 용어는 소프트웨어 라이프사이클 중 애플리케이션 또는 API가 최종 사용자 또는 소비자에게 정식으로 제공되는 단계를 말합니다. 이와 반대로 _"개발(development)"_ 단계에서는 아직 코드가 활발하게 작성 및 테스트되며 애플리케이션은 외부 액세스에 개방되지 않습니다. 이에 대응하는 시스템 환경은 각각 _프로덕션_ 환경 및 _개발_ 환경이라고 부릅니다. 개발 환경 및 프로덕션 환경은 일반적으로 서로 다르게 설정되며 두 환경의 요구사항은 크게 다릅니다. 개발 환경에서는 좋은 것일지라도 프로덕션 환경에서는 허용되지 않을 수도 있습니다. 예를 들면, 개발 환경에서는 디버깅을 위해 상세한 오류 로깅이 선호될 수 있지만, 이러한 행동은 프로덕션 환경에서 보안 우려사항이 될 수 있습니다. 그리고 개발 환경에서는 확장성, 신뢰성 및 성능에 대해 걱정할 필요가 없지만, 이러한 요인들은 프로덕션 환경에서 매우 중요해집니다. -{% include admonitions/note.html content="Express의 보안 취약점을 발견하신것 같다면, -[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures)를 따라주십시오. -" %} +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} 이 문서에서는 프로덕션 환경에 배치된 Express 애플리케이션을 위한 몇 가지 보안 우수 사례에 대해 논의합니다. -- [더 이상 사용되지 않거나 취약성이 있는 버전의 Express 사용 중지](#dont-use-deprecated-or-vulnerable-versions-of-express) -- [TLS 사용](#use-tls) -- [Helmet 사용](#use-helmet) -- [쿠키를 안전하게 사용](#use-cookies-securely) -- [인증 체계에 대한 브루스 포트 공격 방지](#prevent-brute-force-attacks-against-authorization) -- [종속 항목이 안전한지 확인](#ensure-your-dependencies-are-secure) -- [그 외의 알려져 있는 취약점 회피](#avoid-other-known-vulnerabilities) -- [추가적인 고려사항](#additional-considerations) +- [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) + - [TLS 사용](#use-tls) + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [Helmet 사용](#use-helmet) + - [Reduce fingerprinting](#reduce-fingerprinting) + - [쿠키를 안전하게 사용](#use-cookies-securely) + - + - [ieNoOpen](https://github.com/helmetjs/ienoopen)은 IE8 이상에 대해 `X-Download-Options`를 설정합니다. + - [인증 체계에 대한 브루스 포트 공격 방지](#prevent-brute-force-attacks-against-authorization) + - [종속 항목이 안전한지 확인](#ensure-your-dependencies-are-secure) + - [그 외의 알려져 있는 취약점 회피](#avoid-other-known-vulnerabilities) + - [추가적인 고려사항](#additional-considerations) - ## 더 이상 사용되지 않거나 취약성이 있는 버전의 Express를 사용 중지 -Express 2.x 및 3.x에 대한 유지보수는 더 이상 이루어지지 않습니다. 이러한 버전에서의 보안 및 성능 문제는 수정되지 않습니다. 이러한 버전은 사용하지 마십시오! 아직 버전 4로 이전하지 않은 경우에는 [마이그레이션 안내서](/{{ page.lang }}/guide/migrating-4.html)를 따르십시오. +Express 2.x 및 3.x에 대한 유지보수는 더 이상 이루어지지 않습니다. 이러한 버전에서의 보안 및 성능 문제는 수정되지 않습니다. 이러한 버전은 사용하지 마십시오! 아직 버전 4로 이전하지 않은 경우에는 [마이그레이션 안내서](/{{ page.lang }}/guide/migrating-4.html)를 따르십시오. 또한 [보안 업데이트 페이지](/{{ page.lang }}/advanced/security-updates.html)의 목록에 포함된 취약성 있는 Express 버전을 사용하고 있지 않은지 확인하십시오. 취약성 있는 Express 버전을 사용하고 있는 경우에는 안정적인 릴리스 중 하나로 업데이트해야 하며, 가능하면 최신 버전으로 업데이트하는 것이 좋습니다. - - ## TLS 사용 앱이 민감한 데이터를 다루거나 전송하는 경우에는 [전송 계층 보안](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)에 취약합니다. -여러분은 SSL(Secure Socket Layer) 암호화에 익숙할 것입니다. [TLS는 단순히 SSL이 다음 단계로 발전된 형태입니다](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). 즉, 이전에 SSL을 사용했다면 TLS로의 업그레이드를 고려해야 합니다. 일반적으로 TLS의 처리를 위해서는 Nginx를 권장합니다. Nginx(및 기타 서버)에서 TLS를 구성하는 방법에 대한 좋은 참조 자료를 확인하려면 [Recommended Server Configurations(Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations)를 참조하십시오. +여러분은 SSL(Secure Socket Layer) 암호화에 익숙할 것입니다. [TLS는 단순히 SSL이 다음 단계로 발전된 형태입니다](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). 즉, 이전에 SSL을 사용했다면 TLS로의 업그레이드를 고려해야 합니다. 일반적으로 TLS의 처리를 위해서는 Nginx를 권장합니다. Nginx(및 기타 서버)에서 TLS를 구성하는 방법에 대한 좋은 참조 자료를 확인하려면 [Recommended Server Configurations(Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations)를 참조하십시오. 또한 무료 TLS 인증서를 얻기 위한 편리한 도구 중 하나는 [Internet Security Research Group(ISRG)](https://letsencrypt.org/isrg/)이 제공하는 무료의 자동 개방형 인증 기관(CA)인 [Let's Encrypt](https://letsencrypt.org/about/)입니다. - +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## Helmet 사용 [Helmet](https://www.npmjs.com/package/helmet)을 이용하면 HTTP 헤더를 적절히 설정하여 몇 가지 잘 알려진 웹 취약성으로부터 앱을 보호할 수 있습니다. -사실 Helmet은 보안 관련 HTTP 헤더를 설정하는 다음과 같은 더 작은 크기의 미들웨어 함수 9개의 모음입니다. +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: + +- `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 +- `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 +- `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 -* [csp](https://github.com/helmetjs/csp)는 `Content-Security-Policy` 헤더를 설정하여 XSS(Cross-site scripting) 공격 및 기타 교차 사이트 인젝션을 예방합니다. -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by)는 `X-Powered-By` 헤더를 제거합니다. -* [hsts](https://github.com/helmetjs/hsts)는 서버에 대한 안전한(SSL/TLS를 통한 HTTP) 연결을 적용하는 `Strict-Transport-Security` 헤더를 설정합니다. -* [ieNoOpen](https://github.com/helmetjs/ienoopen)은 IE8 이상에 대해 `X-Download-Options`를 설정합니다. -* [noCache](https://github.com/helmetjs/nocache)는 `Cache-Control` 및 Pragma 헤더를 설정하여 클라이언트 측에서 캐싱을 사용하지 않도록 합니다. -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype)는 `X-Content-Type-Options` 를 설정하여, 선언된 콘텐츠 유형으로부터 벗어난 응답에 대한 브라우저의 MIME 가로채기를 방지합니다. -* [frameguard](https://github.com/helmetjs/frameguard)는 `X-Frame-Options` 헤더를 설정하여 [clickjacking](https://www.owasp.org/index.php/Clickjacking)에 대한 보호를 제공합니다. -* [xssFilter](https://github.com/helmetjs/x-xss-protection)는 `X-XSS-Protection`을 설정하여 대부분의 최신 웹 브라우저에서 XSS(Cross-site scripting) 필터를 사용하도록 합니다. +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. 다른 모든 모듈처럼 Helmet은 다음과 같이 설치할 수 있습니다. ```bash -$ npm install --save helmet +$ npm install helmet ``` -이후 코드에서 Helmet을 사용하는 방법은 다음과 같습니다. +Then to use it in your code: ```js // ... @@ -80,40 +122,70 @@ app.use(helmet()) // ... ``` -### 적어도 X-Powered-By 헤더는 사용하지 않도록 설정 +## Reduce fingerprinting -Helmet의 사용을 원치 않는 경우에는 적어도 `X-Powered-By` 헤더를 사용하지 마십시오. 공격자는 이 헤더(기본적으로 사용하도록 설정되어 있음)를 이용해 Express를 실행하는 앱을 발견한 후 특정한 대상에 대한 공격을 실행할 수 있습니다. +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. 따라서 우수 사례는 다음과 같이 `app.disable()` 메소드를 이용해 이 헤더를 끄는 것입니다. - ```js app.disable('x-powered-by') ``` -`helmet.js`를 사용하는 경우에는 사용자를 대신하여 `helmet.js`가 위의 작업을 실행합니다. +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} -{% include admonitions/note.html content="`X-Powered-By header`를 비활성화하는 행위는 고수준의 공격자가 앱이 Express를 사용하고 있는지 확인하는 걸 막을 수 없습니다. 일반적인 취약점은 막을지 모르지만, 앱이 Express를 사용하고 있는지 알아내는 다른 방법은 많이 있습니다. "%} +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` - ## 쿠키를 안전하게 사용 쿠키로 인해 앱이 악용에 노출되지 않도록 하기 위해 기본 세션 쿠키 이름을 사용하지 말고 쿠키 보안 옵션을 적절히 설정하십시오. 두 개의 기본 미들웨어 쿠키 세션 모듈은 다음과 같습니다. -* [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` 미들웨어 대체). +- [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` 미들웨어 대체). -이 두 모듈의 주요 차이점은 쿠키 세션 데이터를 저장하는 방식입니다. [express-session](https://www.npmjs.com/package/express-session) 미들웨어는 세션 데이터를 서버에 저장하며, 쿠키 자체에는 세션 데이터가 아니라 세션 ID만 저장됩니다. 기본적으로 express-session은 인메모리 스토리지를 이용하며, 프로덕션 환경용으로 설계되지 않았습니다. 프로덕션 환경에서는 확장 가능한 session-store를 설정해야 합니다. [호환 가능한 세션 스토어](https://github.com/expressjs/session#compatible-session-stores)의 목록을 참조하십시오. +이 두 모듈의 주요 차이점은 쿠키 세션 데이터를 저장하는 방식입니다. [express-session](https://www.npmjs.com/package/express-session) 미들웨어는 세션 데이터를 서버에 저장하며, 쿠키 자체에는 세션 데이터가 아니라 세션 ID만 저장됩니다. 기본적으로 express-session은 인메모리 스토리지를 이용하며, 프로덕션 환경용으로 설계되지 않았습니다. 프로덕션 환경에서는 확장 가능한 session-store를 설정해야 합니다. [호환 가능한 세션 스토어](https://github.com/expressjs/session#compatible-session-stores)의 목록을 참조하십시오. -이와 반대로 [cookie-session](https://www.npmjs.com/package/cookie-session) 미들웨어는 쿠키 기반의 스토리지를 구현하며, 하나의 세션 키가 아니라 세션 전체를 쿠키에 직렬화합니다. cookie-session은 세션 데이터의 크기가 상대적으로 작으며 (오브젝트가 아닌) 원시 값으로 쉽게 인코딩 가능할 때에만 사용하십시오. 브라우저는 하나의 쿠키당 4,096바이트 이상을 지원하도록 되어 있지만, 한계를 초과하지 않도록 보장하려면 하나의 도메인당 4,093바이트의 크기를 초과하지 마십시오. 또한, 클라이언트에서 쿠키 데이터를 볼 수 있으므로, 쿠키 데이터를 안전하게 또는 모호하게 유지해야 할 이유가 있는 경우에는 express-session을 선택하는 것이 더 나을 수 있습니다. +이와 반대로 [cookie-session](https://www.npmjs.com/package/cookie-session) 미들웨어는 쿠키 기반의 스토리지를 구현하며, 하나의 세션 키가 아니라 세션 전체를 쿠키에 직렬화합니다. cookie-session은 세션 데이터의 크기가 상대적으로 작으며 (오브젝트가 아닌) 원시 값으로 쉽게 인코딩 가능할 때에만 사용하십시오. 브라우저는 하나의 쿠키당 4,096바이트 이상을 지원하도록 되어 있지만, 한계를 초과하지 않도록 보장하려면 하나의 도메인당 4,093바이트의 크기를 초과하지 마십시오. 또한, 클라이언트에서 쿠키 데이터를 볼 수 있으므로, 쿠키 데이터를 안전하게 또는 모호하게 유지해야 할 이유가 있는 경우에는 express-session을 선택하는 것이 더 나을 수 있습니다. -### 기본 세션 쿠키 이름을 사용하지 않음 +### 기본 세션 쿠키 이름을 사용하지 않음 -기본 세션 쿠키 이름을 사용하면 앱을 공격에 노출시킬 수 있습니다. 이로 인해 제기되는 보안 문제는 `X-Powered-By`와 유사하며, 잠재적인 공격자는 이를 이용해 서버의 지문을 채취한 후 이에 따라 공격 대상을 설정할 수 있습니다. +기본 세션 쿠키 이름을 사용하면 앱을 공격에 노출시킬 수 있습니다. 이로 인해 제기되는 보안 문제는 `X-Powered-By`와 유사하며, 잠재적인 공격자는 이를 이용해 서버의 지문을 채취한 후 이에 따라 공격 대상을 설정할 수 있습니다. -이러한 문제점을 피하려면 일반적인 쿠키 이름을 사용하십시오. 예를 들면 [express-session](https://www.npmjs.com/package/express-session) 미들웨어를 이용해 다음과 같이 하십시오. +다음에는 [cookie-session](https://www.npmjs.com/package/cookie-session) 미들웨어를 사용한 예가 표시되어 있습니다. ```js const session = require('express-session') @@ -128,13 +200,13 @@ app.use(session({ 다음과 같은 쿠키 옵션을 설정하여 보안을 강화하십시오. -* `secure` - 브라우저가 HTTPS를 통해서만 쿠키를 전송하도록 합니다. -* `httpOnly` - 쿠키가 클라이언트 JavaScript가 아닌 HTTP(S)를 통해서만 전송되도록 하며, 이를 통해 XSS(Cross-site scripting) 공격으로부터 보호할 수 있습니다. -* `domain` - 쿠키의 도메인을 표시합니다. URL이 요청되고 있는 서버의 도메인에 대해 비교할 때 사용하십시오. 두 도메인이 일치하는 경우에는 그 다음으로 경로 속성을 확인하십시오. -* `path` - 쿠키의 경로를 표시합니다. 요청 경로에 대해 비교할 때 사용하십시오. 이 경로와 도메인이 일치하는 경우에는 요청되고 있는 쿠키를 전송하십시오. -* `expires` - 지속적 쿠키에 대한 만기 날짜를 설정하는 데 사용됩니다. +- `secure` - 브라우저가 HTTPS를 통해서만 쿠키를 전송하도록 합니다. +- `httpOnly` - 쿠키가 클라이언트 JavaScript가 아닌 HTTP(S)를 통해서만 전송되도록 하며, 이를 통해 XSS(Cross-site scripting) 공격으로부터 보호할 수 있습니다. +- `domain` - 쿠키의 도메인을 표시합니다. URL이 요청되고 있는 서버의 도메인에 대해 비교할 때 사용하십시오. 두 도메인이 일치하는 경우에는 그 다음으로 경로 속성을 확인하십시오. +- `path` - 쿠키의 경로를 표시합니다. 요청 경로에 대해 비교할 때 사용하십시오. 이 경로와 도메인이 일치하는 경우에는 요청되고 있는 쿠키를 전송하십시오. +- `expires` - 지속적 쿠키에 대한 만기 날짜를 설정하는 데 사용됩니다. -다음에는 [cookie-session](https://www.npmjs.com/package/cookie-session) 미들웨어를 사용한 예가 표시되어 있습니다. +[noCache](https://github.com/helmetjs/nocache)는 `Cache-Control` 및 Pragma 헤더를 설정하여 클라이언트 측에서 캐싱을 사용하지 않도록 합니다. ```js const session = require('cookie-session') @@ -155,10 +227,20 @@ app.use(session({ })) ``` - +## 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. + +[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) + ## 종속 항목이 안전한지 확인 -npm을 이용해 애플리케이션의 종속 항목을 관리하는 것은 강력하면서도 편리합니다. 그러나 사용 중인 패키지에는 애플리케이션에 영향을 미칠 수 있는 치명적인 보안 취약성이 포함되어 있을 수도 있습니다. 앱의 보안성은 종속 항목 내의 "가장 약한 링크"의 보안성에 따라 결정됩니다. +npm을 이용해 애플리케이션의 종속 항목을 관리하는 것은 강력하면서도 편리합니다. 그러나 사용 중인 패키지에는 애플리케이션에 영향을 미칠 수 있는 치명적인 보안 취약성이 포함되어 있을 수도 있습니다. 앱의 보안성은 종속 항목 내의 "가장 약한 링크"의 보안성에 따라 결정됩니다. npm@6부터 npm은 자동으로 모든 설치 요청을 검사합니다. 또한 `npm audit`을 이용해 여러분의 의존성 트리를 검사할 수 있습니다. @@ -169,7 +251,6 @@ $ npm audit 더 강한 보안을 원한다면, [Snyk](https://snyk.io/)를 사용하십시오. Snyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [Github 통합](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: -Sync는 [커맨드라인 도구](https://www.npmjs.com/package/snyk)와 [Snyk's open source vulnerability database](https://snyk.io/vuln/)에 있는 여러분의 의존성들의 알려진 취약성에 대한 검사를 실행하는 [Github integration](https://snyk.io/docs/github)을 제공합니다. 아래 커맨드로 설치합니다. ```bash $ npm install -g snyk @@ -182,20 +263,20 @@ $ cd your-app $ snyk test ``` - -## 그 외의 알려져 있는 취약점 회피 +### 그 외의 알려져 있는 취약점 회피 -Express에, 또는 앱에 사용되는 다른 모듈에 영향을 미칠 수 있는 [Node Security Project](https://npmjs.com/advisories)의 보안 권고문에 항상 주의를 기울이십시오. 일반적으로 Node Security Project는 Node의 보안과 관련된 지식 및 도구에 대한 훌륭한 자원입니다. +Express에, 또는 앱에 사용되는 다른 모듈에 영향을 미칠 수 있는 [Node Security Project](https://npmjs.com/advisories)의 보안 권고문에 항상 주의를 기울이십시오. 일반적으로 Node Security Project는 Node의 보안과 관련된 지식 및 도구에 대한 훌륭한 자원입니다. 마지막으로, 다른 모든 웹 앱과 마찬가지로 Express 앱은 다양한 웹 기반 공격에 취약할 수 있습니다. 알려져 있는 [웹 취약성](https://www.owasp.org/www-project-top-ten/)을 숙지한 후 이러한 취약성을 피하기 위한 예방 조치를 취하십시오. - ## 추가적인 고려사항 유용한 [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/)에서 발췌한 몇 가지 추가적인 권장사항은 다음과 같습니다. 아래의 권장사항에 대한 모든 상세 정보를 확인하려면 해당 블로그 게시물을 참조하십시오. -* 항상 사용자 입력을 필터링하고 사용자 입력에서 민감한 데이터를 제거하여 XSS(Cross-site scripting) 및 명령 인젝션 공격으로부터 보호하십시오. -* 매개변수화된 조회 또는 준비된 명령문을 이용하여 SQL 인젝션 공격으로부터 방어하십시오. -* 오픈 소스 방식의 [sqlmap](http://sqlmap.org/) 도구를 이용하여 앱 내의 SQL 인젝션 취약성을 발견하십시오. -* [nmap](https://nmap.org/) 및 [sslyze](https://github.com/nabla-c0d3/sslyze) 도구를 이용하여 SSL 암호, 키 및 재협상의 구성, 그리고 인증서의 유효성을 테스트하십시오. -* [safe-regex](https://www.npmjs.com/package/safe-regex)를 이용하여 정규식이 [정규식 서비스 거부](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) 공격을 쉽게 받지 않도록 하십시오. +- 항상 사용자 입력을 필터링하고 사용자 입력에서 민감한 데이터를 제거하여 XSS(Cross-site scripting) 및 명령 인젝션 공격으로부터 보호하십시오. +- 매개변수화된 조회 또는 준비된 명령문을 이용하여 SQL 인젝션 공격으로부터 방어하십시오. +- 오픈 소스 방식의 [sqlmap](http://sqlmap.org/) 도구를 이용하여 앱 내의 SQL 인젝션 취약성을 발견하십시오. +- [nmap](https://nmap.org/) 및 [sslyze](https://github.com/nabla-c0d3/sslyze) 도구를 이용하여 SSL 암호, 키 및 재협상의 구성, 그리고 인증서의 유효성을 테스트하십시오. +- [safe-regex](https://www.npmjs.com/package/safe-regex)를 이용하여 정규식이 [정규식 서비스 거부](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) 공격을 쉽게 받지 않도록 하십시오. + +[helmet]: https://helmetjs.github.io/ \ No newline at end of file diff --git a/ko/advanced/developing-template-engines.md b/ko/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 22773466cd..50e0a7d66d --- a/ko/advanced/developing-template-engines.md +++ b/ko/advanced/developing-template-engines.md @@ -1,10 +1,10 @@ --- layout: page title: 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. menu: advanced lang: ko -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. +redirect_from: " " --- # Express용 템플릿 엔진 개발 @@ -19,7 +19,8 @@ app.engine('ntl', (filePath, options, callback) => { // define the template engi fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -34,6 +35,7 @@ app.set('view engine', 'ntl') // register the template engine #title# #message# ``` + 이후 앱에 다음과 같은 라우트를 작성하십시오. ```js @@ -41,4 +43,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -홈 페이지에 대한 요청을 실행할 때 `index.ntl`은 HTML로 렌더링됩니다. + +홈 페이지에 대한 요청을 실행할 때 `index.ntl`은 HTML로 렌더링됩니다. \ No newline at end of file diff --git a/ko/advanced/healthcheck-graceful-shutdown.md b/ko/advanced/healthcheck-graceful-shutdown.md index ae4cb9c6f8..bb2f50e1b0 100644 --- a/ko/advanced/healthcheck-graceful-shutdown.md +++ b/ko/advanced/healthcheck-graceful-shutdown.md @@ -1,24 +1,35 @@ --- layout: page title: 상태 검사와 우아한 종료 +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. menu: advanced lang: ko -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. +redirect_from: " " --- -# 상태 확인와 정상 종료 +# 상태 검사와 우아한 종료 ## 정상 종료 애플리케이션의 새 버전을 배포할 때, 이전 버전을 교체해야 합니다. 여러분이 사용하는 프로세스 매니저 는 애플리케어션에 SIGTERM 신호를 보내 종료를 통보할 것입니다. 애플리케이션이 신호를 받으면, 신규 요청을 받는걸 중단하고, 진행중인 요청을 끝내고, DB 연결이나 파일 사용을 포함한 사용한 리소스를 정리할 것입니다. -## 상태 확인 +### Example -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/): -로드 밸런서는 상태 확인을 애플리케이션이 장상 작동하고 요청을 받을 수 있는지 판단하는데 사용합니다. 예시로, [Kubernetes는 2개의 상태 확인을 가지고 있습니다.](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/) +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` -* `liveness`: 언제 컨테이너를 재시작할지 결정합니다. -* `readiness`: 컨테이너가 트래픽을 받기 시작할 준비가 되었는지 결정합니다. 컨테이너가 준비되지 않았다면, 서비스 로드 밸런서들에게서 제거됩니다. +## 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/): +로드 밸런서는 상태 확인을 애플리케이션이 장상 작동하고 요청을 받을 수 있는지 판단하는데 사용합니다. +- `liveness`: 언제 컨테이너를 재시작할지 결정합니다. +- `readiness`: 컨테이너가 트래픽을 받기 시작할 준비가 되었는지 결정합니다. 컨테이너가 준비되지 않았다면, 서비스 로드 밸런서들에게서 제거됩니다. \ No newline at end of file diff --git a/ko/advanced/security-updates.md b/ko/advanced/security-updates.md old mode 100755 new mode 100644 index 0808b1301e..e441cbd7de --- a/ko/advanced/security-updates.md +++ b/ko/advanced/security-updates.md @@ -1,10 +1,10 @@ --- layout: page title: Express 보안 업데이트 +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: ko -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # 보안 업데이트 @@ -16,43 +16,73 @@ Node.js 취약성은 Express에 직접 영향을 미칩니다. 따라서 [Node.j 아래의 목록에는 지정된 버전 업데이트에서 수정된 Express 취약성이 열거되어 있습니다. +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.16.0 - * 의존성 `forwarded`가 [발견된 취약점](https://npmjs.com/advisories/527)에 따라 업데이트되었습니다. `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`을 사용하는 애플리케이션에 영향을 끼칠 수 있습니다. - * 의존성 `mime`이 [발견된 취약점](https://npmjs.com/advisories/535)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. - * 의존성 `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 - * 의존성 `debug`가 [발견된 취약점](https://snyk.io/vuln/npm:debug:20170905)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. - * 의존성 `fresh`가 [발견된 취약점](https://npmjs.com/advisories/526)에 따라 업데이트되었습니다. `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`를 사용하고 있는 애플리케이션에 영향을 끼칩니다. - * 4.15.3 - * 의존성 `ms`가 [발견된 취약점](https://snyk.io/vuln/npm:ms:20170412)에 따라 업데이트되었습니다. 애플리케이션이 `express.static`, `res.sendfile`, `res.sendFile`의 `maxAge` 옵션에 Untrusted 문자열을 입력받고 있으면 영향을 끼칠 수 있습니다. - * 4.15.2 - * 의존성 `qs`가 [발견된 취약점](https://snyk.io/vuln/npm:qs:20170213)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. 4.15.2로 업데이트하는 것을 권장하나, 취약점을 막는 업데이트는 아닙니다.. - * 4.11.1 - * `express.static`, `res.sendfile` 및 `res.sendFile`의 루트 경로 노출 취약성을 수정했습니다. - * 4.10.7 - * `express.static`의 개방된 경로 재지정 취약성을 수정했습니다([보안 권고문](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 4.8.8 - * `express.static`의 디렉토리 조회 취약성을 수정했습니다([보안 권고문](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 이용 시, 특정한 상황에서 `fd` 누수가 발생할 수 있으며, 이는 `express.static` 및 `res.sendfile`에 영향을 미칩니다. 악성 요청은 `fd` 누수를 발생시킬 수 있으며, 결국 `EMFILE` 오류와 서버 무응답을 초래할 수 있습니다. - * 4.8.0 - * 조회 문자열에서 극단적으로 높은 인덱스를 갖는 스파스 배열은 프로세스가 메모리 부족을 발생시키고 서버에서 충돌이 발생하도록 하는 원인이 될 수 있습니다. - * 극단적인 수준으로 중첩된 조회 문자열 오브젝트는 프로세스가 서버를 차단하고 일시적으로 서버를 무응답 상태로 만드는 원인이 될 수 있습니다. +- 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). +- 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`. +- 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. +- 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`. +- 4.16.0 + - 의존성 `forwarded`가 [발견된 취약점](https://npmjs.com/advisories/527)에 따라 업데이트되었습니다. `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`을 사용하는 애플리케이션에 영향을 끼칠 수 있습니다. + - 의존성 `mime`이 [발견된 취약점](https://npmjs.com/advisories/535)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. + - 의존성 `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 + - 의존성 `debug`가 [발견된 취약점](https://snyk.io/vuln/npm:debug:20170905)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. + - 의존성 `fresh`가 [발견된 취약점](https://npmjs.com/advisories/526)에 따라 업데이트되었습니다. `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`를 사용하고 있는 애플리케이션에 영향을 끼칩니다. +- 4.15.3 + - 의존성 `ms`가 [발견된 취약점](https://snyk.io/vuln/npm:ms:20170412)에 따라 업데이트되었습니다. 애플리케이션이 `express.static`, `res.sendfile`, `res.sendFile`의 `maxAge` 옵션에 Untrusted 문자열을 입력받고 있으면 영향을 끼칠 수 있습니다. +- 4.15.2 + - 의존성 `qs`가 [발견된 취약점](https://snyk.io/vuln/npm:qs:20170213)에 따라 업데이트되었으나, Express에 영향을 끼치지는 않습니다. 4.15.2로 업데이트하는 것을 권장하나, 취약점을 막는 업데이트는 아닙니다.. +- 4.11.1 + - `express.static`, `res.sendfile` 및 `res.sendFile`의 루트 경로 노출 취약성을 수정했습니다. +- 4.10.7 + - `express.static`의 개방된 경로 재지정 취약성을 수정했습니다([보안 권고문](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 4.8.8 + - `express.static`의 디렉토리 조회 취약성을 수정했습니다([보안 권고문](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 이용 시, 특정한 상황에서 `fd` 누수가 발생할 수 있으며, 이는 `express.static` 및 `res.sendfile`에 영향을 미칩니다. 악성 요청은 `fd` 누수를 발생시킬 수 있으며, 결국 `EMFILE` 오류와 서버 무응답을 초래할 수 있습니다. +- 4.8.0 + - 조회 문자열에서 극단적으로 높은 인덱스를 갖는 스파스 배열은 프로세스가 메모리 부족을 발생시키고 서버에서 충돌이 발생하도록 하는 원인이 될 수 있습니다. + - 극단적인 수준으로 중첩된 조회 문자열 오브젝트는 프로세스가 서버를 차단하고 일시적으로 서버를 무응답 상태로 만드는 원인이 될 수 있습니다. ## 3.x - * 3.19.1 - * `express.static`, `res.sendfile` 및 `res.sendFile`의 루트 경로 노출 취약성을 수정했습니다. - * 3.19.0 - * `express.static`의 개방된 경로 재지정 취약성을 수정했습니다([보안 권고문](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 3.16.10 - * `express.static`의 디렉토리 조회 취약성을 수정했습니다. - * 3.16.6 - * Node.js 0.10 이용 시, 특정한 상황에서 `fd` 누수가 발생할 수 있으며, 이는 `express.static` 및 `res.sendfile`에 영향을 미칩니다. 악성 요청은 `fd` 누수를 발생시킬 수 있으며, 결국 `EMFILE` 오류와 서버 무응답을 초래할 수 있습니다. - * 3.16.0 - * 조회 문자열에서 극단적으로 높은 인덱스를 갖는 스파스 배열은 프로세스가 메모리 부족을 발생시키고 서버에서 충돌이 발생하도록 하는 원인이 될 수 있습니다. - * 극단적인 수준으로 중첩된 조회 문자열 오브젝트는 프로세스가 서버를 차단하고 일시적으로 서버를 무응답 상태로 만드는 원인이 될 수 있습니다. - * 3.3.0 - * 지원되지 않는 메소드 대체 시도의 404 응답은 XSS(Cross-site scripting) 공격을 받기 쉬웠습니다. +
    + **Express 3.x은 더 이상 유지보수되지 않습니다.** + +3.x의 알려진 또는 알려지지 않은 보안 및 성능 문제는 마지막 업데이트(2015년 8월 1일) 이후로 처리되지 않고 있습니다. 최신 버전의 Express를 사용할 것을 강력히 권장합니다. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
    + +- 3.19.1 + - `express.static`, `res.sendfile` 및 `res.sendFile`의 루트 경로 노출 취약성을 수정했습니다. +- 3.19.0 + - `express.static`의 개방된 경로 재지정 취약성을 수정했습니다([보안 권고문](https://npmjs.com/advisories/35), [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 3.16.10 + - `express.static`의 디렉토리 조회 취약성을 수정했습니다. +- 3.16.6 + - Node.js 0.10 이용 시, 특정한 상황에서 `fd` 누수가 발생할 수 있으며, 이는 `express.static` 및 `res.sendfile`에 영향을 미칩니다. 악성 요청은 `fd` 누수를 발생시킬 수 있으며, 결국 `EMFILE` 오류와 서버 무응답을 초래할 수 있습니다. +- 3.16.0 + - 조회 문자열에서 극단적으로 높은 인덱스를 갖는 스파스 배열은 프로세스가 메모리 부족을 발생시키고 서버에서 충돌이 발생하도록 하는 원인이 될 수 있습니다. + - 극단적인 수준으로 중첩된 조회 문자열 오브젝트는 프로세스가 서버를 차단하고 일시적으로 서버를 무응답 상태로 만드는 원인이 될 수 있습니다. +- 3.3.0 + - 지원되지 않는 메소드 대체 시도의 404 응답은 XSS(Cross-site scripting) 공격을 받기 쉬웠습니다. \ No newline at end of file diff --git a/ko/api.md b/ko/api.md old mode 100755 new mode 100644 index 17838716db..5cbbc65a88 --- a/ko/api.md +++ b/ko/api.md @@ -1,19 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - API 참조 +version: 5x +title: Express 5.x - API 참조 +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: ko -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    4.x API

    - - {% include api/en/4x/express.md %} - {% include api/en/4x/app.md %} - {% include api/en/4x/req.md %} - {% include api/en/4x/res.md %} - {% include api/en/4x/router.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} + + {% include api/en/5x/app.md %} + + {% include api/en/5x/req.md %} + + {% include api/en/5x/res.md %} + + {% include api/en/5x/router.md %}
    diff --git a/ko/changelog/index.md b/ko/changelog/index.md new file mode 100644 index 0000000000..755f584be0 --- /dev/null +++ b/ko/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: ko +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) to address a [vulnerability](https://npmjs.com/advisories/527). `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`을 사용하는 애플리케이션에 영향을 끼칠 수 있습니다. +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) to address a [vulnerability](https://npmjs.com/advisories/526). `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`를 사용하고 있는 애플리케이션에 영향을 끼칩니다. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://snyk.io/vuln/npm:ms:20170412). 애플리케이션이 `express.static`, `res.sendfile`, `res.sendFile`의 `maxAge` 옵션에 Untrusted 문자열을 입력받고 있으면 영향을 끼칠 수 있습니다. +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/ko/guide/behind-proxies.md b/ko/guide/behind-proxies.md old mode 100755 new mode 100644 index 2ccb6c63a6..7cebbabb50 --- a/ko/guide/behind-proxies.md +++ b/ko/guide/behind-proxies.md @@ -1,20 +1,22 @@ --- layout: page title: 프록시 환경에서 Express 사용 +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. menu: guide lang: ko -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. +redirect_from: " " --- # 프록시 환경에서 Express 사용 -프록시 뒤에서 Express 앱을 실행할 때는, ([app.set()](/{{ page.lang }}/4x/api.html#app.set)을 이용하여) 애플리케이션 변수 `trust proxy`를 다음 표에 나열된 값 중 하나로 설정하십시오. +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.
    -애플리케이션 변수 `trust proxy`가 설정되지 않아도 앱은 실행되지만, `trust proxy`가 구성되지 않으면 프록시의 IP 주소가 클라이언트 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.
    +프록시 뒤에서 Express 앱을 실행할 때는, ([app.set()](/{{ page.lang }}/4x/api.html#app.set)을 이용하여) 애플리케이션 변수 `trust proxy`를 다음 표에 나열된 값 중 하나로 설정하십시오. + @@ -24,16 +26,20 @@ description: Learn how to configure Express.js applications to work correctly be `true`인 경우, 클라이언트의 IP 주소는 `X-Forwarded-*` 내의 가장 왼쪽 입력 항목인 것으로 인식됩니다. `false`인 경우, 앱이 직접 인터넷에 연결되는 것으로 인식되며 클라이언트의 IP 주소는 `req.connection.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. +
    - + - +
    유형
    IP 주소IP addresses -신뢰할 IP 주소나 서브넷, 또는 IP 주소 및 서브넷의 배열입니다. 아래의 목록에는 사전에 구성된 서브넷 이름이 표시되어 있습니다. +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: -* 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` +- 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` 다음의 방법 중 하나로 IP 주소를 설정할 수 있습니다. @@ -44,20 +50,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -IP 주소 또는 서브넷이 지정되는 경우, 해당 IP 주소 또는 서브넷은 주소 결정 프로세스에서 제외되며, 신뢰할 수 있는 것으로 지정되지 않은 IP 주소 중 애플리케이션 서버에서 가장 가까운 IP 주소가 클라이언트의 IP 주소로 결정됩니다. +IP 주소 또는 서브넷이 지정되는 경우, 해당 IP 주소 또는 서브넷은 주소 결정 프로세스에서 제외되며, 신뢰할 수 있는 것으로 지정되지 않은 IP 주소 중 애플리케이션 서버에서 가장 가까운 IP 주소가 클라이언트의 IP 주소로 결정됩니다. 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. +
    숫자 -가장 앞의 프록시 서버로부터 `n`번 째 홉을 클라이언트로서 신뢰합니다. +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. + +
    +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. +
    함수Function -사용자 정의 신뢰 구현입니다. 이 방법을 올바르게 숙지하고 있는 경우에만 이 방법을 사용하십시오. - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -65,12 +75,13 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
    -`trust proxy` 값을 `false` 이외의 값으로 설정하면 다음과 같은 세 가지의 중요한 변화가 발생합니다. +Enabling `trust proxy` will have the following impact:
    • [req.hostname](/{{ page.lang }}/api.html#req.hostname)의 값은 `X-Forwarded-Host` 헤더에 설정된 값으로부터 도출되며, 이 값은 클라이언트 또는 프록시에 의해 설정될 수 있습니다. diff --git a/ko/guide/database-integration.md b/ko/guide/database-integration.md old mode 100755 new mode 100644 index 2108277a82..954520dee9 --- a/ko/guide/database-integration.md +++ b/ko/guide/database-integration.md @@ -1,337 +1,491 @@ --- layout: page title: Express 데이터베이스 통합 +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: ko -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # 데이터베이스 통합 데이터베이스를 Express 앱에 연결하는 기능을 추가하려면 앱에 포함된 데이터베이스를 위한 적절한 Node.js 드라이버를 로드해야 합니다. 이 문서에서는 Express 앱의 데이터베이스 시스템에 가장 널리 이용되고 있는 Node.js 모듈 중 다음과 같은 몇 개의 모듈을 추가 및 사용하는 방법을 설명합니다. -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
      -위의 데이터베이스 드라이버는 사용 가능한 여러 데이터베이스 드라이버 중 일부입니다. 다른 옵션을 확인하려면, +위의 데이터베이스 드라이버는 사용 가능한 여러 데이터베이스 드라이버 중 일부입니다. 다른 옵션을 확인하려면, [npm](https://www.npmjs.com/) 사이트에서 검색하십시오.
      - - ## Cassandra **모듈**: [cassandra-driver](https://github.com/datastax/nodejs-driver) **설치** +### Installation + ```bash $ npm install cassandra-driver ``` -**예제** +### Example + +```js +const cassandra = require('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 -
      -
      -var cassandra = require('cassandra-driver');
      -var client = new cassandra.Client({ contactPoints: ['localhost']});
      +**Module**: [couchnode](https://github.com/couchbase/couchnode)
       
      -client.execute('select key from system.local', function(err, result) {
      -  if (err) throw err;
      -  console.log(result.rows[0]);
      -});
      -
      -
      +### Installation - +```bash +$ npm install couchbase +``` + +### Example + +```js +const couchbase = require('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) **설치** +### Installation + ```bash $ npm install nano ``` -**예제** +### Example -
      -
      -var nano = require('nano')('http://localhost:5984');
      -nano.db.create('books');
      -var books = nano.db.use('books');
      +```js
      +const nano = require('nano')('http://localhost:5984')
      +nano.db.create('books')
      +const books = nano.db.use('books')
       
      -//Insert a book document in the books database
      -books.insert({name: 'The Art of war'}, null, function(err, body) {
      -  if (!err){
      -    console.log(body);
      +// Insert a book document in the books database
      +books.insert({ name: 'The Art of war' }, null, (err, body) => {
      +  if (err) {
      +    console.log(err)
      +  } else {
      +    console.log(body)
         }
      -});
      -
      -//Get a list of all books
      -books.list(function(err, body){
      -  console.log(body.rows);
      -});
      -
      -
      +}) - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **모듈**: [levelup](https://github.com/rvagg/node-levelup) **설치** +### Installation + ```bash $ npm install level levelup leveldown ``` -**예제** - -
      -
      -var levelup = require('levelup');
      -var db = levelup('./mydb');
      +### Example
       
      -db.put('name', 'LevelUP', function (err) {
      +```js
      +const levelup = require('levelup')
      +const db = levelup('./mydb')
       
      -  if (err) return console.log('Ooops!', err);
      -  db.get('name', function (err, value) {
      -    if (err) return console.log('Ooops!', err);
      -    console.log('name=' + value);
      -  });
      +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/) **설치** +### Installation + ```bash $ npm install mysql ``` -**예제** +### Example -
      -
      -var mysql      = require('mysql');
      -var connection = mysql.createConnection({
      -  host     : 'localhost',
      -  user     : 'dbuser',
      -  password : 's3kreee7'
      -});
      +```js
      +const mysql = require('mysql')
      +const connection = mysql.createConnection({
      +  host: 'localhost',
      +  user: 'dbuser',
      +  password: 's3kreee7',
      +  database: 'my_db'
      +})
       
      -connection.connect();
      +connection.connect()
       
      -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      -  if (err) throw err;
      -  console.log('The solution is: ', rows[0].solution);
      -});
      +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
      +  if (err) throw err
       
      -connection.end();
      -
      -
      + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **모듈**: [mongodb](https://github.com/mongodb/node-mongodb-native) **설치** +### Installation + ```bash $ npm install mongodb ``` -**예제** +### Example (v2.\*) -
      -
      -var MongoClient = require('mongodb').MongoClient;
      +```js
      +const MongoClient = require('mongodb').MongoClient
       
      -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
      -  if (err) {
      -    throw err;
      -  }
      -  db.collection('mammals').find().toArray(function(err, result) {
      -    if (err) {
      -      throw err;
      -    }
      -    console.log(result);
      -  });
      -});
      -
      -
      +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err -MongoDB용 오브젝트 모델 드라이버가 필요한 경우에는 [Mongoose](https://github.com/LearnBoost/mongoose)를 확인하십시오. + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err - + console.log(result) + }) +}) +``` + +### Example (v3.\*) + +```js +const MongoClient = require('mongodb').MongoClient + +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err + + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +MongoDB용 오브젝트 모델 드라이버가 필요한 경우에는 [Mongoose](https://github.com/LearnBoost/mongoose)를 확인하십시오. ## Neo4j -**모듈**: [apoc](https://github.com/hacksparrow/apoc) -**설치** +**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver) + +### Installation ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**예제** +### Example -
      -
      -var apoc = require('apoc');
      +```js
      +const neo4j = require('neo4j-driver')
      +const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
       
      -apoc.query('match (n) return n').exec().then(
      -  function (response) {
      -    console.log(response);
      -  },
      -  function (fail) {
      -    console.log(fail);
      +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
      +const oracledb = require('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) **설치** +### Installation + ```bash $ npm install pg-promise ``` -**예제** +### Example -
      -
      -var pgp = require("pg-promise")(/*options*/);
      -var db = pgp("postgres://username:password@host:port/database");
      +```js
      +const pgp = require('pg-promise')(/* options */)
      +const db = pgp('postgres://username:password@host:port/database')
       
      -db.one("SELECT $1 AS value", 123)
      -    .then(function (data) {
      -        console.log("DATA:", data.value);
      -    })
      -    .catch(function (error) {
      -        console.log("ERROR:", error);
      -    });
      -
      -
      - - +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **모듈**: [redis](https://github.com/mranney/node_redis) **설치** +### Installation + ```bash $ npm install redis ``` -**예제** +### Example + +```js +const redis = require('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 -
      -
      -var client = require('redis').createClient();
      +**Module**: [tedious](https://github.com/tediousjs/tedious)
       
      -client.on('error', function (err) {
      -  console.log('Error ' + err);
      -});
      +### Installation
       
      -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);
      +```bash
      +$ npm install tedious
      +```
       
      -client.hkeys('hash key', function (err, replies) {
      +### Example
       
      -  console.log(replies.length + ' replies:');
      -  replies.forEach(function (reply, i) {
      -    console.log('    ' + i + ': ' + reply);
      -  });
      +```js
      +const Connection = require('tedious').Connection
      +const Request = require('tedious').Request
       
      -  client.quit();
      +const config = {
      +  server: 'localhost',
      +  authentication: {
      +    type: 'default',
      +    options: {
      +      userName: 'your_username', // update me
      +      password: 'your_password' // update me
      +    }
      +  }
      +}
       
      -});
      -
      -
      +const connection = new Connection(config) - +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **모듈**: [sqlite3](https://github.com/mapbox/node-sqlite3) **설치** +### Installation + ```bash $ npm install sqlite3 ``` -**예제** +### Example -
      -
      -var sqlite3 = require('sqlite3').verbose();
      -var db = new sqlite3.Database(':memory:');
      +```js
      +const sqlite3 = require('sqlite3').verbose()
      +const db = new sqlite3.Database(':memory:')
       
      -db.serialize(function() {
      +db.serialize(() => {
      +  db.run('CREATE TABLE lorem (info TEXT)')
      +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
       
      -  db.run('CREATE TABLE lorem (info TEXT)');
      -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
      -
      -  for (var i = 0; i < 10; i++) {
      -    stmt.run('Ipsum ' + i);
      +  for (let i = 0; i < 10; i++) {
      +    stmt.run(`Ipsum ${i}`)
         }
       
      -  stmt.finalize();
      -
      -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
      -    console.log(row.id + ': ' + row.info);
      -  });
      -});
      +  stmt.finalize()
       
      -db.close();
      -
      -
      + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) + }) +}) - +db.close() +``` ## ElasticSearch **모듈**: [elasticsearch](https://github.com/elastic/elasticsearch-js) **설치** +### Installation + ```bash $ npm install elasticsearch ``` -**예제** +### Example -
      -
      -var elasticsearch = require('elasticsearch');
      -var client = elasticsearch.Client({
      +```js
      +const elasticsearch = require('elasticsearch')
      +const client = elasticsearch.Client({
         host: 'localhost:9200'
      -});
      +})
       
       client.search({
         index: 'books',
      @@ -344,10 +498,9 @@ client.search({
             }
           }
         }
      -}).then(function(response) {
      -  var hits = response.hits.hits;
      -}, function(error) {
      -  console.trace(error.message);
      -});
      -
      -
      +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/ko/guide/debugging.md b/ko/guide/debugging.md old mode 100755 new mode 100644 index 2e5ce300e9..d1ee00e757 --- a/ko/guide/debugging.md +++ b/ko/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Express 디버깅 +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: ko -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # Express 디버깅 @@ -19,7 +19,7 @@ $ DEBUG=express:* node index.js Windows에서는 다음과 같은 명령을 사용하십시오. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` [Express 생성기](/{{ page.lang }}/starter/generator.html)가 생성한 기본 앱에 대해 이 명령을 실행하면 다음과 같이 인쇄됩니다. @@ -60,11 +60,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -105,3 +105,27 @@ $ DEBUG=sample-app:* node ./bin/www ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/ko/guide/error-handling.md b/ko/guide/error-handling.md old mode 100755 new mode 100644 index 86d6025249..62e4c8040e --- a/ko/guide/error-handling.md +++ b/ko/guide/error-handling.md @@ -1,17 +1,196 @@ --- layout: page title: Express 오류 처리 +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: ko -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # 오류 처리 +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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. 예를 들면 다음과 같습니다. + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + +여러 콜백 함수를 갖는 라우트 핸들러가 있는 경우에는 `route` 매개변수를 사용하여 그 다음의 라우트 핸들러로 건너뛸 수 있습니다. 예를 들면 다음과 같습니다. + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + 다른 미들웨어 함수와 동일한 방법으로 오류 처리 미들웨어 함수를 정의할 수 있지만, 오류 처리 함수는 3개가 아닌 4개의 인수, 즉 `(err, req, res, next)`를 -갖는다는 점이 다릅니다. 예를 들면 다음과 같습니다. +갖는다는 점이 다릅니다. +예를 들면 다음과 같습니다. + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +`next()` 함수로 어떠한 내용을 전달하는 경우(`'route'`라는 문자열 제외), Express는 현재의 요청에 오류가 있는 것으로 간주하며, 오류 처리와 관련되지 않은 나머지 라우팅 및 미들웨어 함수를 건너뜁니다. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. 예를 들면 다음과 같습니다. + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. 예를 들면 다음과 같습니다. + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +You could also use a chain of handlers to rely on synchronous error +catching, by reducing the asynchronous code to something trivial. 예를 들면 다음과 같습니다. + +```js +app.get('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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는 내장된 오류 핸들러와 함께 제공되며, 내장 오류 핸들러는 앱에서 발생할 수 있는 모든 오류를 처리합니다. 이러한 기본 오류 처리 미들웨어 함수는 미들웨어 함수 스택의 끝에 추가됩니다. + +`next()`로 오류를 전달하지만 오류 핸들러에서 해당 오류를 +처리하지 않는 경우, 기본 제공 오류 핸들러가 해당 오류를 처리하며, 해당 오류는 +클라이언트에 스택 추적과 함께 기록됩니다. 스택 추적은 프로덕션 환경에 포함되어 있지 않습니다. + +
      +프로덕션 모드에서 앱을 실행하려면 환경 변수 `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. + +응답의 기록을 시작한 후에 오류가 있는 `next()`를 +호출하는 경우(예: 응답을 클라이언트로 스트리밍하는 중에 오류가 +발생하는 경우), Express의 기본 오류 핸들러는 해당 연결을 닫고 +해당 요청을 처리하지 않습니다. + +따라서 사용자 정의 오류 핸들러를 추가할 때, 헤더가 이미 클라이언트로 전송된 경우에는 +다음과 같이 Express 내의 기본 오류 처리 메커니즘에 위임해야 합니다: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +만약 `next()`를 여러분의 코드에서 여러 번 호출한다면, 사용자 정의 오류 핸들러가 있음에도 불구하고 기본 오류 핸들러가 발동될 수 있음에 주의하십시오. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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)`. 예를 들면 다음과 같습니다. ```js app.use((err, req, res, next) => { @@ -26,7 +205,10 @@ app.use((err, req, res, next) => { const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -44,7 +226,10 @@ app.use((err, req, res, next) => { const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -63,6 +248,8 @@ function logErrors (err, req, res, next) { 또한 이 예에서 `clientErrorHandler`는 다음과 같이 정의되며, 이 경우 오류는 명시적으로 그 다음 항목으로 전달됩니다. +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) { if (req.xhr) { @@ -72,6 +259,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + "모든 오류를 처리하는(catch-all)" `errorHandler` 함수는 다음과 같이 구현될 수 있습니다. ```js @@ -81,17 +269,16 @@ function errorHandler (err, req, res, next) { } ``` -`next()` 함수로 어떠한 내용을 전달하는 경우(`'route'`라는 문자열 제외), Express는 현재의 요청에 오류가 있는 것으로 간주하며, 오류 처리와 관련되지 않은 나머지 라우팅 및 미들웨어 함수를 건너뜁니다. 이러한 오류를 어떻게든 처리하기 원하는 경우, 다음 섹션에 설명된 것과 같이 오류 처리 라우트를 작성해야 합니다. - -여러 콜백 함수를 갖는 라우트 핸들러가 있는 경우에는 `route` 매개변수를 사용하여 그 다음의 라우트 핸들러로 건너뛸 수 있습니다. 예를 들면 다음과 같습니다. +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('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -100,40 +287,9 @@ app.get('/a_route_behind_paywall', }) }) ``` + 이 예에서 `getPaidContent` 핸들러의 실행은 건너뛰지만, `/a_route_behind_paywall`에 대한 `app` 내의 나머지 핸들러는 계속하여 실행됩니다.
      `next()` 및 `next(err)`에 대한 호출은 현재의 핸들러가 완료되었다는 것과 해당 핸들러의 상태를 표시합니다. `next(err)`는 위에 설명된 것과 같이 오류를 처리하도록 설정된 핸들러를 제외한 체인 내의 나머지 모든 핸들러를 건너뜁니다.
      - -## 기본 오류 핸들러 - -Express는 내장된 오류 핸들러와 함께 제공되며, 내장 오류 핸들러는 앱에서 발생할 수 있는 모든 오류를 처리합니다. 이러한 기본 오류 처리 미들웨어 함수는 미들웨어 함수 스택의 끝에 추가됩니다. - -`next()`로 오류를 전달하지만 오류 핸들러에서 해당 오류를 -처리하지 않는 경우, 기본 제공 오류 핸들러가 해당 오류를 처리하며, 해당 오류는 -클라이언트에 스택 추적과 함께 기록됩니다. 스택 추적은 프로덕션 환경에 포함되어 있지 않습니다. - -
      -프로덕션 모드에서 앱을 실행하려면 환경 변수 `NODE_ENV`를 `production`으로 설정하십시오. -
      - -응답의 기록을 시작한 후에 오류가 있는 `next()`를 -호출하는 경우(예: 응답을 클라이언트로 스트리밍하는 중에 오류가 -발생하는 경우), Express의 기본 오류 핸들러는 해당 연결을 닫고 -해당 요청을 처리하지 않습니다. - -따라서 사용자 정의 오류 핸들러를 추가할 때, 헤더가 이미 클라이언트로 전송된 경우에는 -다음과 같이 Express 내의 기본 오류 처리 메커니즘에 위임해야 합니다: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` - -만약 `next()`를 여러분의 코드에서 여러 번 호출한다면, 사용자 정의 오류 핸들러가 있음에도 불구하고 기본 오류 핸들러가 발동될 수 있음에 주의하십시오. diff --git a/ko/guide/migrating-4.md b/ko/guide/migrating-4.md old mode 100755 new mode 100644 index dfc20b6495..f4a84fab01 --- a/ko/guide/migrating-4.md +++ b/ko/guide/migrating-4.md @@ -1,10 +1,10 @@ --- layout: page title: 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. menu: guide lang: ko -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. +redirect_from: " " --- # Express 4로의 이전 @@ -26,7 +26,7 @@ Express 4는 Express 3로부터 근본적으로 변경되었습니다. 따라서 Express 4에서는 여러 중요한 부분이 변경되었습니다.
        -
      • Express 코어 및 미들웨어 시스템에 대한 변경. Connect 및 기본 제공 미들웨어에 대한 종속 항목이 제거되었으며, 따라서 사용자가 직접 미들웨어를 추가해야 합니다. +
      • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
      • 라우팅 시스템에 대한 변경.
      • 기타 다양한 변경사항.
      • @@ -34,8 +34,8 @@ Express 4에서는 여러 중요한 부분이 변경되었습니다. 또한 다음을 참조하십시오. -* [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) +- [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)

        Express 코어 및 미들웨어 시스템에 대한 변경 @@ -56,7 +56,7 @@ Express 4는 더 이상 Connect에 종속되지 않으며, `express.static` 함 다음 표에는 Express 3의 미들웨어 및 그에 대응하는 Express 4의 미들웨어가 나열되어 있습니다. - + @@ -88,7 +88,7 @@ Express 4는 더 이상 Connect에 종속되지 않으며, `express.static` 함 -
        Express 3Express 4
        Express 3Express 4
        express.bodyParser body-parser + multer
        serve-index
        express.static serve-static
        + Express 4 미들웨어의 [전체 목록](https://github.com/senchalabs/connect#middleware)을 참조하십시오. @@ -102,11 +102,12 @@ Express 4 미들웨어의 [전체 목록](https://github.com/senchalabs/connect# 예를 들면 다음과 같습니다. ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

        라우팅 시스템

        @@ -119,8 +120,9 @@ app.use('/book/:id', function (req, res, next) { 라우팅 시스템에는 다음과 같은 2개의 새로운 기능이 추가되었습니다. {: .doclist } -* 라우트 경로에 대하여 체인 가능한 라우트 핸들러를 작성할 수 있는 새로운 메소드인 `app.route()`. -* 모듈식 마운팅 가능한 라우트 핸들러를 작성할 수 있는 새로운 클래스인 `express.Router`. + +- 라우트 경로에 대하여 체인 가능한 라우트 핸들러를 작성할 수 있는 새로운 메소드인 `app.route()`. +- 모듈식 마운팅 가능한 라우트 핸들러를 작성할 수 있는 새로운 클래스인 `express.Router`.

        app.route() 메소드

        @@ -132,13 +134,13 @@ app.use('/book/:id', function (req, res, next) { ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -161,16 +163,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -182,7 +184,7 @@ module.exports = router ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -198,7 +200,7 @@ app.use('/birds', birds) 다음 표에는 Express 4의 작지만 중요한 다른 변경사항이 나열되어 있습니다. - + @@ -308,7 +310,7 @@ Express 4에서는 기본적으로 `json spaces` 애플리케이션 특성을 기능을 위해서는 `res.cookie()`를 사용하십시오. -
        오브젝트 설명
        +

        앱 마이그레이션의 예

        @@ -352,7 +354,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -360,7 +362,7 @@ http.createServer(app).listen(app.get('port'), function () {

        package.json

        동반되는 버전 3의 `package.json` 파일의 내용은 - 다음과 같을 수 있습니다. +다음과 같을 수 있습니다. ```json { @@ -392,15 +394,15 @@ $ npm install serve-favicon morgan method-override express-session body-parser m `app.js`를 다음과 같이 변경하십시오. 1. 기본 제공 Express 미들웨어 함수인 `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` 및 - `express.errorHandler`는 더 이상 `express` - 오브젝트에 사용할 수 없습니다. 이들 함수의 대체 함수를 수동으로 - 설치한 후 앱에서 로드해야 합니다. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` 및 + `express.errorHandler`는 더 이상 `express` + 오브젝트에 사용할 수 없습니다. 이들 함수의 대체 함수를 수동으로 + 설치한 후 앱에서 로드해야 합니다. 2. `app.router` 함수는 이제 로드할 필요가 없습니다. - 이 함수는 유효한 Express 4 앱 오브젝트가 아니므로 - `app.use(app.router);` 코드를 제거하십시오. + 이 함수는 유효한 Express 4 앱 오브젝트가 아니므로 + `app.use(app.router);` 코드를 제거하십시오. 3. 미들웨어 함수들이 올바른 순서로 로드되는지 확인하십시오(앱 라우트를 로드한 후 `errorHandler`를 로드). @@ -423,7 +425,7 @@ $ npm install serve-favicon morgan method-override express-session body-parser m "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -489,14 +491,14 @@ server.listen(app.get('port'), () => { `http` 모듈을 이용해 직접 작업해야 하는 경우(socket.io/SPDY/HTTPS)를 제외하면 `http` 모듈을 로드할 필요가 없으며, 다음과 같은 방법으로 간단히 앱을 시작할 수 있습니다. ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ```
    -

    앱 실행

    +

    Run the app

    마이그레이션 프로세스가 완료되었으며, 이제 앱은 Express 4 앱이 되었습니다. 확인을 위하여, 다음의 명령을 이용해 앱을 시작하십시오. @@ -506,14 +508,14 @@ $ node . ``` [http://localhost:3000](http://localhost:3000)을 - 로드한 후 홈 페이지가 Express 4에 의해 렌더링되는 것을 확인하십시오. +로드한 후 홈 페이지가 Express 4에 의해 렌더링되는 것을 확인하십시오.

    Express 4 앱 생성기로의 업그레이드

    Express 앱을 생성하기 위한 명령행 도구는 여전히 - `express`이지만, 새 버전으로 업그레이드하려면 - Express 3 앱 생성기의 설치를 제거한 후 새로운 - `express-generator`를 설치해야 합니다. +`express`이지만, 새 버전으로 업그레이드하려면 +Express 3 앱 생성기의 설치를 제거한 후 새로운 +`express-generator`를 설치해야 합니다.

    설치

    @@ -544,11 +546,12 @@ $ npm install -g express-generator 다음을 제외하면, 명령의 옵션 및 용도는 대체로 동일하게 유지되었습니다. {: .doclist } -* `--sessions` 옵션이 제거되었습니다. -* `--jshtml` 옵션이 제거되었습니다. -* [Hogan.js](http://twitter.github.io/hogan.js/)를 지원하기 위한 `--hogan` 옵션이 추가되었습니다. -

    +- `--sessions` 옵션이 제거되었습니다. +- `--jshtml` 옵션이 제거되었습니다. +- [Hogan.js](http://twitter.github.io/hogan.js/)를 지원하기 위한 `--hogan` 옵션이 추가되었습니다. + +

    Example

    Express 4 앱을 작성하기 위하여 다음의 명령을 실행하십시오. @@ -592,7 +595,7 @@ Node.js 파일을 통해 시작되어야 합니다. 이 경우에서 Node.js 파 ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -606,6 +609,6 @@ var debug = require('debug')('app4') 다음으로, `package.json` 파일의 `"start": "node ./bin/www"`를 `"start": "node app.js"`로 변경하십시오. 이제 `./bin/www`의 기능이 다시 `app.js`로 -이전되었습니다. 이러한 변경은 권장되지 않지만, 이러한 연습을 통해 +이전되었습니다. 이러한 변경은 권장되지 않지만, 이러한 연습을 통해 `./bin/www` 파일의 작동 원리를 이해하고 `app.js` 파일이 더 이상 자체적으로 시작되지 않는 이유를 이해할 수 있습니다. diff --git a/ko/guide/migrating-5.md b/ko/guide/migrating-5.md old mode 100755 new mode 100644 index dcf3082ff1..852db44f55 --- a/ko/guide/migrating-5.md +++ b/ko/guide/migrating-5.md @@ -1,32 +1,45 @@ --- layout: page title: Express 5로의 마이그레이션 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: ko -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # Express 5로의 이전

    개요

    -Express 5.0은 아직 알파 릴리스 단계에 있지만, 이 문서에서는 릴리스에 포함될 변경사항과 Express 4 앱을 Express 5로 마이그레이션하는 방법을 미리 살펴봅니다. +Express 5는 Express 4와 크게 다르지 않으며, API에 대한 변경은 3.0에서 4.0으로의 변경만큼 크지 않습니다. 기본적인 API는 동일하게 유지되지만, 근본적인 변경사항이 존재합니다. 즉, Express 5를 사용하기 위해 기존 Express 4 프로그램을 업데이트하면 기존 Express 4 프로그램은 작동하지 않을 수 있습니다. -Express 5는 Express 4와 크게 다르지 않으며, API에 대한 변경은 3.0에서 4.0으로의 변경만큼 크지 않습니다. 기본적인 API는 동일하게 유지되지만, 근본적인 변경사항이 존재합니다. 즉, Express 5를 사용하기 위해 기존 Express 4 프로그램을 업데이트하면 기존 Express 4 프로그램은 작동하지 않을 수 있습니다. +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -Express 5의 최신 알파 버전을 설치하고 미리보려면, 애플리케이션 루트 디렉토리에서 다음의 명령을 입력하십시오. - -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` 이후 자동화된 테스트를 실행하여 실패하는 항목을 확인하고, 아래에 나열된 업데이트에 따라 문제를 수정할 수 있습니다. 테스트 실패 항목을 처리한 후에는 앱을 실행하여 어떠한 오류가 발생하는지 확인하십시오. 지원되지 않는 메소드나 특성을 앱이 사용하는 경우에는 이를 곧바로 확인할 수 있습니다. -

    Express 5에서의 변경사항

    +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` -아래에는 Express 사용자에게 영향을 미치는 변경사항(알파 2 릴리스 기준)의 목록이 표시되어 있습니다. -계획된 모든 기능의 목록을 확인하려면 [pull request](https://github.com/expressjs/express/pull/2237)를 참조하십시오. +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

    Express 5에서의 변경사항

    **제거된 메소드 및 특성** @@ -38,26 +51,40 @@ $ npm install "express@5" --save
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
  • -**변경된 항목** +**개선된 항목** -**개선된 항목** +**변경된 항목** -

    제거된 메소드 및 특성

    +### 제거된 메소드 및 특성 앱에서 이러한 메소드 또는 특성 중 어느 하나라도 사용한다면 앱에서 충돌이 발생합니다. 따라서 버전 5로 업데이트한 후에는 앱을 변경해야 합니다. @@ -67,19 +94,73 @@ Express 5는 `app.del()` 함수를 더 이상 지원하지 않습니다. 이 함 `delete`는 JavaScript의 예약된 키워드이므로, 처음에는 `delete` 대신 `del`이 사용되었습니다. 그러나, ECMAScript 6을 기준으로, `delete` 및 다른 예약된 키워드를 정식 특성 이름으로 사용할 수 있게 되었습니다. +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +``` +

    app.param(fn)

    `app.param(fn)` 시그니처는 `app.param(name, fn)` 함수의 작동을 수정하는 데 사용되었습니다. 이 시그니처는 v4.11.0 이후 더 이상 사용되지 않았으며 Express 5에서는 전혀 지원되지 않습니다.

    복수형의 메소드 이름

    -다음과 같은 메소드 이름은 이제 복수형이 되었습니다. Express 4에서는 구버전의 메소드를 사용하면 사용 중단 경고가 표시되었습니다. Express 5는 구버전의 메소드를 전혀 지원하지 않습니다. +다음과 같은 메소드 이름은 이제 복수형이 되었습니다. Express 4에서는 구버전의 메소드를 사용하면 사용 중단 경고가 표시되었습니다. Express 5는 구버전의 메소드를 전혀 지원하지 않습니다. + +`req.acceptsLanguage()`는 `req.acceptsLanguages()`로 대체되었습니다. `req.acceptsCharset()`는 `req.acceptsCharsets()`로 대체되었습니다. `req.acceptsEncoding()`은 `req.acceptsEncodings()`로 대체되었습니다. -`req.acceptsLanguage()`는 `req.acceptsLanguages()`로 대체되었습니다. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    app.param(name, fn)에 대한 이름(name)의 첫머리 콜론(:)

    @@ -91,43 +172,334 @@ Express 5는 `app.del()` 함수를 더 이상 지원하지 않습니다. 이 함 양식 데이터 검색을 위한 이 메소드는 혼란과 위험을 발생시킬 수 있으므로 제거되었습니다. 이제는 `req.params`, `req.body` 또는 `req.query` 오브젝트에서 제출된 매개변수 이름을 구체적으로 확인해야 합니다. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

    res.json(obj, status)

    Express 5는 `res.json(obj, status)` 시그니처를 더 이상 지원하지 않습니다. 대신, 상태를 설정한 후 이를 `res.status(status).json(obj)`과 같은 `res.json()` 메소드에 체인해야 합니다. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

    res.jsonp(obj, status)

    Express 5는 `res.jsonp(obj, status)` 시그니처를 더 이상 지원하지 않습니다. 대신, 상태를 설정한 후 이를 `res.status(status).jsonp(obj)`와 같은 `res.jsonp()` 메소드에 체인해야 합니다. -

    res.send(body, status)

    +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    Express 5는 `res.send(obj, status)` 시그니처를 더 이상 지원하지 않습니다. 대신, 상태를 설정한 후 이를 `res.status(status).send(obj)`와 같은 `res.send()` 메소드에 체인해야 합니다. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

    res.send(body, status)

    + +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

    res.send(status)

    -Express 5는 *`status`*가 숫자인 res.send(status) 시그니처를 더 이상 지원하지 않습니다. 대신, HTTP 응답 헤더 상태 코드를 설정하고 해당 코드의 텍스트 버전("Not Found", "Internal Server Error" 등)을 전송하는 `res.sendStatus(statusCode)` 함수를 사용해야 합니다. +Express 5는 \*`status`\*가 숫자인 res.send(status) 시그니처를 더 이상 지원하지 않습니다. 대신, HTTP 응답 헤더 상태 코드를 설정하고 해당 코드의 텍스트 버전("Not Found", "Internal Server Error" 등)을 전송하는 `res.sendStatus(statusCode)` 함수를 사용해야 합니다. `res.send()` 함수를 이용해 숫자를 전송해야 하는 경우, Express가 그 숫자를 지원되지 않는 구버전 시그니처 사용 시도로 해석하지 않도록 숫자의 앞뒤에 따옴표를 추가하여 숫자를 문자열로 변환하십시오. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +``` +

    res.sendfile()

    Express 5에서 `res.sendfile()` 함수는 낙타 대문자(camel-cased) 버전인 `res.sendFile()`로 대체되었습니다. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. 이 시그니처는 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. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    변경된 항목

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. 예를 들면 다음과 같습니다. + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +예를 들면 다음과 같습니다. + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    Express 4에서 제거되었던 `app.router` 오브젝트가 Express 5에 되돌아왔습니다. Express 3에서는 앱이 이 오브젝트를 명시적으로 로드해야 했던 것과 달리, 새 버전에서 이 오브젝트는 단순히 기본 Express 라우터에 대한 참조의 역할을 합니다. +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

    req.host

    Express 4에서, 포트 번호가 존재하는 경우 `req.host` 함수는 포트 번호를 올바르지 않게 제거했습니다. Express 5에서는 포트 번호가 유지됩니다.

    req.query

    -Express 4.7 및 Express 5 버전 이상에서는, 조회 문자열 구문 분석 로직을 위해 자체적인 함수를 사용하기 원할 때 조회 문자열 구문 분석을 사용하지 않도록 하는 `false`를 조회 구문 분석기 옵션으로 사용할 수 있습니다. +The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from "extended" to "simple". -

    개선된 항목

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### 개선된 항목

    res.render()

    이 메소드는 이제 모든 보기 엔진에 대해 비동기식 작동을 적용하며, 동기식 구현을 갖는 보기 엔진 및 권장되는 인터페이스를 위반하는 보기 엔진에 의한 버그의 발생을 방지합니다. + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/ko/guide/overriding-express-api.md b/ko/guide/overriding-express-api.md new file mode 100644 index 0000000000..531bdd1e64 --- /dev/null +++ b/ko/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: ko +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/ko/guide/routing.md b/ko/guide/routing.md old mode 100755 new mode 100644 index 3b38a4a70e..0781d521c6 --- a/ko/guide/routing.md +++ b/ko/guide/routing.md @@ -1,17 +1,28 @@ --- layout: page title: Express 라우팅 +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: ko -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # 라우팅 -*라우팅*은 애플리케이션 엔드 포인트(URI)의 정의, 그리고 URI가 클라이언트 요청에 응답하는 방식을 말합니다. +_라우팅_은 애플리케이션 엔드 포인트(URI)의 정의, 그리고 URI가 클라이언트 요청에 응답하는 방식을 말합니다. 라우팅에 대한 소개는 [기본 라우팅](/{{ page.lang }}/starter/basic-routing.html)을 참조하십시오. +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) for details). + +특수한 라우팅 메소드인 `app.all()`은 어떠한 HTTP 메소드로부터도 파생되지 않습니다. 이 메소드는 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용됩니다. + +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. + 다음 코드는 매우 기본적인 라우트의 예입니다. ```js @@ -43,16 +54,9 @@ app.post('/', (req, res) => { ``` Express는 HTTP 메소드에 해당하는 다음과 같은 라우팅 메소드를 지원합니다. -`get`, `post`, `put`, `head`, `delete`, `options`, `trace`, `copy`, `lock`, `mkcol`, `move`, `purge`, `propfind`, `proppatch`, `unlock`, `report`, `mkactivity`, `checkout`, `merge`, `m-search`, `notify`, `subscribe`, `unsubscribe`, `patch`, `search` 및 `connect`. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -
    -올바르지 않은 JavaScript 변수 이름으로 변환되는 메소드를 라우팅하려면 대괄호 표기법을 사용하십시오. 예를 들면 -`app['m-search']('/', function ...` 등과 같습니다. -
    - -특수한 라우팅 메소드인 `app.all()`은 어떠한 HTTP 메소드로부터도 파생되지 않습니다. 이 메소드는 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용됩니다. - -다음 예에서는, GET, POST, PUT 또는 DELETE 메소드를 사용하는 경우, 또는 [http 모듈](https://nodejs.org/api/http.html#http_http_methods)에서 지원되는 기타 모든 HTTP 요청 메소드를 사용하는 경우 등의 "/secret"에 대한 요청을 위하여 핸들러가 실행됩니다. +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). ```js app.all('/secret', (req, res, next) => { @@ -65,15 +69,32 @@ app.all('/secret', (req, res, next) => { 라우트 경로는, 요청 메소드와의 조합을 통해, 요청이 이루어질 수 있는 엔드포인트를 정의합니다. 라우트 경로는 문자열, 문자열 패턴 또는 정규식일 수 있습니다. -
    - Express는 라우트 경로의 일치를 위해 [path-to-regexp](https://www.npmjs.com/package/path-to-regexp)를 사용합니다. 라우트 경로를 정의할 수 있는 모든 가능성을 확인하려면 path-to-regexp 문서를 참조하십시오. [Express Route Tester](http://forbeslindesay.github.io/express-route-tester/)는 기본적인 Express 라우트의 테스트를 위한 편리한 도구이지만, 패턴 일치는 지원하지 않습니다. -
    +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
    -조회 문자열은 라우트 경로의 일부가 아닙니다. -
    +{% include admonitions/caution.html content=caution-character %} + +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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 Route Tester](http://forbeslindesay.github.io/express-route-tester/)는 기본적인 Express 라우트의 테스트를 위한 편리한 도구이지만, 패턴 일치는 지원하지 않습니다. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} -문자열을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다. +{% capture query-string-note %} + +Query strings are not part of the route path. + +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### 문자열을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다. 다음의 라우트 경로는 요청을 루트 라우트 `/`에 일치시킵니다. @@ -99,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -문자열 패턴을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다. +### 문자열 패턴을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다. + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} 다음의 라우트 경로는 `acd` 및 `abcd`와 일치합니다. @@ -133,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
    -?, +, * 및 () 문자는 정규식 문자의 서브세트입니다. 하이픈(-) 및 점(.)은 문자열 기반 경로에 의해 문자 그대로 해석됩니다. -
    - -정규식을 기반으로 하는 라우트 경로의 예: +### 정규식을 기반으로 하는 라우트 경로의 예: 다음의 라우트 경로는 라우트 이름에 "a"가 포함된 모든 항목과 일치합니다. @@ -155,13 +176,80 @@ app.get(/.*fly$/, (req, res) => { }) ``` +

    +조회 문자열은 라우트 경로의 일부가 아닙니다. +

    + +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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
    +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} +

    라우트 핸들러

    [미들웨어](/{{ page.lang }}/guide/using-middleware.html)와 비슷하게 작동하는 여러 콜백 함수를 제공하여 요청을 처리할 수 있습니다. 유일한 차이점은 이러한 콜백은 `next('route')`를 호출하여 나머지 라우트 콜백을 우회할 수도 있다는 점입니다. 이러한 메커니즘을 이용하면 라우트에 대한 사전 조건을 지정한 후, 현재의 라우트를 계속할 이유가 없는 경우에는 제어를 후속 라우트에 전달할 수 있습니다. 다음 예에 나타난 것과 같이, 라우트 핸들러는 함수나 함수 배열의 형태 또는 둘을 조합한 형태일 수 있습니다. -하나의 콜백 함수는 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. +하나의 콜백 함수는 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. ```js app.get('/example/a', (req, res) => { @@ -179,7 +267,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. + +하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. ```js const cb0 = function (req, res, next) { @@ -199,7 +288,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. +독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다. ```js const cb0 = function (req, res, next) { @@ -224,17 +313,17 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => { 다음 표에 표시된 응답 오브젝트에 대한 메소드(`res`)는 응답을 클라이언트로 전송하고 요청-응답 주기를 종료할 수 있습니다. 라우트 핸들러로부터 다음 메소드 중 어느 하나도 호출되지 않는 경우, 클라이언트 요청은 정지된 채로 방치됩니다. -| 메소드 | 설명 -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | 파일이 다운로드되도록 프롬프트합니다. -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | 응답 프로세스를 종료합니다. -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | JSON 응답을 전송합니다. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | JSONP 지원을 통해 JSON 응답을 전송합니다. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 요청의 경로를 재지정합니다. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | 보기 템플리트를 렌더링합니다. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 다양한 유형의 응답을 전송합니다. -| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 파일을 옥텟 스트림의 형태로 전송합니다. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송합니다. +| 메소드 | 설명 | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | 파일이 다운로드되도록 프롬프트합니다. | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | 응답 프로세스를 종료합니다. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | JSON 응답을 전송합니다. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | JSONP 지원을 통해 JSON 응답을 전송합니다. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 요청의 경로를 재지정합니다. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | 보기 템플리트를 렌더링합니다. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 다양한 유형의 응답을 전송합니다. | +| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 파일을 옥텟 스트림의 형태로 전송합니다. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송합니다. |

    app.route()

    @@ -269,10 +358,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -290,9 +381,15 @@ module.exports = router ```js const birds = require('./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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/ko/guide/using-middleware.md b/ko/guide/using-middleware.md old mode 100755 new mode 100644 index ce405fadb0..872d298c5c --- a/ko/guide/using-middleware.md +++ b/ko/guide/using-middleware.md @@ -1,34 +1,34 @@ --- layout: page title: Express 미들웨어 사용 +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: ko -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # 미들웨어 사용 Express는 자체적인 최소한의 기능을 갖춘 라우팅 및 미들웨어 웹 프레임워크이며, Express 애플리케이션은 기본적으로 일련의 미들웨어 함수 호출입니다. -*미들웨어* 함수는 [요청 오브젝트](/{{ page.lang }}/4x/api.html#req)(`req`), [응답 오브젝트](/{{ page.lang }}/4x/api.html#res) (`res`), 그리고 애플리케이션의 요청-응답 주기 중 그 다음의 미들웨어 함수 대한 액세스 권한을 갖는 함수입니다. 그 다음의 미들웨어 함수는 일반적으로 `next`라는 이름의 변수로 표시됩니다. +_미들웨어_ 함수는 [요청 오브젝트](/{{ page.lang }}/4x/api.html#req)(`req`), [응답 오브젝트](/{{ page.lang }}/4x/api.html#res) (`res`), 그리고 애플리케이션의 요청-응답 주기 중 그 다음의 미들웨어 함수 대한 액세스 권한을 갖는 함수입니다. 그 다음의 미들웨어 함수는 일반적으로 `next`라는 이름의 변수로 표시됩니다. 미들웨어 함수는 다음과 같은 태스크를 수행할 수 있습니다. -* 모든 코드를 실행. -* 요청 및 응답 오브젝트에 대한 변경을 실행. -* 요청-응답 주기를 종료. -* 스택 내의 그 다음 미들웨어 함수를 호출. +- 모든 코드를 실행. +- 요청 및 응답 오브젝트에 대한 변경을 실행. +- 요청-응답 주기를 종료. +- 스택 내의 그 다음 미들웨어 함수를 호출. 현재의 미들웨어 함수가 요청-응답 주기를 종료하지 않는 경우에는 `next()`를 호출하여 그 다음 미들웨어 함수에 제어를 전달해야 합니다. 그렇지 않으면 해당 요청은 정지된 채로 방치됩니다. Express 애플리케이션은 다음과 같은 유형의 미들웨어를 사용할 수 있습니다. - - [애플리케이션 레벨 미들웨어](#middleware.application) - - [라우터 레벨 미들웨어](#middleware.router) - - [오류 처리 미들웨어](#middleware.error-handling) - - [기본 제공 미들웨어](#middleware.built-in) - - [써드파티 미들웨어](#middleware.third-party) +- [애플리케이션 레벨 미들웨어](#middleware.application) +- [라우터 레벨 미들웨어](#middleware.router) +- [오류 처리 미들웨어](#middleware.error-handling) +- [기본 제공 미들웨어](#middleware.built-in) +- [써드파티 미들웨어](#middleware.third-party) 애플리케이션 레벨 및 라우터 레벨 미들웨어는 선택적인 마운트 경로를 통해 로드할 수 있습니다. 일련의 미들웨어 함수를 함께 로드할 수도 있으며, 이를 통해 하나의 마운트 위치에 미들웨어 시스템의 하위 스택을 작성할 수 있습니다. @@ -40,6 +40,7 @@ Express 애플리케이션은 다음과 같은 유형의 미들웨어를 사용 다음 예에는 마운트 경로가 없는 미들웨어 함수가 표시되어 있습니다. 이 함수는 앱이 요청을 수신할 때마다 실행됩니다. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -93,12 +94,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` 라우터 미들웨어 스택의 나머지 미들웨어 함수들을 건너뛰려면 `next('route')`를 호출하여 제어를 그 다음 라우트로 전달하십시오. -**참고**: `next('route')`는 `app.METHOD()` 또는 `router.METHOD()` 함수를 이용해 로드된 미들웨어 함수에서만 작동합니다. + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} 다음 예에는 `/user/:id` 경로에 대한 GET 요청을 처리하는 미들웨어 하위 스택이 표시되어 있습니다. @@ -107,15 +115,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +아래에는 상세한 옵션 오브젝트와 함께 `express.static` 미들웨어 함수를 사용하는 예가 표시되어 있습니다. + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -126,11 +155,13 @@ app.get('/user/:id', (req, res, next) => { ```js const router = express.Router() ``` + `router.use()` 및 `router.METHOD()` 함수를 사용하여 라우터 레벨 미들웨어를 로드하십시오. 다음 예의 코드는 위에서 애플리케이션 레벨 미들웨어에 대해 표시된 미들웨어 시스템을 라우터 레벨 미들웨어를 사용하여 복제합니다. ```js +const express = require('express') const app = express() const router = express.Router() @@ -154,7 +185,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -169,10 +200,37 @@ router.get('/user/:id', (req, res, next) => { // 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. + +다음 예에는 `/user/:id` 경로에 대한 GET 요청을 처리하는 미들웨어 하위 스택이 표시되어 있습니다. + +```js +const express = require('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` 오브젝트를 사용할 필요는 없지만, 시그니처를 유지하기 위해 해당 오브젝트를 지정해야 합니다. 그렇지 않으면 `next` 오브젝트는 일반적인 미들웨어로 해석되어 오류 처리에 실패하게 됩니다. +오류 처리 미들웨어에는 항상 *4개*의 인수가 필요합니다. 어떠한 함수를 오류 처리 미들웨어 함수로 식별하려면 4개의 인수를 제공해야 합니다. `next` 오브젝트를 사용할 필요는 없지만, 시그니처를 유지하기 위해 해당 오브젝트를 지정해야 합니다. 그렇지 않으면 `next` 오브젝트는 일반적인 미들웨어로 해석되어 오류 처리에 실패하게 됩니다.
    다른 미들웨어 함수와 동일반 방법으로 다음과 같이 오류 처리 미들웨어 함수를 정의할 수 있지만, 오류 처리 함수는 3개가 아닌 4개의 인수, 구체적으로 말하면 `(err, req, res, next)` 시그니처를 갖는다는 점이 다릅니다. @@ -186,59 +244,18 @@ app.use((err, req, res, next) => { 오류 처리 미들웨어에 대한 상세 정보는 [오류 처리](/{{ page.lang }}/guide/error-handling.html)를 참조하십시오. -

    기본 제공 미들웨어

    +

    Built-in middleware

    4.x 버전 이후의 Express는 더 이상 [Connect](https://github.com/senchalabs/connect)에 종속되지 않습니다. `express.static`의 실행을 제외하면, 이전에 Express와 함께 포함되었던 모든 미들웨어 함수는 이제 별도의 모듈에 포함되어 있습니다. [미들웨어 함수 목록](https://github.com/senchalabs/connect#middleware)을 확인하십시오. -

    express.static(root, [options])

    - -Express의 유일한 기본 제공 미들웨어 함수는 `express.static`입니다. 이 함수는 [serve-static](https://github.com/expressjs/serve-static)을 기반으로 하며, Express 애플리케이션의 정적 자산을 제공하는 역할을 합니다. - -`root` 인수는 정적 자산의 제공을 시작하는 위치가 되는 루트 디렉토리를 지정합니다. - -선택사항인 `options` 오브젝트는 다음과 같은 특성을 가질 수 있습니다. - -| 특성 | 설명 | 유형 | 기본값 | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | dotfile을 제공하기 위한 옵션입니다. 사용 가능한 값은 "allow", "deny" 및 "ignore"입니다. | 문자열 | "ignore" | -| `etag` | etag의 생성을 사용 또는 사용 안함으로 설정합니다. | 부울 | `true` | -| `extensions` | 파일 확장자 폴백을 설정합니다. | 배열 | `[]` | -| `index` | 디렉토리 인덱스 파일을 전송합니다. 디렉토리 인덱스 작성을 사용하지 않으려면 `false`를 설정하십시오. | 혼합 | "index.html" | - `lastModified` | OS에서 해당 파일이 마지막으로 수정된 날짜를 `Last-Modified` 헤더에 설정합니다. 사용 가능한 값은 `true` 또는 `false`입니다. | 부울 | `true` | -| `maxAge` | 밀리초 또는 [ms 형식](https://www.npmjs.org/package/ms)의 문자열로 Cache-Control 헤더의 max-age 특성을 설정합니다. | 숫자 | 0 | -| `redirect` | 경로 이름이 디렉토리인 경우 후미부의 "/"로 경로를 재지정합니다. | 부울 | `true` | -| `setHeaders` | 파일을 제공하도록 HTTP 헤더를 설정하기 위한 함수입니다. | 함수 | | - -아래에는 상세한 옵션 오브젝트와 함께 `express.static` 미들웨어 함수를 사용하는 예가 표시되어 있습니다. - -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -다음과 같이, 하나의 앱은 2개 이상의 정적 디렉토리를 가질 수 있습니다. - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` +Express has the following built-in middleware functions: -`serve-static` 함수 및 그 옵션에 대한 자세한 정보는 [serve-static](https://github.com/expressjs/serve-static) 문서를 참조하십시오. +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+** -

    써드파티 미들웨어

    +

    Third-party middleware

    Express 앱에 기능을 추가하려면 써드파티 미들웨어를 사용하십시오. diff --git a/ko/guide/using-template-engines.md b/ko/guide/using-template-engines.md old mode 100755 new mode 100644 index a662a2d070..7bed81e016 --- a/ko/guide/using-template-engines.md +++ b/ko/guide/using-template-engines.md @@ -1,18 +1,25 @@ --- layout: page title: Express와 함께 템플리트 엔진 사용 +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: ko -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- -# Express와 함께 템플리트 엔진을 사용 +# Express와 함께 템플리트 엔진 사용 -Express가 템플리트를 렌더링하려면 다음과 같은 애플리케이션 설정이 필요합니다. +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. -* `views`, 템플리트가 있는 디렉토리. 예: `app.set('views', './views')` -* `view engine`, 사용할 템플리트 엔진. 예: `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, 템플리트가 있는 디렉토리. 예: `app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, 사용할 템플리트 엔진. 예: `app.set('view engine', 'pug')` 이후 그에 맞는 템플리트 엔진 npm 패키지를 다음과 같이 설치하십시오. @@ -24,6 +31,7 @@ $ npm install pug --save Express와 호환되는 템플리트 엔진(예: Pug)은 `__express(filePath, options, callback)`라는 이름의 함수를 내보내며, 이 함수는 `res.render()` 함수에 의해 호출되어 템플리트 코드를 렌더링합니다. 일부 템플리트 엔진은 이러한 방식을 따르지 않습니다. [Consolidate.js](https://www.npmjs.org/package/consolidate) 라이브러리는 널리 이용되고 있는 모든 Node.js 템플리트 엔진을 맵핑함으로써 이러한 방식을 따르므로 Express 내에서 완벽하게 작동합니다. +
    보기 엔진을 설정한 후에는 앱에서 엔진을 지정하거나 템플리트 엔진 모듈을 로드할 필요가 없으며, Express는 아래에 표시된 것과 같이 내부적으로 모듈을 로드합니다(위의 예에 대한 코드). @@ -52,4 +60,4 @@ app.get('/', (req, res) => { 홈 페이지에 대한 요청을 실행할 때, `index.pug` 파일은 HTML 형식으로 렌더링됩니다. -Express에서 템플리트 엔진이 작동하는 방식에 대한 자세한 내용을 확인하려면 ["Express용 템플리트 엔진 개발"](/{{ page.lang }}/advanced/developing-template-engines.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/ko/guide/writing-middleware.md b/ko/guide/writing-middleware.md old mode 100755 new mode 100644 index bd7bb06554..653092ee44 --- a/ko/guide/writing-middleware.md +++ b/ko/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: Express 앱에서 사용하기 위한 미들웨어 작성 +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: ko -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- # Express 앱에서 사용하기 위한 미들웨어 작성

    개요

    -*미들웨어* 함수는 [요청 오브젝트](/{{ page.lang }}/4x/api.html#req)(`req`), [응답 오브젝트](/{{ page.lang }}/4x/api.html#res) (`res`), 그리고 애플리케이션의 요청-응답 주기 중 그 다음의 미들웨어 함수 대한 액세스 권한을 갖는 함수입니다. 그 다음의 미들웨어 함수는 일반적으로 `next`라는 이름의 변수로 표시됩니다. +_미들웨어_ 함수는 [요청 오브젝트](/{{ page.lang }}/4x/api.html#req)(`req`), [응답 오브젝트](/{{ page.lang }}/4x/api.html#res) (`res`), 그리고 애플리케이션의 요청-응답 주기 중 그 다음의 미들웨어 함수 대한 액세스 권한을 갖는 함수입니다. 그 다음의 미들웨어 함수는 일반적으로 `next`라는 이름의 변수로 표시됩니다. 미들웨어 함수는 다음과 같은 태스크를 수행할 수 있습니다. -* 모든 코드를 실행. -* 요청 및 응답 오브젝트에 대한 변경을 실행. -* 요청-응답 주기를 종료. -* 스택 내의 그 다음 미들웨어를 호출. +- 모든 코드를 실행. +- 요청 및 응답 오브젝트에 대한 변경을 실행. +- 요청-응답 주기를 종료. +- 스택 내의 그 다음 미들웨어를 호출. 현재의 미들웨어 함수가 요청-응답 주기를 종료하지 않는 경우에는 `next()`를 호출하여 그 다음 미들웨어 함수에 제어를 전달해야 합니다. 그렇지 않으면 해당 요청은 정지된 채로 방치됩니다. 다음 예시에 미들웨어 함수 호출의 요소가 표시되어 있습니다. -
    미들웨어 함수가 적용되는 경로(라우트).
    @@ -43,7 +43,14 @@ description: Learn how to write custom middleware functions for Express.js appli
    +
    Elements of a middleware function call -
    미들웨어 함수가 적용되는 HTTP 메소드.
    +
    미들웨어 함수가 적용되는 HTTP 메소드.
    +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. + +

    Example

    + 아래에는 간단한 "Hello World" Express 애플리케이션에 대한 예가 표시되어 있으며, 이 애플리케이션을 위해 두 개의 미들웨어 함수를 정의하게 됩니다. +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 const express = require('express') @@ -56,8 +63,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    개발

    - +

    Middleware function myLogger

    아래에는 "myLogger"라는 이름의 미들웨어 함수에 대한 간단한 예가 표시되어 있습니다. 이 함수는 앱에 대한 요청이 해당 함수를 거쳐 전달될 때 단순히 "LOGGED"를 인쇄합니다. 이 미들웨어 함수는 `myLogger`라는 이름의 변수에 지정되어 있습니다. ```js @@ -68,8 +74,9 @@ const myLogger = function (req, res, next) { ```
    -위의 예에서 `next()`에 대한 호출에 주목하십시오. 이 함수를 호출하면 앱 내의 그 다음 미들웨어 함수가 호출됩니다. -`next()` 함수는 Node.js 또는 Express API의 일부가 아니지만, 미들웨어 함수에 전달되는 세 번째 인수입니다. `next()` 함수에는 어떠한 이름을 지정해도 좋지만, 일반적으로 항상 "next"라는 이름을 갖습니다. 혼란을 방지하려면 항상 이러한 방식을 사용하십시오. +위의 예에서 `next()`에 대한 호출에 주목하십시오. 이 함수를 호출하면 앱 내의 그 다음 미들웨어 함수가 호출됩니다. +`next()` 함수는 Node.js 또는 Express API의 일부가 아니지만, 미들웨어 함수에 전달되는 세 번째 인수입니다. `next()` 함수에는 어떠한 이름을 지정해도 좋지만, 일반적으로 항상 "next"라는 이름을 갖습니다. +혼란을 방지하려면 항상 이러한 방식을 사용하십시오.
    미들웨어 함수를 로드하려면 미들웨어 함수를 지정하여 `app.use()`를 호출하십시오. @@ -101,6 +108,8 @@ app.listen(3000) 미들웨어 함수 `myLogger`는 단순히 메시지를 인쇄한 후 `next()` 함수를 호출하여 스택 내의 그 다음 미들웨어 함수에 요청을 전달합니다. +

    Middleware function requestTime

    + 다음 예에서는 `requestTime`라는 특성을 요청 오브젝트에 추가합니다. 이 미들웨어 함수는 "requestTime"이라고 명명하겠습니다. ```js @@ -131,8 +140,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + 앱의 루트에 대한 요청을 실행할 때, 앱은 이제 요청의 타임스탬프를 브라우저에 표시합니다. +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + 사용자는 요청 오브젝트, 응답 오브젝트, 스택 내의 그 다음 미들웨어 함수, 그리고 모든 Node.js API에 대한 액세스 권한을 가지고 있으므로, 미들웨어 함수에 대한 가능성은 끝이 없습니다. Express 미들웨어에 대한 자세한 정보는 [Express 미들웨어 사용](/{{ page.lang }}/guide/using-middleware.html)을 참조하십시오. + +

    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 +module.exports = 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') + +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. diff --git a/ko/resources/community.md b/ko/resources/community.md old mode 100755 new mode 100644 index 3438945981..d3fe4f8931 --- a/ko/resources/community.md +++ b/ko/resources/community.md @@ -1,28 +1,93 @@ --- layout: page title: Express 커뮤니티 +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: ko -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # 커뮤니티 +## 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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +활기찬 커뮤니티에서는 매우 다양한 확장기능, [미들웨어 모듈](/{{ page.lang }}/resources/middleware.html) +및 상위 레벨 프레임워크가 개발되어 왔습니다. + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). + +## 문제 + +버그라고 생각되는 현상을 겪었거나, 기능에 대한 요청을 하기 원하는 경우에는 +[issue queue](https://github.com/expressjs/express/issues)에서 티켓을 작성하십시오. + ## 예제 API 설계에서부터 인증 및 템플리트 엔진 통합에 이르는 모든 주제를 다루는 저장소에서 수십 개의 Express 애플리케이션 [예제](https://github.com/expressjs/express/tree/master/examples)를 확인하십시오. -## 문제 +## Github Discussions -버그라고 생각되는 현상을 겪었거나, 기능에 대한 요청을 하기 원하는 경우에는 -[issue queue](https://github.com/expressjs/express/issues)에서 티켓을 작성하십시오. +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. -## 써드파티 +# Branding of Express.js -활기찬 커뮤니티에서는 매우 다양한 확장기능, [미들웨어 모듈](/{{ page.lang }}/resources/middleware.html) -및 상위 레벨 프레임워크가 개발되어 왔습니다. [wiki](https://github.com/expressjs/express/wiki)에서 -이 모두를 확인해 보십시오. +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/ko/resources/contributing.md b/ko/resources/contributing.md new file mode 100644 index 0000000000..765b19e29d --- /dev/null +++ b/ko/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: ko +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/ko/resources/glossary.md b/ko/resources/glossary.md old mode 100755 new mode 100644 index ce54b24844..4a6706232e --- a/ko/resources/glossary.md +++ b/ko/resources/glossary.md @@ -1,58 +1,66 @@ --- layout: page title: Express 용어집 +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. menu: resources lang: ko -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. +redirect_from: " " --- # 용어집 -### 라우터(router) +### 애플리케이션(application) -API 참조의 [라우터](/{{ page.lang }}/4x/api.html#router)를 참조하십시오. +일반적으로, 특정한 목적의 연산을 수행하도록 설계된 하나 이상의 프로그램입니다. Express의 컨텍스트에서는, Node.js 플랫폼에서 실행되며 Express API를 사용하는 프로그램을 말합니다. 또한 [앱 오브젝트](/{{ page.lang }}/api.html#express)를 지칭할 수도 있습니다. -### 라우트(route) +### API -자원을 식별하는 URL의 일부입니다. 예를 들면, `http://foo.com/products/id`에서 "/products/id"가 라우트입니다. +애플리케이션 프로그래밍 인터페이스(Application Programming Interface)입니다. 이 용어를 최초로 사용할 때는 약어를 풀어서 기재하십시오. -### 미들웨어(middleware) +### Express -최종 요청 핸들러 이전의 Express 라우팅 계층에 의해 호출되는 함수이며, 따라서 원시 요청과 의도된 최종 라우트 사이의 미들웨어에 위치합니다. 미들웨어와 관련된 용어의 몇 가지 요점은 다음과 같습니다. +Node.js 애플리케이션을 위한 빠르고 개방적인 간결한 웹 프레임워크입니다. 일반적으로 "Express.js"보다 "Express"가 선호되지만, "Express.js"도 허용됩니다. - * `var foo = require('middleware')`는 Node.js 모듈을 *요구* 또는 *사용*하는 것으로 일컬어집니다. 이후 `var mw = foo()` 명령문은 일반적으로 미들웨어를 리턴합니다. - * `app.use(mw)`는 *미들웨어를 전역 처리 스택에 추가*하는 것으로 일컬어집니다. - * `app.get('/foo', mw, function (req, res) { ... })`는 *미들웨어를 "GET /foo" 처리 스택에 추가*하는 것으로 일컬어집니다. +### libuv -### 애플리케이션(application) +비동기식 I/O에 초점을 둔 멀티플랫폼 지원 라이브러리이며, 주로 Node.js에 의해 사용되도록 개발됩니다. -일반적으로, 특정한 목적의 연산을 수행하도록 설계된 하나 이상의 프로그램입니다. Express의 컨텍스트에서는, Node.js 플랫폼에서 실행되며 Express API를 사용하는 프로그램을 말합니다. 또한 [앱 오브젝트](/{{ page.lang }}/api.html#express)를 지칭할 수도 있습니다. +### middleware + +최종 요청 핸들러 이전의 Express 라우팅 계층에 의해 호출되는 함수이며, 따라서 원시 요청과 의도된 최종 라우트 사이의 미들웨어에 위치합니다. 미들웨어와 관련된 용어의 몇 가지 요점은 다음과 같습니다. + +- `var foo = require('middleware')`는 Node.js 모듈을 _요구_ 또는 _사용_하는 것으로 일컬어집니다. 이후 `var mw = foo()` 명령문은 일반적으로 미들웨어를 리턴합니다. +- `app.use(mw)`는 _미들웨어를 전역 처리 스택에 추가_하는 것으로 일컬어집니다. +- `app.get('/foo', mw, function (req, res) { ... })`는 _미들웨어를 "GET /foo" 처리 스택에 추가_하는 것으로 일컬어집니다. + +### Node.js + +확장 가능한 네트워크 애플리케이션을 개발하는 데 사용되는 소프트웨어 플랫폼입니다. Node.js는 JavaScript를 스크립팅 언어로 사용하며, 방해하지 않는 I/O 및 단일 스레드 이벤트 루프를 통해 높은 처리량을 달성합니다. [nodejs.org](http://nodejs.org/)를 참조하십시오. **활용 참고**: 최초에는 "Node.js"였으며 이후 "Node"가 되었습니다. ### 오픈 소스(open-source, open source) -영문에서 형용사로 사용될 때는 하이픈이 사용됩니다. (예: "이 소프트웨어는 오픈 소스 소프트웨어입니다" [Wikipedia의 Open-source software](http://en.wikipedia.org/wiki/Open-source_software)를 참조하십시오.) 참고로 영문에서 이 용어에 하이픈이 사용되지 않는 경우가 흔하지만, 여기서는 합성 형용사에 하이픈을 추가하는 표준 영문 규칙을 사용합니다. +When used as an adjective, hyphenate; for example: "This is open-source software." (예: "이 소프트웨어는 오픈 소스 소프트웨어입니다" [Wikipedia의 Open-source software](http://en.wikipedia.org/wiki/Open-source_software)를 참조하십시오.) -### 요청(request) +{% capture english-rules %} -HTTP 요청입니다. 클라이언트는 HTTP 요청 메시지를 서버에 제출하며, 서버는 응답을 리턴합니다. 요청은 여러 [요청 메소드](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) 중 하나를 사용해야 합니다(예: GET, POST 등). +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. -### 응답(response) +{% endcapture %} -HTTP 응답입니다. 서버는 HTTP 응답 메시지를 클라이언트에 리턴합니다. 응답에는 요청에 대한 완료 상태 정보가 포함되어 있으며 응답 메시지 본문에는 요청된 컨텐츠가 포함되어 있을 수도 있습니다. +{% include admonitions/note.html content=english-rules %} -### API +### 요청(request) -애플리케이션 프로그래밍 인터페이스(Application Programming Interface)입니다. 이 용어를 최초로 사용할 때는 약어를 풀어서 기재하십시오. +HTTP 요청입니다. 클라이언트는 HTTP 요청 메시지를 서버에 제출하며, 서버는 응답을 리턴합니다. 요청은 여러 [요청 메소드](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) 중 하나를 사용해야 합니다(예: GET, POST 등). -### Express +### 응답(response) -Node.js 애플리케이션을 위한 빠르고 개방적인 간결한 웹 프레임워크입니다. 일반적으로 "Express.js"보다 "Express"가 선호되지만, "Express.js"도 허용됩니다. +HTTP 응답입니다. 서버는 HTTP 응답 메시지를 클라이언트에 리턴합니다. 응답에는 요청에 대한 완료 상태 정보가 포함되어 있으며 응답 메시지 본문에는 요청된 컨텐츠가 포함되어 있을 수도 있습니다. -### libuv +### 라우트(route) -비동기식 I/O에 초점을 둔 멀티플랫폼 지원 라이브러리이며, 주로 Node.js에 의해 사용되도록 개발됩니다. +자원을 식별하는 URL의 일부입니다. 예를 들면, `http://foo.com/products/id`에서 "/products/id"가 라우트입니다. -### Node.js +### 라우터(router) -확장 가능한 네트워크 애플리케이션을 개발하는 데 사용되는 소프트웨어 플랫폼입니다. Node.js는 JavaScript를 스크립팅 언어로 사용하며, 방해하지 않는 I/O 및 단일 스레드 이벤트 루프를 통해 높은 처리량을 달성합니다. [nodejs.org](http://nodejs.org/)를 참조하십시오. **활용 참고**: 최초에는 "Node.js"였으며 이후 "Node"가 되었습니다. +API 참조의 [라우터](/{{ page.lang }}/4x/api.html#router)를 참조하십시오. diff --git a/ko/resources/middleware.md b/ko/resources/middleware.md old mode 100755 new mode 100644 index 6339ef7e6c..c39696e5cc --- a/ko/resources/middleware.md +++ b/ko/resources/middleware.md @@ -1,58 +1,44 @@ --- -layout: page +layout: middleware title: Express 미들웨어 +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. menu: resources lang: ko -redirect_from: /resources/middleware.html +redirect_from: " " module: mw-home -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. --- ## Express 미들웨어 목록에 적힌 Express 미들웨어 모듈들은 [Expressjs 팀](https://github.com/orgs/expressjs/people)이 유지보수합니다. -| 미들웨어 모듈 | 설명 | 내장 함수 (Express 3)| -|---------------------------|---------------------|----------------------| -| [body-parser](/resources/middleware/body-parser.html) | HTTP 요청 body를 파싱합니다. [body](https://github.com/raynos/body), [co-body](https://github.com/visionmedia/co-body), 그리고 [raw-body](https://github.com/stream-utils/raw-body)도 참고하세요. | express.bodyParser | -| [compression](/resources/middleware/compression.html) | HTTP 요청들을 압축합니다. | express.compress | -| [connect-rid](/resources/middleware/connect-rid.html) | 고유한 요청 ID를 생성합니다. | 없음 | -| [cookie-parser](/resources/middleware/cookie-parser.html) | 쿠키 헤더를 파싱하고 `req.cookies`에 할당합니다. [cookies](https://github.com/jed/cookies)와 [keygrip](https://github.com/jed/keygrip)도 참고하세요. | express.cookieParser | -| [cookie-session](/resources/middleware/cookie-session.html) | 쿠키 기반의 세션을 만듭니다. | express.cookieSession | -| [cors](/resources/middleware/cors.html) | 다양한 옵션들을 이용하여 Cross-origin resource sharing (CORS)를 활성화합니다. | 없음 | -| [errorhandler](/resources/middleware/errorhandler.html) | 개발 중에 발생하는 에러를 핸들링하고 디버깅합니다. | express.errorHandler | -| [method-override](/resources/middleware/method-override.html) | 헤더를 이용해 HTTP method를 덮어씁니다. | express.methodOverride | -| [morgan](/resources/middleware/morgan.html) | HTTP 요청 로그를 남깁니다. | express.logger | -| [multer](/resources/middleware/multer.html) | multi-part 폼 데이터를 처리합니다. | express.bodyParser | -| [response-time](/resources/middleware/response-time.html) | 응답 시간을 기록합니다. | express.responseTime | -| [serve-favicon](/resources/middleware/serve-favicon.html) | 파비콘을 제공합니다. | express.favicon | -| [serve-index](/resources/middleware/serve-index.html) | 주어진 경로의 디렉토리 리스트를 제공합니다. | express.directory | -| [serve-static](/resources/middleware/serve-static.html) | 정적 파일을 제공합니다. | express.static | -| [session](/resources/middleware/session.html) | 서버 기반의 세션을 만듭니다 (개발 전용). | express.session | -| [timeout](/resources/middleware/timeout.html) | HTTP 요청 처리를 위해 timeout을 만듭니다. | express.timeout | -| [vhost](/resources/middleware/vhost.html) | 가상 도메인을 만듭니다. | express.vhost | +| 미들웨어 모듈 | 설명 | +| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | HTTP 요청 body를 파싱합니다. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | HTTP 요청들을 압축합니다. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | 고유한 요청 ID를 생성합니다. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | 쿠키 헤더를 파싱하고 `req.cookies`에 할당합니다. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | 쿠키 기반의 세션을 만듭니다. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | 다양한 옵션들을 이용하여 Cross-origin resource sharing (CORS)를 활성화합니다. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | 개발 중에 발생하는 에러를 핸들링하고 디버깅합니다. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | 헤더를 이용해 HTTP method를 덮어씁니다. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP 요청 로그를 남깁니다. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | multi-part 폼 데이터를 처리합니다. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | 응답 시간을 기록합니다. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | 주어진 경로의 디렉토리 리스트를 제공합니다. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | 정적 파일을 제공합니다. | +| [session](/{{page.lang}}/resources/middleware/session.html) | 서버 기반의 세션을 만듭니다 (개발 전용). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | 가상 도메인을 만듭니다. | ## 추가 미들웨어 모듈 -몇몇 유명한 외부 미들웨어 모듈들입니다. +These are some additional popular middleware modules. {% include community-caveat.html %} -|미들웨어 모듈 | 설명 | -|---------------------------|---------------------| -| [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus) | 이미지 제공을 최적화힙니다. 할 수 있다면 이미지를 `.webp`나 `.jxr`로 바꿉니다. | -| [express-debug](https://github.com/devoidfury/express-debug) | 템플릿 변수 (지역), 현재 세션, 기타 등등에 대한 정보를 제공하는 개발 도구입니다. | -| [express-partial-response](https://github.com/nemtsov/express-partial-response) | JSON 응답을 URL의 `fields`를 받아서 필터링합니다. Google API의 Partial Response를 활용합니다. | -| [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn) | 정적 요소들을 위해 CDN을 사용하도록 도와줍니다. 다양한 호스트를 지원합니다. | -| [express-slash](https://github.com/ericf/express-slash) | 구현된 루터에 맟춰서 슬래쉬 유무를 맞춰줍니다. | -| [express-stormpath](https://github.com/stormpath/stormpath-express) | 사용자 저장소, 인증 확인, 인증, SSO, 그리고 데이터 보안에 관련된 모듈입니다. (Okta로 합쳐졌습니다) | -| [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize) | 대문자를 포함하는 HTTP 요청들을 표준 소문자 폼으로 리다이렉트시킵니다. containing uppercase to a canonical lowercase form. | -| [helmet](https://github.com/helmetjs/helmet) |다양한 HTTP 헤더를 설정해 앱이 안전하게 도와줍니다. | -| [join-io](https://github.com/coderaiser/join-io) | 요청 횟수를 줄이기 위해 파일들을 묶어줍니다. | -| [passport](https://github.com/jaredhanson/passport) | OAuth, OpenID 같은 방법들을 사용하는 인증 체계입니다. 자세한 정보는 [http://passportjs.org/](http://passportjs.org/)에서 확인하세요. | -| [static-expiry](https://github.com/paulwalker/connect-static-expiry) | 정적 에셋을 위해 헤더를 캐싱하거나 URL을 고유화합니다. | -| [view-helpers](https://github.com/madhums/node-view-helpers) | 뷰 엔진들을 위한 일반적인 도움을 제공합니다. | -| [sriracha-admin](https://github.com/hdngr/siracha) | 동적으로 Mongoose의 관리 사이트를 만듭니다. | - -[http-framework](https://github.com/Raynos/http-framework#modules)에서 더 많은 모듈들을 찾을 수 있습니다. +| 미들웨어 모듈 | 설명 | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet) | 다양한 HTTP 헤더를 설정해 앱이 안전하게 도와줍니다. | +| [passport](https://github.com/jaredhanson/passport) | OAuth, OpenID 같은 방법들을 사용하는 인증 체계입니다. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/ko/resources/middleware/body-parser.md b/ko/resources/middleware/body-parser.md new file mode 100644 index 0000000000..ff9922eb8f --- /dev/null +++ b/ko/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: ko +redirect_from: " " +module: body-parser +--- diff --git a/ko/resources/middleware/compression.md b/ko/resources/middleware/compression.md new file mode 100644 index 0000000000..fae4dff678 --- /dev/null +++ b/ko/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: ko +redirect_from: " " +module: compression +--- diff --git a/ko/resources/middleware/connect-rid.md b/ko/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..7baa9fa6c5 --- /dev/null +++ b/ko/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: ko +redirect_from: " " +module: connect-rid +--- diff --git a/ko/resources/middleware/cookie-parser.md b/ko/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..9634eb45ac --- /dev/null +++ b/ko/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: ko +redirect_from: " " +module: cookie-parser +--- diff --git a/ko/resources/middleware/cookie-session.md b/ko/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..bf5ba8db00 --- /dev/null +++ b/ko/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: ko +redirect_from: " " +module: cookie-session +--- diff --git a/ko/resources/middleware/cors.md b/ko/resources/middleware/cors.md new file mode 100644 index 0000000000..dcf88e6dc3 --- /dev/null +++ b/ko/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: ko +redirect_from: " " +module: cors +--- diff --git a/ko/resources/middleware/errorhandler.md b/ko/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..a88dea193c --- /dev/null +++ b/ko/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: ko +redirect_from: " " +module: errorhandler +--- diff --git a/ko/resources/middleware/method-override.md b/ko/resources/middleware/method-override.md new file mode 100644 index 0000000000..4fce968de5 --- /dev/null +++ b/ko/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: ko +redirect_from: " " +module: method-override +--- diff --git a/ko/resources/middleware/morgan.md b/ko/resources/middleware/morgan.md new file mode 100644 index 0000000000..90bfb66082 --- /dev/null +++ b/ko/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: ko +redirect_from: " " +module: morgan +--- diff --git a/ko/resources/middleware/multer.md b/ko/resources/middleware/multer.md new file mode 100644 index 0000000000..2d75724e88 --- /dev/null +++ b/ko/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: ko +redirect_from: " " +module: multer +--- diff --git a/ko/resources/middleware/response-time.md b/ko/resources/middleware/response-time.md new file mode 100644 index 0000000000..fb0d5bc396 --- /dev/null +++ b/ko/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: ko +redirect_from: " " +module: response-time +--- diff --git a/ko/resources/middleware/serve-favicon.md b/ko/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..4daa4e8ac0 --- /dev/null +++ b/ko/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: ko +redirect_from: " " +module: serve-favicon +--- diff --git a/ko/resources/middleware/serve-index.md b/ko/resources/middleware/serve-index.md new file mode 100644 index 0000000000..53ae655558 --- /dev/null +++ b/ko/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: ko +redirect_from: " " +module: serve-index +--- diff --git a/ko/resources/middleware/serve-static.md b/ko/resources/middleware/serve-static.md new file mode 100644 index 0000000000..c12f9c484c --- /dev/null +++ b/ko/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: ko +redirect_from: " " +module: serve-static +--- diff --git a/ko/resources/middleware/session.md b/ko/resources/middleware/session.md new file mode 100644 index 0000000000..8d590cdd8b --- /dev/null +++ b/ko/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: ko +redirect_from: " " +module: session +--- diff --git a/ko/resources/middleware/timeout.md b/ko/resources/middleware/timeout.md new file mode 100644 index 0000000000..29e0b17c6f --- /dev/null +++ b/ko/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: ko +redirect_from: " " +module: timeout +--- diff --git a/ko/resources/middleware/vhost.md b/ko/resources/middleware/vhost.md new file mode 100644 index 0000000000..54eb9e8442 --- /dev/null +++ b/ko/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: ko +redirect_from: " " +module: vhost +--- diff --git a/ko/resources/utils.md b/ko/resources/utils.md new file mode 100644 index 0000000000..82a15b8067 --- /dev/null +++ b/ko/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: ko +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | 설명 | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/ko/starter/basic-routing.md b/ko/starter/basic-routing.md old mode 100755 new mode 100644 index 3cced3129d..2f3597d272 --- a/ko/starter/basic-routing.md +++ b/ko/starter/basic-routing.md @@ -1,20 +1,20 @@ --- layout: page title: Express 기본 라우팅 +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. menu: starter lang: ko -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. +redirect_from: " " --- # 기본 라우팅 -*라우팅*은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것을 말합니다. +_라우팅_은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것을 말합니다. 각 라우트는 하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때 실행됩니다. 라우트 정의에는 다음과 같은 구조가 필요합니다. + ```js app.METHOD(PATH, HANDLER) ``` @@ -65,3 +65,5 @@ app.delete('/user', (req, res) => { ``` 라우팅에 대한 자세한 내용을 확인하려면 [라우팅 안내서](/{{ page.lang }}/guide/routing.html)를 참조하십시오. + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/ko/starter/examples.md b/ko/starter/examples.md new file mode 100644 index 0000000000..3db463c9e7 --- /dev/null +++ b/ko/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: ko +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/ko/starter/faq.md b/ko/starter/faq.md old mode 100755 new mode 100644 index 5e93c5a4fd..175daac6f3 --- a/ko/starter/faq.md +++ b/ko/starter/faq.md @@ -1,11 +1,10 @@ --- layout: page title: Express 자주 묻는 질문(FAQ) +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: ko -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # 자주 묻는 질문(FAQ) @@ -20,13 +19,13 @@ description: Find answers to frequently asked questions about Express.js, includ 선호하는 모든 디렉토리 구조에 존재할 수 있습니다. 도움을 받으려면 다음의 예를 확인하십시오. -* [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [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) +- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [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) 또한, 이러한 패턴을 간략화할 수 있는 다음과 같은 Express용 써드파티 확장기능이 존재합니다. -* [Resourceful routing](https://github.com/expressjs/express-resource) +- [Resourceful routing](https://github.com/expressjs/express-resource) ## 모델을 어떻게 정의해야 합니까? @@ -39,10 +38,9 @@ Express에는 데이터베이스의 개념이 없습니다. 이러한 개념은 ## 어떻게 사용자를 인증할 수 있습니까? 인증은 또 다른 주관적인 영역이며, Express는 -이에 관여하지 않습니다. 개발자는 자신이 원하는 어떠한 인증 체계라도 사용할 수 있습니다. +이에 관여하지 않습니다. 개발자는 자신이 원하는 어떠한 인증 체계라도 사용할 수 있습니다. 사용자 이름 / 비밀번호 체계에 대해서는 [이 예제](https://github.com/expressjs/express/tree/master/examples/auth)를 참조하십시오. - ## Express는 어느 템플리트 엔진을 지원합니까? Express는 `(path, locals, callback)` 시그니처를 준수하는 모든 템플리트 엔진을 지원합니다. @@ -50,6 +48,8 @@ Express는 `(path, locals, callback)` 시그니처를 준수하는 모든 템플 [consolidate.js](https://github.com/visionmedia/consolidate.js) 프로젝트를 참조하여 지원을 받으십시오. 목록에 포함되지 않은 템플리트 엔진이 Express 시그니처를 지원할 수도 있습니다. +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). + ## 404 응답을 어떻게 처리해야 합니까? Express에서 404 응답은 오류로 인해 발생하는 결과가 아니며, 따라서 @@ -62,10 +62,13 @@ Express에서 404 응답은 오류로 인해 발생하는 결과가 아니며, ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## 오류 핸들러를 어떻게 설정해야 합니까? 오류 처리 미들웨어는 다른 미들웨어와 동일한 방식으로 정의할 수 있지만, @@ -86,3 +89,10 @@ app.use((err, req, res, next) => { 특정한 파일을 렌더링해야 하는 경우에는 `res.sendFile()` 함수를 사용하십시오. 하나의 디렉토리에서 여러 자산을 제공하는 경우에는 `express.static()` 미들웨어 함수를 사용하십시오. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/ko/starter/generator.md b/ko/starter/generator.md old mode 100755 new mode 100644 index 8c6ffb5efb..d634ce16d7 --- a/ko/starter/generator.md +++ b/ko/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Express 애플리케이션 생성기 +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: ko -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Express 애플리케이션 생성기 애플리케이션의 골격을 신속하게 작성하려면 애플리케이션 생성기 도구인 `express`를 사용하십시오. -다음의 명령을 이용해 `express`를 설치하십시오. +You can run the application generator with the `npx` command (available in 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: ```bash -$ npm install express-generator -g +$ npm install -g express-generator +$ express ``` 다음과 같이 `-h` 옵션을 이용해 명령의 옵션을 표시하십시오. @@ -22,7 +29,7 @@ $ npm install express-generator -g ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -예를 들면, 다음의 예에서는 _myapp_라는 이름의 Express 앱을 현재 작업 디렉토리에 작성합니다. +예를 들면, 다음의 예에서는 _myapp_라는 이름의 Express 앱을 현재 작업 디렉토리에 작성합니다. The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -82,6 +89,12 @@ Windows에서는 다음 명령을 사용하십시오. > set DEBUG=myapp:* & npm start ``` +다음의 명령을 이용해 `express`를 설치하십시오. + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + 이후 브라우저에서 `http://localhost:3000/`을 로드하여 앱에 액세스하십시오. 생성된 앱은 다음과 같은 디렉토리 구조를 갖습니다. @@ -111,3 +124,5 @@ Windows에서는 다음 명령을 사용하십시오.
    생성기에 의해 작성된 앱 구조는 Express 앱을 구조화하는 여러 방법 중 하나에 불과합니다. 이러한 구조를 사용하거나 사용자의 요구사항에 가장 적합하도록 구조를 수정하십시오.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/ko/starter/hello-world.md b/ko/starter/hello-world.md old mode 100755 new mode 100644 index ad4b7fa2e7..c013a1948c --- a/ko/starter/hello-world.md +++ b/ko/starter/hello-world.md @@ -1,10 +1,10 @@ --- layout: page title: Express "Hello World" 예제 +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: ko -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Hello world 예제 @@ -13,10 +13,6 @@ description: Get started with Express.js by building a simple 'Hello World' appl 기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 [Express 생성기](/{{ page.lang }}/starter/generator.html)를 통해 얻게 되는 앱과는 같지 *않습니다*. (이 예제와 달리 Express 생성기를 통해 얻게 되는 앱은 다양한 목적을 위한 여러 JavaScript 파일, Jade 템플리트 및 하위 디렉토리를 포함하는 전체 앱에 대한 스캐폴딩을 작성합니다.)
    -먼저, `myapp`이라는 이름의 디렉토리를 작성한 후 이 디렉토리로 이동하여 `npm init`를 실행하십시오. 이후 [설치 안내서](/{{ page.lang }}/starter/installing.html)에 따라 `express`를 종속 항목으로서 설치하십시오. - -`myapp` 디렉토리에 `app.js`라는 이름의 파일을 작성한 후 다음과 같은 코드를 추가하십시오. - ```js const express = require('express') const app = express() @@ -31,9 +27,15 @@ app.listen(port, () => { }) ``` -앱은 서버를 시작하며 3000번 포트에서 연결을 청취합니다. 앱은 루트 URL(`/`) 또는 *라우트*에 +앱은 서버를 시작하며 3000번 포트에서 연결을 청취합니다. 앱은 루트 URL(`/`) 또는 _라우트_에 대한 요청에 "Hello World!"로 응답합니다. 다른 모든 경로에 대해서는 **404 Not Found**로 응답합니다. +### Running Locally + +먼저, `myapp`이라는 이름의 디렉토리를 작성한 후 이 디렉토리로 이동하여 `npm init`를 실행하십시오. 이후 [설치 안내서](/{{ page.lang }}/starter/installing.html)에 따라 `express`를 종속 항목으로서 설치하십시오. + +`myapp` 디렉토리에 `app.js`라는 이름의 파일을 작성한 후 다음과 같은 코드를 추가하십시오. +
    `req`(요청) 및 `res`(응답)는 Node가 제공하는 동일한 오브젝트이며, 따라서 `req.pipe()`, `req.on('data', callback)` 그리고 Express의 관여가 필요 없는 다른 모든 항목을 호출할 수 있습니다. @@ -47,3 +49,4 @@ $ node app.js 이후 브라우저에서 [http://localhost:3000/](http://localhost:3000/)을 로드하여 결과물을 확인하십시오. +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/ko/starter/installing.md b/ko/starter/installing.md old mode 100755 new mode 100644 index 3198f78dc6..06a903c0e7 --- a/ko/starter/installing.md +++ b/ko/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: Express 설치 +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: ko -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # 설치 [Node.js](https://nodejs.org/)가 이미 설치되었다고 가정한 상태에서, 애플리케이션을 보관할 디렉토리를 작성하고 그 디렉토리를 작업 디렉토리로 설정하십시오. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -26,7 +29,7 @@ $ npm init 이 명령을 실행하면 애플리케이션의 이름 및 버전과 같은 몇 가지 정보에 대해 프롬프트합니다. 지금은 다음의 항목을 제외한 대부분의 항목에서 ENTER 키를 눌러 기본값을 수락할 수 있습니다. -```bash +``` entry point: (index.js) ``` @@ -35,16 +38,17 @@ entry point: (index.js) 이제 `myapp` 디렉토리에 Express를 설치한 후 종속 항목 목록에 저장하십시오. 예를 들면 다음과 같습니다. ```bash -$ npm install express --save +$ npm install express ``` Express를 임시로 설치하고 종속 항목 목록에 추가하지 않으려면, 다음과 같이 `--save` 옵션을 생략하십시오. ```bash -$ npm install express +$ npm install express --no-save ```
    -`--save` 옵션을 통해 설치된 Node 모듈은 `package.json` 파일 내의 `dependencies` 목록에 추가됩니다. -이후 `app` 디렉토리에서 `npm install`을 실행하면 종속 항목 목록 내의 모듈이 자동으로 설치됩니다. +`--save` 옵션을 통해 설치된 Node 모듈은 `package.json` 파일 내의 `dependencies` 목록에 추가됩니다. 이후 `app` 디렉토리에서 `npm install`을 실행하면 종속 항목 목록 내의 모듈이 자동으로 설치됩니다.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/ko/starter/static-files.md b/ko/starter/static-files.md old mode 100755 new mode 100644 index f966f94a49..09e1b5244e --- a/ko/starter/static-files.md +++ b/ko/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: Express에서 정적 파일 제공 +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: ko -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # Express에서 정적 파일 제공 이미지, CSS 파일 및 JavaScript 파일과 같은 정적 파일을 제공하려면 Express의 기본 제공 미들웨어 함수인 `express.static`을 사용하십시오. -정적 자산이 포함된 디렉토리의 이름을 `express.static` 미들웨어 함수에 전달하면 파일의 직접적인 제공을 시작할 수 있습니다. 예를 들면, 다음과 같은 코드를 이용하여 `public`이라는 이름의 디렉토리에 포함된 이미지, CSS 파일 및 JavaScript 파일을 제공하십시오. +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](/{{page.lang}}/4x/api.html#express.static). + +예를 들면, 다음과 같은 코드를 이용하여 `public`이라는 이름의 디렉토리에 포함된 이미지, CSS 파일 및 JavaScript 파일을 제공하십시오. ```js app.use(express.static('public')) @@ -40,6 +49,11 @@ app.use(express.static('files')) Express는 `express.static` 미들웨어 함수를 이용해 정적 디렉토리를 설정한 순서대로 파일을 검색합니다. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + `express.static` 함수를 통해 제공되는 파일에 대한 가상 경로 접두부(파일 시스템 내에 해당 경로가 실제로 존재하지 않는 경우)를 작성하려면, 아래에 표시된 것과 같이 정적 디렉토리에 대한 [마운트 경로를 지정](/{{ page.lang }}/4x/api.html#app.use)하십시오. ```js @@ -62,3 +76,7 @@ http://localhost:3000/static/hello.html const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/ko/support/index.md b/ko/support/index.md index f724d1f0ff..23248a3f52 100644 --- a/ko/support/index.md +++ b/ko/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: ko --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/pt-br/3x/api.md b/pt-br/3x/api.md index a237985782..aa73a54499 100644 --- a/pt-br/3x/api.md +++ b/pt-br/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - API Reference +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: pt-br -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x support is ending soon** - This series will continue to receive only security updates and bug fixes until July 2015. It is highly recommended to upgrade to Express 4.x. -
    - -

    3.x API

    +This series will continue to receive only security updates and bug fixes until July 2015. It is highly recommended to upgrade to Express 4.x. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
    - - {% include api/en/3x/res.md %} +

    3.x API

    - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
    diff --git a/pt-br/4x/api.md b/pt-br/4x/api.md index a7d6b18884..df1c51e454 100644 --- a/pt-br/4x/api.md +++ b/pt-br/4x/api.md @@ -1,28 +1,27 @@ --- layout: api version: 4x -title: Express 4.x - Referência da API +title: Express 4.x - Referência de API +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: pt-br -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +
    -

    4.x API

    +

    API 4.x

    - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
    diff --git a/pt-br/5x/api.md b/pt-br/5x/api.md index 5cc4a36e47..f32c6d7b0e 100644 --- a/pt-br/5x/api.md +++ b/pt-br/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - Referência da API +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: pt-br -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/pt-br/advanced/best-practice-performance.md b/pt-br/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 61a4c86483..e969561a7d --- a/pt-br/advanced/best-practice-performance.md +++ b/pt-br/advanced/best-practice-performance.md @@ -1,36 +1,43 @@ --- layout: page title: Melhores Práticas de Desempenho Usando o Express em Produção +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: pt-br -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # Melhores Práticas de Produção: desempenho e confiabilidade -## Visão Geral - Este artigo discute as melhores práticas de desempenho e de confiabilidade para aplicativos Express implementados para produção. Este tópico se enquadra claramente no mundo de "devops", abordando o desenvolvimento tradicional e as operações. Assim, as informações são divididas em duas partes: -* [Itens a fazer no seu código](#code) (a parte do dev). -* [Itens a fazer no seu ambiente / configuração](#env) (a parte de ops). - - +- [Itens a fazer no seu código](#code) (a parte do dev). + - Use a compactação gzip + - Não use funções síncronas + - Faça o registro de logs corretamente + - [Handle exceptions properly](#handle-exceptions-properly) +- [Itens a fazer no seu ambiente / configuração](#env) (a parte de ops). + - Configure o NODE_ENV para "produção" + - Executar o seu aplicativo (e Node) diretamente com o sistema + de inicialização. Isto é de certa forma mais simples, mas você não + obtém as vantagens adicionais do uso de um gerenciador de processos. + - Execute seu aplicativo em um cluster + - + - Use um balanceador de carga + - Use um proxy reverso ## Itens a fazer no seu código A seguir serão apresentados alguns itens que podem ser feitos no seu código para melhorar o desempenho dos aplicativos: -* Use a compactação gzip -* Não use funções síncronas -* Use o middleware para entregar arquivos estáticos -* Faça o registro de logs corretamente -* Lide com exceções adequadamente +- Use a compactação gzip +- Não use funções síncronas +- Faça o registro de logs corretamente +- [Handle exceptions properly](#handle-exceptions-properly) ### Use a compactação gzip @@ -40,12 +47,13 @@ A compactação Gzip pode diminuir bastante o tamanho do corpo de resposta e ass const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` Para um website com tráfego intenso na produção, a melhor maneira de colocar a compactação em prática, é implementá-la em um -nível de proxy reverso (consulte [Use um proxy reverso](#proxy)). Neste caso, não é necessário usar o middleware de compactação. Para obter detalhes sobre a ativação da compactação gzip no Nginx, consulte o [Módulo -ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) na documentação do Nginx. +nível de proxy reverso (consulte [Use um proxy reverso](#proxy)). Neste caso, não é necessário usar o middleware de compactação. Para obter detalhes sobre a ativação da compactação gzip no Nginx, consulte o Módulo +ngx_http_gzip_module na documentação do Nginx. ### Não use funções síncronas @@ -56,32 +64,16 @@ aplicativo. Evite o uso delas na produção. Apesar de o Node e muitos módulos fornecerem versões síncronas e assíncronas de suas funções, sempre use as versões assíncronas na produção. O único momento em que o uso de uma função síncrona pode ser justificado é na primeira inicialização. -Se estiver usando o Node.js 4.0+ ou o io.js 2.1.0+, é possível usar a sinalização `--trace-sync-io` da linha de comandos para imprimir um aviso e um rastreio de pilha sempre que o seu aplicativo usar uma API síncrona. Obviamente, não seria desejado usar isto na produção, mas sim antes, para garantir que seu código está pronto para produção. Consulte a [Atualização -semanal para o io.js 2.1.0](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0) para obter mais informações. - -### Use o middleware para entregar arquivos estáticos - -No desenvolvimento, é possível usar a [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) para entregar arquivos estáticos. Mas -não use isto na produção, pois esta função precisa ser lida a partir -do sistema de arquivos para cada solicitação de arquivo, e portanto -encontraria latência e afetaria o desempenho geral do aplicativo. Observe que a `res.sendFile()` *não* é implementada com a chamada de sistema [sendfile](http://linux.die.net/man/2/sendfile) o que a tornaria muito mais eficiente. - -Ao invés disso, use o middleware [serve-static](https://www.npmjs.com/package/serve-static) -(ou algo equivalente), que é otimizado para a entrega de arquivos para os aplicativos do Express. - -Uma opção ainda melhor é usar um proxy reverso para entregar -arquivos estáticos; consulte [Use um proxy -reverso](#proxy) para obter 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. Obviamente, não seria desejado usar isto na produção, mas sim antes, para garantir que seu código está pronto para produção. Consulte a Atualização +semanal para o io.js 2.1.0 para obter mais informações. -### Faça o registro de logs corretamente +### Lide com exceções adequadamente Em geral, existem duas razões para registrar logs em seu aplicativo: Para depuração e para registro de logs de atividade do aplicativo (essencialmente, todo o resto). Usar o `console.log()` ou o `console.err()` para imprimir mensagens de log no -terminal é uma prática comum em desenvolvimento. Mas [essas -funções são síncronas](https://nodejs.org/api/console.html#console_console_1) quando o destino é um terminal ou um arquivo, portanto elas não são adequadas para produção, a não ser que -a saída seja canalizada para outro programa. +terminal é uma prática comum em desenvolvimento. 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 estiver registrando logs com o propósito de depuração, então ao invés de usar o `console.log()`, use um módulo especial para depuração como o [debug](https://www.npmjs.com/package/debug). Este @@ -91,14 +83,7 @@ módulo permite que seja usada a variável de ambiente DEBUG para controlar quai #### Para atividade do aplicativo -Se estiver registrando logs de atividade do aplicativo (por -exemplo, rastreamento de tráfico ou chamadas de API), ao invés de -usar o `console.log()`, use uma biblioteca de -registro de logs como [Winston](https://www.npmjs.com/package/winston) ou [Bunyan](https://www.npmjs.com/package/bunyan). Para -obter uma comparação detalhada dessas duas bibliotecas, consulte a postagem do blog do StrongLoop -[Comparando o registro de logs no Node.js usando Winston e Bunyan](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/). - - +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. ### Lide com exceções adequadamente @@ -112,8 +97,8 @@ necessário tratar exceções adequadamente. Para garantir que está tratando todas as exceções, use as seguintes técnicas: -* [Use try-catch](#try-catch) -* [Use promessas](#promises) +- [Use try-catch](#try-catch) +- [Use promessas](#promises) Antes de se aprofundar nestes tópicos, você deveria ter um entendimento básico de manipulação de erros do Node/Express: usando @@ -124,37 +109,12 @@ convenção de retorno de chamada erros-first para tratar o erro de forma signif Para obter mais informações sobre os fundamentos de manipulação de erros, consulte: -* [Manipulação de Erros no Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Construindo Aplicativos Node Robustos: Manipulação de Erros](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (blog do StrongLoop) - -#### O que não fazer - -Uma coisa que *não* deveria fazer é escutar a eventos `uncaughtException`, emitidos quando uma exceção -emerge regressando ao loop de eventos. Incluir um listener de eventos para `uncaughtException` irá mudar o comportamento -padrão do processo que está encontrando uma exceção; o processo irá continuar a execução apesar da exceção. Essa pode parecer como uma boa maneira de prevenir que o seu -aplicativo caia, mas continuar a execução do aplicativo após uma -exceção não capturada é uma prática perigosa e não é recomendada, porque o estado do processo se torna não confiável e imprevisível. - -Adicionalmente, usar o `uncaughtException` é oficialmente reconhecido como [grosseiro](https://nodejs.org/api/process.html#process_event_uncaughtexception) -e existe uma [proposta](https://github.com/nodejs/node-v0.x-archive/issues/2582) -de removê-lo do núcleo. Portando escutar por um `uncaughtException` é simplesmente uma má ideia. É -por isso que recomendamos coisas como múltiplos processos e -supervisores: o processo de queda e reinicialização é frequentemente a -forma mais confiável de se recuperar de um erro. - -Também não recomendamos o uso de [domínios](https://nodejs.org/api/domain.html). Ele -geralmente não resolve o problema e é um módulo descontinuado. - - +- [Manipulação de Erros no Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### Use try-catch Try-catch é uma construção da linguagem JavaScript que pode ser usada para capturar exceções em um código síncrono. Use try-catch, por exemplo, para tratar erros de análise sintática de JSON como mostrado abaixo. -Use uma ferramenta como o [JSHint](http://jshint.com/) ou o -[JSLint](http://www.jslint.com/) para ajudá-lo a localizar exceções implícitas como -[erros de referência em variáveis indefinidas](http://www.jshint.com/docs/options/#undef). - Aqui está um exemplo de uso de try-catch para tratar uma potencial exceção causadora de queda de processo. Esta função middleware aceita um parâmetro de campo de consulta chamado "params" que é um objeto JSON. @@ -178,103 +138,87 @@ Entretanto, o try-catch funciona apenas para códigos síncronos. Como a plataforma Node é a princípio assíncrona (particularmente em um ambiente de produção), o try-catch deixará de capturar muitas exceções. - - #### Use promessas -Promessas irão tratar quaisquer exceções (ambas explícitas e implícitas) em blocos de códigos assíncronos que usem -`then()`. Apenas inclua `.catch(next)` no final da cadeia de promessas. Por exemplo: +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -Agora todos os erros assíncronos e síncronos são propagados para o middleware de erros. - -Entretanto, existem dois alertas: - -1. Todo seu código assíncrono deve retornar promessas (exceto -emissores). Se uma biblioteca em particular não retornar promessas, -converta o objeto base através do uso de uma função auxiliar como -[Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html). -2. Emissores de eventos (como fluxos) podem ainda causar -exceções não capturadas. Portanto certifique-se de que está tratando -o evento de erro apropriadamente; por exemplo: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -Para obter mais informações sobre o manipulação de erros usando -promessas, consulte: +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 + +Uma coisa que _não_ deveria fazer é escutar a eventos `uncaughtException`, emitidos quando uma exceção +emerge regressando ao loop de eventos. Incluir um listener de eventos para `uncaughtException` irá mudar o comportamento +padrão do processo que está encontrando uma exceção; o processo irá continuar a execução apesar da exceção. Essa pode parecer como uma boa maneira de prevenir que o seu +aplicativo caia, mas continuar a execução do aplicativo após uma +exceção não capturada é uma prática perigosa e não é recomendada, porque o estado do processo se torna não confiável e imprevisível. + +Adicionalmente, usar o `uncaughtException` é oficialmente reconhecido como [grosseiro](https://nodejs.org/api/process.html#process_event_uncaughtexception) +e existe uma [proposta](https://github.com/nodejs/node-v0.x-archive/issues/2582) +de removê-lo do núcleo. Portando escutar por um `uncaughtException` é simplesmente uma má ideia. É +por isso que recomendamos coisas como múltiplos processos e +supervisores: o processo de queda e reinicialização é frequentemente a +forma mais confiável de se recuperar de um erro. -* [Manipulando Erros -Assíncronos no Express com Promessas, Geradores e ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promessas no Node.js com o Q – Uma Alternativa a Retornos de Chamada](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +Também não recomendamos o uso de [domínios](https://nodejs.org/api/domain.html). Ele +geralmente não resolve o problema e é um módulo descontinuado. - +## Things to do in your environment / setup -## Coisa a se fazer no seu ambiente / configuração +{#in-environment} A seguir serão apresentados alguns itens que podem ser feitos no seu ambiente de sistema para melhorar o desempenho dos seus aplicativos: -* Configure o NODE_ENV para "produção" -* Assegure que o seu aplicativo reinicie automaticamente -* Execute seu aplicativo em um cluster -* Armazene em cache os resultados das solicitações -* Use um balanceador de carga -* Use um proxy reverso +- Configure o NODE_ENV para "produção" +- Executar o seu aplicativo (e Node) diretamente com o sistema + de inicialização. Isto é de certa forma mais simples, mas você não + obtém as vantagens adicionais do uso de um gerenciador de processos. +- Execute seu aplicativo em um cluster +- +- Use um balanceador de carga +- Use um proxy reverso ### Configure o NODE_ENV para "produção" A variável de ambiente NODE_ENV especifica o ambiente no qual um aplicativo está executando (geralmente, desenvolvimento ou -produção). Uma das coisas mais simples que podem ser feitas para -melhorar o desempenho é configurar NODE_ENV para "produção". +produção). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. Configurando NODE_ENV para "produção" faz com que o Express: -* Armazene em Cache os modelos de visualização. -* Armazene em Cache arquivos CSS gerados a partir de extensões CSS. -* Gere menos mensagens de erro detalhadas +- Armazene em Cache os modelos de visualização. +- Armazene em Cache arquivos CSS gerados a partir de extensões CSS. +- Gere menos mensagens de erro detalhadas -[Testes -indicam](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) que apenas fazendo isso pode melhorar o desempenho por um fator de três! +[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! Se precisar escrever código específico por ambiente, é possível verificar o valor de NODE_ENV com `process.env.NODE_ENV`. Esteja ciente de que verificar o valor de qualquer variável de ambiente incorre em perda de desempenho, e por isso deve ser feito raramente. Em desenvolvimento, você tipicamente configura variáveis de ambiente no seu shell interativo, por exemplo, usando o -`export` ou o seu arquivo `.bash_profile`. Mas -em geral você não deveria fazer isto em um servidor de produção; ao invés disso, use o sistema de inicialização do seu sistema -operacional (systemd ou Upstart). A próxima seção fornece mais detalhes sobre a utilização do seu sistema de inicialização em geral, +`export` ou o seu arquivo `.bash_profile`. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). A próxima seção fornece mais detalhes sobre a utilização do seu sistema de inicialização em geral, mas configurando NODE_ENV é tão importante para o desempenho (e fácil de fazer), que está destacado aqui. -Com o Upstart, use a palavra-chave `env` no -seu arquivo de tarefa. Por exemplo: - -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` - -Para obter mais informações, consulte o [Introdução, Cookbook e Melhores Práticas para o Upstart](http://upstart.ubuntu.com/cookbook/#environment-variables). - Com o systemd, use a diretiva `Environment` no seu arquivo de unidade. Por exemplo: ```sh @@ -282,12 +226,7 @@ Com o systemd, use a diretiva `Environment` no seu arquivo de unidade. Por exemp Environment=NODE_ENV=production ``` -Para obter mais informações, consulte [Usando -Variáveis de Ambiente em Unidades systemd](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html). - -Se estiver usando o StrongLoop Process Manager, é possível também -[configurar -a variável de ambiente ao instalar o StrongLoop PM como um serviço](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables). +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Assegure que o seu aplicativo reinicie automaticamente @@ -297,9 +236,9 @@ reinicie tanto se o aplicativo cair quanto se o próprio servidor cair. Apesar de se esperar que nenhum desses eventos ocorram, realisticamente você deve considerar ambas as eventualidades: -* Usando um gerenciador de processos para reiniciar o aplicativo (e o Node) quando ele cair. -* Usando o sistema de inicialização fornecido pelo seu sistema operacional para reiniciar o gerenciador de processos quando o -sistema operacional cair. Também é possível usar o sistema de inicialização sem um gerenciador de processos. +- Usando um gerenciador de processos para reiniciar o aplicativo (e o Node) quando ele cair. +- Usando o sistema de inicialização fornecido pelo seu sistema operacional para reiniciar o gerenciador de processos quando o + sistema operacional cair. Também é possível usar o sistema de inicialização sem um gerenciador de processos. Aplicativos do Node caem se encontrarem uma exceção não capturada. A principal coisa que precisa ser feita é assegurar que o @@ -320,37 +259,11 @@ gerenciamento do aplicativo em tempo real. Em adição à reinicialização do seu aplicativo quando cai, um gerenciador de processos pode permitir que você: -* Ganhe insights sobre o desempenho em tempo de execução e o consumo de recursos. -* Modifique configurações dinamicamente para melhorar o desempenho. -* Controle a clusterização (StrongLoop PM e pm2). - -Os gerenciador de processos mais populares para o Node são os -seguintes: +- Ganhe insights sobre o desempenho em tempo de execução e o consumo de recursos. +- Modifique configurações dinamicamente para melhorar o desempenho. +- Control clustering (pm2). -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -Para uma comparação recurso por recurso dos três gerenciadores -de processos, consulte [http://strong-pm.io/compare/](http://strong-pm.io/compare/). - -Usando qualquer um desses gerenciadores de processos será o -suficiente para manter seu aplicativo funcionando, mesmo se ele cair -de tempos em tempos. - -Entretanto, o StrongLoop PM possui vários recursos que são especificamente destinados para a implementação na produção. É possível usá-lo e as ferramentas relacionadas do StrongLoop para: - -* Construir e empacotar seu aplicativo localmente, em seguida -implemente-o seguramente para o seu sistema de produção. -* Automaticamente reiniciar seu aplicativo se ele cair por qualquer razão. -* Gerenciar seus clusters remotamente. -* Visualizar perfis de CPU e captura instantânea de heap para -otimizar o desempenho e diagnosticar fugas de memória. -* Visualizar métricas de desempenho para o seu aplicativo. -* Facilmente escalar para múltiplos hosts com controle integrado para o balanceador de carga Nginx. - -Como explicado abaixo, ao instalar o StrongLoop PM como um serviço do sistema operacional usando o seu sistema de -inicialização, ele irá automaticamente reiniciar quando o sistema reiniciar. Assim, ele irá manter seus processos do aplicativo e clusters ativos para sempre. +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. #### Use um sistema de inicialização @@ -358,18 +271,14 @@ A próxima camada de confiabilidade é para assegurar que o seu aplicativo reinicie quando o servidor reiniciar. Os sistemas podem ainda assim cair por uma variedade de razões. Para assegurar que o seu aplicativo reinicie se o servidor cair, use o sistema de -inicialização integrado no seu sistema operacional. Os dois -principais sistemas de inicialização usados atualmente são o -[systemd](https://wiki.debian.org/systemd) e o [Upstart](http://upstart.ubuntu.com/). +inicialização integrado no seu sistema operacional. The main init system in use today is [systemd](https://wiki.debian.org/systemd). Existem duas formas de usar sistemas de inicialização com o seu aplicativo Express: -* Executar o seu aplicativo em um gerenciador de processos, e instalar o gerenciador de processos com o sistema de inicialização. O gerenciador de processos irá reiniciar seu aplicativo quando o -aplicativo cair, e o sistema de inicialização irá reiniciar o -gerenciador de processos quando o sistema operacional reiniciar. Esta é a abordagem recomendada. -* Executar o seu aplicativo (e Node) diretamente com o sistema -de inicialização. Isto é de certa forma mais simples, mas você não -obtém as vantagens adicionais do uso de um gerenciador de processos. +- Executar o seu aplicativo em um gerenciador de processos, e instalar o gerenciador de processos com o sistema de inicialização. O gerenciador de processos irá reiniciar seu aplicativo quando o + aplicativo cair, e o sistema de inicialização irá reiniciar o + gerenciador de processos quando o sistema operacional reiniciar. Esta é a abordagem recomendada. +- 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 @@ -378,19 +287,19 @@ maioria das distribuições principais do Linux adotaram o systemd como sistema de inicialização padrão. Um arquivo de configuração de serviço do systemd é chamado -de *arquivo de unidade*, com um nome de arquivo +de _arquivo de unidade_, com um nome de arquivo terminando em .service. Aqui está um exemplo de arquivo de unidade para gerenciar um aplicativo Node diretamente (substitua o texto em -negrito com valores para o seu sistema e aplicativo): +negrito com valores para o seu sistema e aplicativo): Replace the values enclosed in `` for your system and app: ```sh [Unit] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -412,121 +321,10 @@ Restart=always [Install] WantedBy=multi-user.target ``` -Para obter mais informações sobre o systemd, consulte a -[referência -do systemd (página do manual)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html). - -##### StrongLoop PM como um serviço do systemd - -É possível facilmente instalar o StrongLoop Process Manager -como um serviço do systemd. Após fazer isso, quando o servidor -reiniciar, ele irá automaticamente reiniciar o StrongLoop PM, que irá -então reiniciar todos os aplicativos que está gerenciando. - -Para instalar o StrongLoop PM como um serviço do systemd: - -```bash -$ sudo sl-pm-install --systemd -``` - -Em seguida inicie o serviço com: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -Para obter mais informações, consulte -[Configurando -um host de produção (documentação do StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10). - -##### Upstart - -O Upstart é uma ferramenta de sistema disponível em muitas distribuições Linux para inicialização de tarefas e serviços durante -a inicialização do sistema, parando-os durante o encerramento, e -supervisionando-os. É possível configurar seu aplicativo Express ou -gerenciador de processos como um serviço e em seguida o Upstart irá -automaticamente reiniciá-lo quando ele cair. - -Um serviço do Upstart é definido em um arquivo de configuração de tarefa -(também chamado de uma "tarefa") com o nome do arquivo terminando com -`.conf`. O seguinte exemplo mostra como criar uma -tarefa chamada "myapp" para um aplicativo chamado "myapp" com o -arquivo principal localizado em `/projects/myapp/index.js`. - -Crie um arquivo chamado `myapp.conf` em -`/etc/init/` com o seguinte conteúdo (substitua o -texto em negrito com os valores para o seu sistema e aplicativo): - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn - -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` - -NOTA: Este script requer o Upstart 1.4 ou mais novo, suportado no Ubuntu 12.04-14.10. - -Como a tarefa está configurada para executar quando o sistema -inicia, seu aplicativo será iniciado juntamente com o sistema -operacional, e automaticamente reiniciado se o aplicativo ou o -sistema cair. - -À parte da reinicialização automática do aplicativo, o Upstart -permite que você use estes comandos: - -* `start myapp` – Inicia o aplicativo -* `restart myapp` – Reinicia o aplicativo -* `stop myapp` – Para o aplicativo - -Para obter mais informações sobre o Upstart, consulte a -[Introdução, Cookbook, -e Melhores Práticas para o Upstart](http://upstart.ubuntu.com/cookbook). - -##### StrongLoop PM como um serviço do Upstart - -É possível facilmente instalar o StrongLoop Process Manager -como um serviço do Upstart. Após fazer isso, quando o servidor -reiniciar, ele irá automaticamente reiniciar o StrongLoop PM, que irá -então reiniciar todos os aplicativos que está gerenciando. - -Para instalar o StrongLoop PM como um serviço do Upstart 1.4: - -```bash -$ sudo sl-pm-install -``` - -Em seguida execute o serviço com: - -```bash -$ sudo /sbin/initctl start strong-pm -``` - -NOTA: Em sistemas que não suportam o Upstart 1.4, os comandos -são ligeiramente diferentes. Consulte [Configurando -um host de produção (documentação do StrongLoop)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) para obter mais informações. +Para obter mais informações sobre o systemd, consulte a +referência +do systemd (página do manual). ### Execute seu aplicativo em um cluster @@ -536,7 +334,7 @@ de processos. Um cluster executa múltiplas instâncias do aplicativo, idealmente uma instância em cada núcleo da CPU, assim distribuindo a carga e as tarefas entre as instâncias. - +![Balancing between application instances using the cluster API](/images/clustering.png) IMPORTANTE: Como as instâncias do aplicativo são executadas em processos separados, elas não compartilham o mesmo espaço de memória. Isto é, os objetos são locais para cada instância do aplicativo. Portanto, não é possível manter o estado no código do aplicativo. Entretanto, é possível usar um armazenamento de dados em memória como o [Redis](http://redis.io/) para armazenar dados relativos à sessão e ao estado. Este alerta aplica-se a essencialmente todas as formas de escalonamento horizontal, seja a @@ -546,39 +344,37 @@ Em aplicativos clusterizados, processos de trabalho podem cair individualmente s #### Usando o módulo de cluster do Node -A clusterização é pode ser feita com o [módulo de -cluster](https://nodejs.org/docs/latest/api/cluster.html) do Node. Isto permite que um processo principal faça o +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). Isto permite que um processo principal faça o spawn de processos de trabalho e distribua conexões recebidas entre -os trabalhadores. Entretanto, em vez de usar este módulo diretamente, -é muito melhor usar uma das muitas ferramentas que fazem isso -automaticamente por você; por exemplo o [node-pm](https://www.npmjs.com/package/node-pm) ou -o [cluster-service](https://www.npmjs.com/package/cluster-service). +os trabalhadores. -#### Usando o StrongLoop PM +#### Using PM2 -Se você implementar seu aplicativo no StrongLoop Process Manager -(PM), então é possível tirar vantagem da clusterização -*sem* modificar o código do seu aplicativo. +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 o StrongLoop Process Manager (PM) executa um aplicativo, -ele automaticamente executa-o em um cluster com um número de -trabalhadores igual ao número de núcleos de CPU do sistema. É -possível manualmente alterar o número de processos de trabalho no -cluster usando a ferramenta de linha de comandos slc 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. -Por exemplo, assumindo que tenha implementado o seu aplicativo -para prod.foo.com e o StrongLoop PM está escutando na porta 8701 (a -padrão), em seguida configurar o tamanho do cluster para oito usando -o slc: +To enable cluster mode, start your application like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -Para obter mais informações sobre clusterização com o StrongLoop -PM, consulte por [Clusterização](https://docs.strongloop.com/display/SLC/Clustering) -na documentação do StrongLoop. +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 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ 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. ### Armazene em cache os resultados das solicitações @@ -587,12 +383,7 @@ armazenar em cache o resultado de solicitações, para que o seu aplicativo não repita a operação para entregar a mesma solicitação repetidamente. -Use um servidor de armazenamento em cache como o -[Varnish](https://www.varnish-cache.org/) ou o -[Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) -(consulte também [Armazenamento -em Cache no Nginx](https://serversforhackers.com/nginx-caching/)) para melhorar imensamente a velocidade e o -desempenho do seu aplicativo. +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 um balanceador de carga @@ -606,29 +397,17 @@ que é possível com uma instância única. Um balanceador de carga é geralmente um proxy reverso que orquestra o tráfego para e de múltiplas instâncias de aplicativo e -servidores. É possível facilmente configurar um balanceador de carga -para o seu aplicativo usando o [Nginx](http://nginx.org/en/docs/http/load_balancing.html) -ou o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +servidores. 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 solicitações que estão associadas com um ID de sessão em particular conectam ao processo que as originou. Isto é conhecido como -*afinidade de sessão*, ou *sessões -pegajosas*, e podem ser endereçadas pela sugestão acima para +_afinidade de sessão_, ou _sessões +pegajosas_, e podem ser endereçadas pela sugestão acima para usar um armazenamento de dados como o Redis para os dados da sessão (dependendo do seu aplicativo). Para uma discussão, consulte por [Usando múltiplos nós](https://socket.io/docs/v4/using-multiple-nodes/). -#### Usando o StrongLoop PM com um balanceador de carga Nginx - -O [StrongLoop Process -Manager](http://strong-pm.io/) é integrado com um Controlador Nginx, tornando mais -fácil a configurar configurações de ambientes de produção com -múltiplos hosts. Para obter mais informações, consulte por -[Escalando -para servidores múltiplos](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers) (documentação do StrongLoop). - - ### Use um proxy reverso Um proxy reverso fica em frente a um aplicativo web e executa @@ -639,7 +418,4 @@ balanceamento de carga entre outras coisas. Entregar tarefas que não requerem conhecimento do estado do aplicativo para um proxy reverso libera o Express para executar -tarefas especializadas de aplicativos. Por esta razão, é recomendado -executar o Express atrás de um proxy reverso como o -[Nginx](https://www.nginx.com/) ou o -[HAProxy](http://www.haproxy.org/) na produção. +tarefas especializadas de aplicativos. 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. diff --git a/pt-br/advanced/best-practice-security.md b/pt-br/advanced/best-practice-security.md old mode 100755 new mode 100644 index e72fe463f5..1bcb7297cd --- a/pt-br/advanced/best-practice-security.md +++ b/pt-br/advanced/best-practice-security.md @@ -1,19 +1,19 @@ --- layout: page title: Melhores Práticas de Segurança para o Express em Produção +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: pt-br -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # Melhores Práticas em Produção: Segurança ## Visão Geral -O termo *"produção"* refere-se ao estágio no ciclo de vida do software onde um aplicativo ou API está geralmente -disponível para os seus usuários finais ou consumidores. Em contrapartida, no estágio de *"desenvolvimento"*, -você ainda está ativamente escrevendo e testando o código, e o aplicativo não está aberto para acesso externo. Os ambiente de sistema correspondentes são conhecidos como ambientes de *produção* e *desenvolvimento*, +O termo _"produção"_ refere-se ao estágio no ciclo de vida do software onde um aplicativo ou API está geralmente +disponível para os seus usuários finais ou consumidores. Em contrapartida, no estágio de _"desenvolvimento"_, +você ainda está ativamente escrevendo e testando o código, e o aplicativo não está aberto para acesso externo. Os ambiente de sistema correspondentes são conhecidos como ambientes de _produção_ e _desenvolvimento_, respectivamente. Os ambientes de desenvolvimento e produção são geralmente @@ -25,13 +25,45 @@ ambiente de produção. E em desenvolvimento, você não precisa se preocupar com a escalabilidade, confiabilidade, e desempenho, enquanto estas preocupações se tornam críticas na produção. +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + Este artigo discute algumas melhores práticas de segurança para aplicativos do Express implementadas na produção. +- [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) + - A [hsts](https://github.com/helmetjs/hsts) configura o cabeçalho `Strict-Transport-Security` + que impinge conexões seguras (HTTP sobre SSL/TLS) com o servidor. + - A principal diferença entre esses dois módulos é como eles salvam os dados de cookies de sessão. O middleware [express-session](https://www.npmjs.com/package/express-session) + armazena os dados da sessão no servidor; ele salva apenas o ID da + sessão no cookie, não os dados da sessão. Por padrão, ele usa + armazenamento em memória e não é projetado para um ambiente de + produção. Em produção, será necessário configurar um armazenamento de + sessão escalável; consulte a lista de armazenamentos + de sessão compatíveis. + - A [ieNoOpen](https://github.com/helmetjs/ienoopen) configura o `X-Download-Options` para o IE8+. + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure) + - A [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) remove o cabeçalho `X-Powered-By`. + - [Additional considerations](#additional-considerations) + ## Não use versões descontinuadas ou vulneráveis do Express Os Express 2.x e 3.x não são mais mantidos. Problemas de -segurança e desempenho nestas versões não serão corrigidos. Não use-as! Se +segurança e desempenho nestas versões não serão corrigidos. Não use-as! Se não tiver migrado para a versão 4, siga o [guia de migração](/{{ page.lang }}/guide/migrating-4.html). Assegure-se também de que não esteja usando nenhuma das versões @@ -42,8 +74,8 @@ liberações estáveis, preferivelmente a mais recente. ## Use TLS Se o seu aplicativo negocia com ou transmite dados sensíveis, -use a [Segurança -da Camada de Transporte](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) para proteger a conexão e os +use a Segurança +da Camada de Transporte (TLS) para proteger a conexão e os dados. Esta tecnologia criptografa os dados antes deles serem enviados do cliente para o servidor, assim evitando alguns ataques comuns (e fáceis). Apesar de solicitações Ajax e POST não parecerem @@ -51,19 +83,46 @@ visivelmente óbvias e parecerem "ocultas" em navegadores, o seu tráfego de rede é vulnerável a [sniffing de pacotes](https://en.wikipedia.org/wiki/Packet_analyzer) e [ataques man-in-the-middle ](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). -Você pode estar familiarizado com a criptografia Secure Sockets Layer(SSL). [O -TLS é simplesmente a próxima progressão do](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx). Em outras palavras, se você estava usando o SSL antes, considere fazer o -upgrade para o TLS. Em geral, recomendamos o Nginx para lidar com o TLS. Para +Você pode estar familiarizado com a criptografia Secure Sockets Layer(SSL). O +TLS é simplesmente a próxima progressão do. Em outras palavras, se você estava usando o SSL antes, considere fazer o +upgrade para o TLS. Em geral, recomendamos o Nginx para lidar com o TLS. Para obter uma boa referência para configurar o TLS no Nginx (e outros servidores), consulte -[Configurações -Recomendadas de Servidores (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations). +Configurações +Recomendadas de Servidores (Mozilla Wiki). Além disso, uma ferramenta útil para obter um certificado TLS -gratuito é a [Let's -Encrypt](https://letsencrypt.org/about/), uma autoridade de certificação (CA) gratuita, +gratuito é a Let's +Encrypt, uma autoridade de certificação (CA) gratuita, automatizada, e aberta fornecida pelo -[Grupo de Pesquisas de -Segurança da Internet (ISRG)](https://letsencrypt.org/isrg/). +Grupo de Pesquisas de +Segurança da Internet (ISRG). + +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` ## Use Helmet @@ -71,59 +130,87 @@ O [Helmet](https://www.npmjs.com/package/helmet) pode ajudar a proteger o seu aplicativo de algumas vulnerabilidades da web bastante conhecidas configurando os cabeçalhos HTTP adequadamente. -O Helmet é na realidade apenas uma coleção de nove funções de -middlewares menores que configuram cabeçalhos HTTP relacionados à -segurança: +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: + +- `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 +- `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 +- `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 -* A [csp](https://github.com/helmetjs/csp) configura o cabeçalho `Content-Security-Policy` para ajudar a evitar ataques de cross-site scripting e outras injeções cross-site. -* A [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) remove o cabeçalho `X-Powered-By`. -* A [hsts](https://github.com/helmetjs/hsts) configura o cabeçalho `Strict-Transport-Security` -que impinge conexões seguras (HTTP sobre SSL/TLS) com o servidor. -* A [ieNoOpen](https://github.com/helmetjs/ienoopen) configura o `X-Download-Options` para o IE8+. -* A [noCache](https://github.com/helmetjs/nocache) configura os cabeçalhos `Cache-Control` e Pragma -para desativar o armazenamento em cache no lado do cliente. -* A [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) -configura o `X-Content-Type-Options` para evitar que os navegadores procurem por MIME uma resposta a partir do -content-type declarado. -* A [frameguard](https://github.com/helmetjs/frameguard) -configura o cabeçalho `X-Frame-Options` para fornecer proteção [clickjacking](https://www.owasp.org/index.php/Clickjacking). -* A [xssFilter](https://github.com/helmetjs/x-xss-protection) -configura o `X-XSS-Protection` para ativar o filtro -de Cross-site scripting (XSS) nos navegadores da web mais recentes. +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Instale o Helmet como qualquer outro módulo: ```bash -$ npm install --save helmet +$ npm install helmet ``` Em seguida use-o no seu código: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### No mínimo, desative o cabeçalho X-Powered-By +## Reduce fingerprinting -Se não desejar usar o Helmet, então pelo menos desative o -cabeçalho `X-Powered-By`. Invasores podem utilizar -este cabeçalho (que fica ativado por padrão) para detectar -aplicativos executando o Express e então iniciar ataques -especificamente direcionados a eles. +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. -Portanto, a melhor prática é desligar o cabeçalho com o método -`app.disable()`: +By default, Express sends the `X-Powered-By` response header that you can +disable using the `app.disable()` method: ```js app.disable('x-powered-by') ``` -Se usar o `helmet.js`, ele cuida disso por você. +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## Use cookies de maneira segura @@ -134,29 +221,23 @@ opções de segurança de cookies adequadamente. Existem dois módulos de middleware principais para sessão de cookies: -* [express-session](https://www.npmjs.com/package/express-session) -que substitui o middleware `express.session` -integrado no Express 3.x. -* [cookie-session](https://www.npmjs.com/package/cookie-session) -que substitui o middleware `express.cookieSession` integrado no Express 3.x. +- [express-session](https://www.npmjs.com/package/express-session) + que substitui o middleware `express.session` + integrado no Express 3.x. +- [cookie-session](https://www.npmjs.com/package/cookie-session) + que substitui o middleware `express.cookieSession` integrado no Express 3.x. -A principal diferença entre esses dois módulos é como eles salvam os dados de cookies de sessão. O middleware [express-session](https://www.npmjs.com/package/express-session) -armazena os dados da sessão no servidor; ele salva apenas o ID da -sessão no cookie, não os dados da sessão. Por padrão, ele usa -armazenamento em memória e não é projetado para um ambiente de -produção. Em produção, será necessário configurar um armazenamento de -sessão escalável; consulte a lista de [armazenamentos -de sessão compatíveis](https://github.com/expressjs/session#compatible-session-stores). +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). Em contrapartida, o middleware [cookie-session](https://www.npmjs.com/package/cookie-session) -implementa um armazenamento apoiado em cookies: ele serializa a sessão inteira para o cookie, ao invés de apenas a chave da sessão. Use apenas quando os dados da sessão são relativamente pequenos e facilmente codificados como números primitivos(ao invés de objetos). Apesar de navegadores supostamente suportarem pelo menos 4096 bytes por cookie, para assegurar que você não exceda o limite, não exceda -um tamanho de 4093 bytes por domínio. Além disso, esteja ciente de que os dados do cookie serão visíveis para o cliente, portanto se +implementa um armazenamento apoiado em cookies: ele serializa a sessão inteira para o cookie, ao invés de apenas a chave da sessão. Use apenas quando os dados da sessão são relativamente pequenos e facilmente codificados como números primitivos(ao invés de objetos). Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Apesar de navegadores supostamente suportarem pelo menos 4096 bytes por cookie, para assegurar que você não exceda o limite, não exceda +um tamanho de 4093 bytes por domínio. Além disso, esteja ciente de que os dados do cookie serão visíveis para o cliente, portanto se houver razão para mantê-los seguros ou obscuros, então o express-session pode ser uma escolha melhor. ### Não use o nome do cookie da sessão padrão Usando o nome do cookie da sessão padrão pode deixar o seu -aplicativo aberto a ataques. O problema de segurança levantado é +aplicativo aberto a ataques. O problema de segurança levantado é parecido ao do `X-Powered-By`: um invasor em potencial poderia usá-lo para identificar o servidor e direcionar ataques de acordo com ele. @@ -170,8 +251,7 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### Configure as opções de segurança de cookie @@ -179,14 +259,14 @@ app.use(session({ Configure as seguintes opções de cookie para aprimorar a segurança: -* `secure` - Assegura que o navegador só envie o cookie por HTTPS. -* `httpOnly` - Assegura que o cookie seja enviado apenas por HTTP(S), não por cliente JavaScript, ajudando -assim a se proteger contra ataques de cross-site scripting. -* `domain` - indica o domínio do cookie; use-o para comparação contra o domínio do servidor em que a URL está -sendo solicitada. Se elas corresponderem, verifique o atributo de caminho em seguida. -* `path` - indica o caminho do cookie; use-o para comparação contra o caminho da solicitação. Se este e o domínio corresponderem, então envie o cookie na solicitação. -* `expires` - use para configurar uma data de -expiração para cookies persistentes. +- `secure` - Assegura que o navegador só envie o cookie por HTTPS. +- `httpOnly` - Assegura que o cookie seja enviado apenas por HTTP(S), não por cliente JavaScript, ajudando + assim a se proteger contra ataques de cross-site scripting. +- `domain` - indica o domínio do cookie; use-o para comparação contra o domínio do servidor em que a URL está + sendo solicitada. Se elas corresponderem, verifique o atributo de caminho em seguida. +- `path` - indica o caminho do cookie; use-o para comparação contra o caminho da solicitação. Se este e o domínio corresponderem, então envie o cookie na solicitação. +- `expires` - use para configurar uma data de + expiração para cookies persistentes. Aqui está um exemplo usando o middleware [cookie-session](https://www.npmjs.com/package/cookie-session): @@ -206,36 +286,68 @@ app.use(session({ path: 'foo/bar', expires: expiryDate } -}) -) +})) ``` -## Considerações adicionais +## 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. + +[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) + +## 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. + +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` -Aqui estão algumas recomendações adicionais da excelente [Lista -de Verificação de Segurança do Node.js](https://blog.risingstack.com/node-js-security-checklist/). Refira-se a esta postagem do blog para obter todos os detalhes destas recomendações: - -* Implemente limitações de tráfego para evitar ataques de força -bruta contra a autenticação. Uma forma de fazer isso é usar o [Gateway -da API do StrongLoop](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) para impingir políticas de limitação de tráfego. Alternativamente, -é possível usar um middleware como o [express-limiter](https://www.npmjs.com/package/express-limiter), -mas fazer isso irá requerer que você modifique seu código de alguma forma. -* Sempre filtrar e limpar a entrada do usuário para se proteger de ataques de cross-site scripting (XSS) e injeção de comando. -* Proteja-se contra ataques de injeção de SQLs usando consultas parametrizadas ou instruções preparadas. -* Use a ferramenta de software livre [sqlmap](http://sqlmap.org/) para detectar -vulnerabilidades de injeção de SQL no seu aplicativo. -* Use as ferramentas [nmap](https://nmap.org/) e [sslyze](https://github.com/nabla-c0d3/sslyze) para -testar a configuração das suas cifras SSL, chaves, e renegociação, bem como a validade do seu certificado. -* Use o [safe-regex](https://www.npmjs.com/package/safe-regex) para assegurar que suas expressões regulares não estejam suscetíveis -a ataques [negação de serviço de expressões regulares](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). - -## Evitar outras vulnerabilidades conhecidas +If you want to stay more secure, consider [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: + +```bash +$ npm install -g snyk +$ cd your-app +``` + +Use this command to test your application for vulnerabilities: + +```bash +$ snyk test +``` + +### Evitar outras vulnerabilidades conhecidas Fique atento às recomendações do -[Node Security -Project](https://npmjs.com/advisories) que podem afetar o Express ou outros módulos usados -pelo seu aplicativo. Em geral, o Node Security Project é um excelente +Node Security +Project que podem afetar o Express ou outros módulos usados +pelo seu aplicativo. Em geral, o Node Security Project é um excelente recurso para conhecimento e ferramentas sobre segurança do Node. Finalmente, os aplicativos do Express - como outros aplicativos web - podem estar vulneráveis a uma variedade de ataques baseados na web. Familiarize-se com [vulnerabilidades web](https://www.owasp.org/www-project-top-ten/) conhecidas e tome precauções para evitá-las. + +## Considerações adicionais + +Aqui estão algumas recomendações adicionais da excelente Lista +de Verificação de Segurança do Node.js. Refira-se a esta postagem do blog para obter todos os detalhes destas recomendações: + +- Sempre filtrar e limpar a entrada do usuário para se proteger de ataques de cross-site scripting (XSS) e injeção de comando. +- Proteja-se contra ataques de injeção de SQLs usando consultas parametrizadas ou instruções preparadas. +- Use a ferramenta de software livre [sqlmap](http://sqlmap.org/) para detectar + vulnerabilidades de injeção de SQL no seu aplicativo. +- Use as ferramentas [nmap](https://nmap.org/) e [sslyze](https://github.com/nabla-c0d3/sslyze) para + testar a configuração das suas cifras SSL, chaves, e renegociação, bem como a validade do seu certificado. +- Use o [safe-regex](https://www.npmjs.com/package/safe-regex) para assegurar que suas expressões regulares não estejam suscetíveis + a ataques [negação de serviço de expressões regulares](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS). + +[helmet]: https://helmetjs.github.io/ \ No newline at end of file diff --git a/pt-br/advanced/developing-template-engines.md b/pt-br/advanced/developing-template-engines.md old mode 100755 new mode 100644 index dbe572bd7d..8ce0c3e671 --- a/pt-br/advanced/developing-template-engines.md +++ b/pt-br/advanced/developing-template-engines.md @@ -1,10 +1,10 @@ --- layout: page title: Desenvolvendo mecanismos de modelo para o 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. menu: advanced lang: pt-br -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. +redirect_from: " " --- # Desenvolvendo mecanismos de modelo para o Express @@ -23,9 +23,10 @@ de modelo muito simples para renderização de arquivos `.ntl`. const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -42,6 +43,7 @@ um arquivo chamado `index.ntl` no diretório #title# #message# ``` + Em seguida, crie a seguinte rota no seu aplicativo. ```js @@ -49,4 +51,5 @@ app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -Ao fazer uma solicitação à página inicial, o `index.ntl` será renderizado como HTML. + +Ao fazer uma solicitação à página inicial, o `index.ntl` será renderizado como HTML. \ No newline at end of file diff --git a/pt-br/advanced/healthcheck-graceful-shutdown.md b/pt-br/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..7977d5973f --- /dev/null +++ b/pt-br/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: pt-br +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### Exemplo + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/pt-br/advanced/security-updates.md b/pt-br/advanced/security-updates.md old mode 100755 new mode 100644 index 51882149ef..5ad69753ac --- a/pt-br/advanced/security-updates.md +++ b/pt-br/advanced/security-updates.md @@ -1,10 +1,10 @@ --- layout: page title: Atualizações de segurança do Express +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: pt-br -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # Atualizações de segurança @@ -20,46 +20,85 @@ usando a versão estável mais recente do Node.js. A lista abaixo enumera as vulnerabilidades do Express que foram corrigidas na versão da atualização especificadas. -## 4.x +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} - * 4.11.1 - * Corrigida a vulnerabilidade de divulgação do caminho -raiz no `express.static`, `res.sendfile`, e `res.sendFile` - * 4.10.7 - * Corrigida a vulnerabilidade de redirecionamento aberto -no `express.static` ([recomendação](https://npmjs.com/advisories/35), -[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 4.8.8 - * Corrigida a vulnerabilidade de travessia de diretório no `express.static` ([recomendação](http://npmjs.com/advisories/32), [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)). - * 4.8.4 - * O Node.js 0.10 pode vazar os `fd`s em certas situações que afetam o `express.static` e o -`res.sendfile`. Solicitações maliciosas podem causar os `fd`s a vazar e eventualmente levar a erros -de `EMFILE` e servidores sem capacidade de resposta. - * 4.8.0 - * Matrizes esparsas que possuem índices extremamente altos na sequência de consulta podem fazer com que o processo sofra um -esgotamento de memória e derrubar o servidor. - * Objetos de sequência de consulta extremamente aninhados podem fazer com que o processo fique bloqueado e o servidor -temporariamente não responsivo. +## 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - Corrigida a vulnerabilidade de divulgação do caminho + raiz no `express.static`, `res.sendfile`, e `res.sendFile` +- 4.10.7 + - Corrigida a vulnerabilidade de redirecionamento aberto no `express.static` ([recomendação](https://npmjs.com/advisories/35), + [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 4.8.8 + - Corrigida a vulnerabilidade de travessia de diretório no `express.static` ([recomendação](http://npmjs.com/advisories/32), [CVE-2014-6394](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6394)). +- 4.8.4 + - O Node.js 0.10 pode vazar os `fd`s em certas situações que afetam o `express.static` e o + `res.sendfile`. Solicitações maliciosas podem causar os `fd`s a vazar e eventualmente levar a erros de + `EMFILE` e servidores sem capacidade de resposta. +- 4.8.0 + - Matrizes esparsas que possuem índices extremamente altos na sequência de consulta podem fazer com que o processo sofra um + esgotamento de memória e derrubar o servidor. + - Objetos de sequência de consulta extremamente aninhados podem fazer com que o processo fique bloqueado e o servidor + temporariamente não responsivo. ## 3.x - * 3.19.1 - * Corrigida a vulnerabilidade de divulgação do caminho raiz no `express.static`, -`res.sendfile`, e `res.sendFile` - * 3.19.0 - * Corrigida a vulnerabilidade de redirecionamento aberto no `express.static` ([recomendação](https://npmjs.com/advisories/35), -[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). - * 3.16.10 - * Corrigida a vulnerabilidade de travessia de diretório no `express.static`. - * 3.16.6 - * O Node.js 0.10 pode vazar os `fd`s em certas situações que afetam o `express.static` e o -`res.sendfile`. Solicitações maliciosas podem causar os `fd`s a vazar e eventualmente levar a erros de -`EMFILE` e servidores sem capacidade de resposta. - * 3.16.0 - * Matrizes esparsas que possuem índices extremamente altos na sequência de consulta podem fazer com que o processo sofra um -esgotamento de memória e derrubar o servidor. - * Objetos de sequência de consulta extremamente aninhados podem fazer com que o processo fique bloqueado e o servidor -temporariamente não responsivo. - * 3.3.0 - * A resposta 404 de uma tentativa de substituição de um método não suportado era suscetível a ataques de cross-site scripting. +
    + **Express 3.x support is ending soon** + +This series will continue to receive only security updates and bug fixes until July 2015. It is highly recommended to upgrade to Express 4.x. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
    + +- 3.19.1 + - Corrigida a vulnerabilidade de divulgação do caminho + raiz no `express.static`, `res.sendfile`, e `res.sendFile` +- 3.19.0 + - Corrigida a vulnerabilidade de redirecionamento aberto no `express.static` ([recomendação](https://npmjs.com/advisories/35), + [CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164)). +- 3.16.10 + - Corrigida a vulnerabilidade de travessia de diretório no `express.static`. +- 3.16.6 + - O Node.js 0.10 pode vazar os `fd`s em certas situações que afetam o `express.static` e o + `res.sendfile`. Solicitações maliciosas podem causar os `fd`s a vazar e eventualmente levar a erros de + `EMFILE` e servidores sem capacidade de resposta. +- 3.16.0 + - Matrizes esparsas que possuem índices extremamente altos na sequência de consulta podem fazer com que o processo sofra um + esgotamento de memória e derrubar o servidor. + - Objetos de sequência de consulta extremamente aninhados podem fazer com que o processo fique bloqueado e o servidor + temporariamente não responsivo. +- 3.3.0 + - A resposta 404 de uma tentativa de substituição de um método não suportado era suscetível a ataques de cross-site scripting. \ No newline at end of file diff --git a/pt-br/api.md b/pt-br/api.md old mode 100755 new mode 100644 index 6fec24bf7d..c837c6b1de --- a/pt-br/api.md +++ b/pt-br/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - Referência de API +version: 5x +title: Express 5.x - Referência da API +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: pt-br -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    API 4.x

    - - - {% include api/en/4x/express.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
    diff --git a/pt-br/changelog/index.md b/pt-br/changelog/index.md new file mode 100644 index 0000000000..d12f94c6f6 --- /dev/null +++ b/pt-br/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: pt-br +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/pt-br/guide/behind-proxies.md b/pt-br/guide/behind-proxies.md old mode 100755 new mode 100644 index c27062f136..dedaefed07 --- a/pt-br/guide/behind-proxies.md +++ b/pt-br/guide/behind-proxies.md @@ -1,27 +1,25 @@ --- layout: page title: Express atrás de 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. menu: guide lang: pt-br -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. +redirect_from: " " --- # Express atrás de proxies +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. + +
    +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. +
    + Ao executar um aplicativo do Express atrás de um proxy, configure (usando [app.set()](/{{ page.lang }}/4x/api.html#app.set)) a variável do aplicativo `trust proxy` para um dos valores listados na seguinte tabela. -
    -Apesar de a execução do aplicativo não falhar se a variável do -aplicativo `trust proxy` não estiver configurada, -ele irá registrar incorretamente o endereço de IP do proxy como o -endereço de IP do cliente a não ser que o `trust -proxy` esteja configurado. -
    - @@ -35,18 +33,20 @@ Se `false`, o aplicativo é compreendido como exposto diretamente à Internet e o endereço de IP do cliente é derivado a partir do `req.connection.remoteAddress`. Esta é a configuração padrão. + +
    +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. +
    - + - +
    TipoValor
    Endereços IPIP addresses -Um endereço de IP, sub-rede, ou uma matriz de endereços de IP e -sub-redes confiáveis. A lista a seguir mostra os nomes de sub-rede -pré-configurados: +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: -* 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` +- 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` É possível configurar endereços de IP de qualquer uma das formas a seguir: @@ -61,21 +61,24 @@ app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify mult Quando especificados, os endereços de IP ou sub-redes são excluídos do processo de determinação de endereço, e o endereço de IP não confiável mais próximos do servidor de aplicativos é -determinado como o endereço de IP do cliente. +determinado como o endereço de IP do cliente. 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. +
    Número -Confia no `n`-ésimo hop a partir do servidor de -proxy frontal como o cliente. +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. + +
    +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. +
    FunçãoFunction -Implementação de confiança customizada. Use apenas se souber o que está fazendo. - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -83,14 +86,13 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
    -Configurando um valor não-`false` para o -`trust -proxy` resulta em três mudanças importantes: +Enabling `trust proxy` will have the following impact:
    • O valor de [req.hostname](/{{ page.lang }}/api.html#req.hostname) é diff --git a/pt-br/guide/database-integration.md b/pt-br/guide/database-integration.md old mode 100755 new mode 100644 index e5613d50e0..8199d90a5f --- a/pt-br/guide/database-integration.md +++ b/pt-br/guide/database-integration.md @@ -1,10 +1,10 @@ --- layout: page title: Integração de banco de dados do Express +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: pt-br -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # Integração de Banco de dados @@ -13,335 +13,483 @@ A inclusão da capacidade de se conectar à banco de dados em aplicativos do Exp Node.js apropriado para o banco de dados no seu aplicativo. Este documento explica brevemente como incluir e utilizar alguns dos mais populares módulos do Node.js para sistemas de bancos de dados no seu aplicativo do Express: -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
      Estes drivers de banco de dados estão entre os muitos que estão disponíveis. Para obter outras opções, procure no site [npm](https://www.npmjs.com/).
      - - ## Cassandra **Módulo**: [cassandra-driver](https://github.com/datastax/nodejs-driver) **Instalação** +### Installation + ```bash $ npm install cassandra-driver ``` -**Exemplo** +### Exemplo + +```js +const cassandra = require('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 -
      -
      -var cassandra = require('cassandra-driver');
      -var client = new cassandra.Client({ contactPoints: ['localhost']});
      +**Module**: [couchnode](https://github.com/couchbase/couchnode)
       
      -client.execute('select key from system.local', function(err, result) {
      -  if (err) throw err;
      -  console.log(result.rows[0]);
      -});
      -
      -
      +### Installation - +```bash +$ npm install couchbase +``` + +### Exemplo + +```js +const couchbase = require('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) **Instalação** +### Installation + ```bash $ npm install nano ``` -**Exemplo** +### Exemplo -
      -
      -var nano = require('nano')('http://localhost:5984');
      -nano.db.create('books');
      -var books = nano.db.use('books');
      +```js
      +const nano = require('nano')('http://localhost:5984')
      +nano.db.create('books')
      +const books = nano.db.use('books')
       
      -//Insert a book document in the books database
      -books.insert({name: 'The Art of war'}, null, function(err, body) {
      -  if (!err){
      -    console.log(body);
      +// Insert a book document in the books database
      +books.insert({ name: 'The Art of war' }, null, (err, body) => {
      +  if (err) {
      +    console.log(err)
      +  } else {
      +    console.log(body)
         }
      -});
      -
      -//Get a list of all books
      -books.list(function(err, body){
      -  console.log(body.rows);
      -});
      -
      -
      +}) - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **Módulo**: [levelup](https://github.com/rvagg/node-levelup) **Instalação** +### Installation + ```bash $ npm install level levelup leveldown ``` -**Exemplo** - -
      -
      -var levelup = require('levelup');
      -var db = levelup('./mydb');
      +### Exemplo
       
      -db.put('name', 'LevelUP', function (err) {
      +```js
      +const levelup = require('levelup')
      +const db = levelup('./mydb')
       
      -  if (err) return console.log('Ooops!', err);
      -  db.get('name', function (err, value) {
      -    if (err) return console.log('Ooops!', err);
      -    console.log('name=' + value);
      -  });
      +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/) **Instalação** +### Installation + ```bash $ npm install mysql ``` -**Exemplo** +### Exemplo -
      -
      -var mysql      = require('mysql');
      -var connection = mysql.createConnection({
      -  host     : 'localhost',
      -  user     : 'dbuser',
      -  password : 's3kreee7'
      -});
      +```js
      +const mysql = require('mysql')
      +const connection = mysql.createConnection({
      +  host: 'localhost',
      +  user: 'dbuser',
      +  password: 's3kreee7',
      +  database: 'my_db'
      +})
       
      -connection.connect();
      +connection.connect()
       
      -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      -  if (err) throw err;
      -  console.log('The solution is: ', rows[0].solution);
      -});
      +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
      +  if (err) throw err
       
      -connection.end();
      -
      -
      + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **Módulo**: [mongodb](https://github.com/mongodb/node-mongodb-native) **Instalação** +### Installation + ```bash $ npm install mongodb ``` -**Exemplo** +### Example (v2.\*) -
      -
      -var MongoClient = require('mongodb').MongoClient;
      +```js
      +const MongoClient = require('mongodb').MongoClient
       
      -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
      -  if (err) {
      -    throw err;
      -  }
      -  db.collection('mammals').find().toArray(function(err, result) {
      -    if (err) {
      -      throw err;
      -    }
      -    console.log(result);
      -  });
      -});
      -
      -
      +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +### Example (v3.\*) + +```js +const MongoClient = require('mongodb').MongoClient + +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err + + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` Se desejar um driver de modelo de objeto para o MongoDB, consulte em [Mongoose](https://github.com/LearnBoost/mongoose). - - ## Neo4j **Módulo**: [apoc](https://github.com/hacksparrow/apoc) **Instalação** +### Installation + ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**Exemplo** +### Exemplo -
      -
      -var apoc = require('apoc');
      +```js
      +const neo4j = require('neo4j-driver')
      +const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
       
      -apoc.query('match (n) return n').exec().then(
      -  function (response) {
      -    console.log(response);
      -  },
      -  function (fail) {
      -    console.log(fail);
      -  }
      -);
      -
      -
      +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) + }) +}) +``` -## PostgreSQL +## Oracle **Módulo**: [pg](https://github.com/brianc/node-postgres) **Instalação** +### Installation + +NOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation). + ```bash -$ npm install pg +$ npm install oracledb ``` -**Exemplo** +### Exemplo + +```js +const oracledb = require('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() + } + } +} -
      -
      -var pg = require('pg');
      -var conString = "postgres://username:password@localhost/database";
      +getEmployee(101)
      +```
       
      -pg.connect(conString, function(err, client, done) {
      +## PostgreSQL
       
      -  if (err) {
      -    return console.error('error fetching client from pool', err);
      -  }
      -  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
      -    done();
      -    if (err) {
      -      return console.error('error running query', err);
      -    }
      -    console.log(result.rows[0].number);
      -  });
      +**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)
       
      -});
      -
      -
      +### Installation - +```bash +$ npm install pg-promise +``` + +### Exemplo + +```js +const pgp = require('pg-promise')(/* options */) +const db = pgp('postgres://username:password@host:port/database') + +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **Módulo**: [redis](https://github.com/mranney/node_redis) **Instalação** +### Installation + ```bash $ npm install redis ``` -**Exemplo** +### Exemplo + +```js +const redis = require('redis') +const client = redis.createClient() -
      -
      -var client = require('redis').createClient();
      +client.on('error', (err) => {
      +  console.log(`Error ${err}`)
      +})
       
      -client.on('error', function (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.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:`)
       
      -client.hkeys('hash key', function (err, replies) {
      +  replies.forEach((reply, i) => {
      +    console.log(`    ${i}: ${reply}`)
      +  })
       
      -  console.log(replies.length + ' replies:');
      -  replies.forEach(function (reply, i) {
      -    console.log('    ' + i + ': ' + reply);
      -  });
      +  client.quit()
      +})
      +```
       
      -  client.quit();
      +## SQL Server
       
      -});
      -
      -
      +**Module**: [tedious](https://github.com/tediousjs/tedious) - +### Installation + +```bash +$ npm install tedious +``` + +### Exemplo + +```js +const Connection = require('tedious').Connection +const Request = require('tedious').Request + +const config = { + server: 'localhost', + authentication: { + type: 'default', + options: { + userName: 'your_username', // update me + password: 'your_password' // update me + } + } +} + +const connection = new Connection(config) + +connection.on('connect', (err) => { + if (err) { + console.log(err) + } else { + executeStatement() + } +}) + +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) + + connection.execSql(request) +} +``` ## SQLite **Módulo**: [sqlite3](https://github.com/mapbox/node-sqlite3) **Instalação** +### Installation + ```bash $ npm install sqlite3 ``` -**Exemplo** +### Exemplo -
      -
      -var sqlite3 = require('sqlite3').verbose();
      -var db = new sqlite3.Database(':memory:');
      +```js
      +const sqlite3 = require('sqlite3').verbose()
      +const db = new sqlite3.Database(':memory:')
       
      -db.serialize(function() {
      +db.serialize(() => {
      +  db.run('CREATE TABLE lorem (info TEXT)')
      +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
       
      -  db.run('CREATE TABLE lorem (info TEXT)');
      -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
      -
      -  for (var i = 0; i < 10; i++) {
      -    stmt.run('Ipsum ' + i);
      +  for (let i = 0; i < 10; i++) {
      +    stmt.run(`Ipsum ${i}`)
         }
       
      -  stmt.finalize();
      -
      -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
      -    console.log(row.id + ': ' + row.info);
      -  });
      -});
      +  stmt.finalize()
       
      -db.close();
      -
      -
      + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) + }) +}) - +db.close() +``` ## ElasticSearch **Módulo**: [elasticsearch](https://github.com/elastic/elasticsearch-js) **Instalação** +### Installation + ```bash $ npm install elasticsearch ``` -**Exemplo** +### Exemplo -
      -
      -var elasticsearch = require('elasticsearch');
      -var client = elasticsearch.Client({
      +```js
      +const elasticsearch = require('elasticsearch')
      +const client = elasticsearch.Client({
         host: 'localhost:9200'
      -});
      +})
       
       client.search({
         index: 'books',
      @@ -354,10 +502,9 @@ client.search({
             }
           }
         }
      -}).then(function(response) {
      -  var hits = response.hits.hits;
      -}, function(error) {
      -  console.trace(error.message);
      -});
      -
      -
      +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/pt-br/guide/debugging.md b/pt-br/guide/debugging.md old mode 100755 new mode 100644 index e9cad3a412..537740b07a --- a/pt-br/guide/debugging.md +++ b/pt-br/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: Depurando o Express +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: pt-br -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # Depurando o Express @@ -20,7 +20,7 @@ $ DEBUG=express:* node index.js No Windows, use o comando correspondente. ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` Executar este comando no aplicativo padrão gerado pelo @@ -62,11 +62,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -118,3 +118,27 @@ designando uma lista de nomes separados por vírgulas: ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/pt-br/guide/error-handling.md b/pt-br/guide/error-handling.md old mode 100755 new mode 100644 index 517757ea42..92326bc891 --- a/pt-br/guide/error-handling.md +++ b/pt-br/guide/error-handling.md @@ -1,17 +1,211 @@ --- layout: page title: Manipulação de erros do Express +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: pt-br -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # Manipulação de erros +_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. + +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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. Por exemplo: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + Defina funções de middleware de manipulação de erros da mesma forma que outras funções de middleware, exceto que funções de manipulação de erros possuem quatro argumentos ao invés de três: +`(err, req, res, next)`. Por exemplo: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +Se você tiver um manipulador de rota com as funções de retorno +de chamada é possível usar o parâmetro `route` +para ignorar o próximo manipulador de rota. +Por exemplo: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +Se passar qualquer coisa para a função `next()` +(exceto a sequência de caracteres `'route'`), +o Express considera a solicitação atual como estando em erro e irá +ignorar quaisquer funções restantes de roteamento e middleware que +não sejam de manipulação de erros. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. Por exemplo: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. Por exemplo: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +You could also use a chain of handlers to rely on synchronous error +catching, by reducing the asynchronous code to something trivial. Por exemplo: + +```js +app.get('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## O Manipulador de Erros Padrão + +O Express vem com um manipulador de erros integrado, que cuida +de qualquer erro que possa ser encontrado no aplicativo. Essa função +de middleware de manipulação de erros padrão é incluída no final da +pilha de funções de middleware. + +se você passar um erro para o `next()` e você +não manipulá-lo com um manipulador de erros, ele irá ser manipulado +por um manipulador de erros integrado; o erro será escrito no cliente +com o rastreio de pilha. O rastreio de pilha não será incluído no +ambiente de produção. + +
      +Configura a variável de ambiente `NODE_ENV` para +`production`, para executar o aplicativo em modo de +produção. +
      + +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. + +Se você chamar o `next()` com um erro após ter +inicializado escrevendo a resposta (por exemplo, se encontrar um erro +enquanto passa a resposta ao cliente) o manipulador de erros padrão do +Express fecha a conexão e falha a solicitação. + +Portanto ao incluir um manipulador de erro customizado, você +desejará delegar para o mecanismo de manipulação de erros padrão no +Express, quando os cabeçalhos já tiverem sido enviados para o cliente: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## 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)`. Por exemplo: ```js @@ -29,7 +223,10 @@ exemplo: const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -40,7 +237,6 @@ Repostas de dentro de uma função de middleware podem estar em qualquer formato que preferir, como uma página HTML de erros, uma mensagem simples, ou uma sequência de caracteres JSON. - Para propósitos organizacionais (e estrutura de alto nível), é possível definir várias funções de middleware de manipulação de erros, de forma muito parecida como você faria com funções de @@ -48,12 +244,14 @@ middleware comuns. Por exemplo, se desejar definir um manipulador de erros para solicitações feitas usando o `XHR`, e aqueles sem, você pode usar os seguintes comandos: - ```js const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -75,6 +273,7 @@ Também neste exemplo, o `clientErrorHandler` é definido como segue; neste caso, o erro é explicitamente passado para o próximo: +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) { @@ -85,8 +284,8 @@ function clientErrorHandler (err, req, res, next) { } } ``` -A função "catch-all" `errorHandler` pode ser implementada como segue: +A função "catch-all" `errorHandler` pode ser implementada como segue: ```js function errorHandler (err, req, res, next) { @@ -95,26 +294,16 @@ function errorHandler (err, req, res, next) { } ``` -Se passar qualquer coisa para a função `next()` -(exceto a sequência de caracteres `'route'`), -o Express considera a solicitação atual como estando em erro e irá -ignorar quaisquer funções restantes de roteamento e middleware que -não sejam de manipulação de erros. Se desejar manipular este erro de -alguma forma, você terá que criar uma rota de manipulação de erros na -próxima seção. - - -Se você tiver um manipulador de rota com as funções de retorno -de chamada é possível usar o parâmetro `route` -para ignorar 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('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -123,59 +312,16 @@ app.get('/a_route_behind_paywall', }) }) ``` + Neste exemplo, o manipulador `getPaidContent` será ignorado mas qualquer manipulador remanescente no `app` para `/a_route_behind_paywall` continuariam sendo executados. -
      Chamadas para `next()` e `next(err)` -indicam que o manipulador atual está completo e em qual estado. -`next(err)` irá ignorar todos os manipuladores +indicam que o manipulador atual está completo e em qual estado. `next(err)` irá ignorar todos os manipuladores remanescentes na cadeia exceto por aqueles que estão configurados para manipular erros como descrito acima.
      - -## O Manipulador de Erros Padrão - -O Express vem com um manipulador de erros integrado, que cuida -de qualquer erro que possa ser encontrado no aplicativo. Essa função -de middleware de manipulação de erros padrão é incluída no final da -pilha de funções de middleware. - - -se você passar um erro para o `next()` e você -não manipulá-lo com um manipulador de erros, ele irá ser manipulado -por um manipulador de erros integrado; o erro será escrito no cliente -com o rastreio de pilha. O rastreio de pilha não será incluído no -ambiente de produção. - - -
      -Configura a variável de ambiente `NODE_ENV` para -`production`, para executar o aplicativo em modo de -produção. -
      - -Se você chamar o `next()` com um erro após ter -inicializado escrevendo a resposta (por exemplo, se encontrar um erro -enquanto passa a resposta ao cliente) o manipulador de erros padrão do -Express fecha a conexão e falha a solicitação. - - -Portanto ao incluir um manipulador de erro customizado, você -desejará delegar para o mecanismo de manipulação de erros padrão no -Express, quando os cabeçalhos já tiverem sido enviados para o cliente: - - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/pt-br/guide/migrating-4.md b/pt-br/guide/migrating-4.md old mode 100755 new mode 100644 index 3ede5cbfa6..98160d7886 --- a/pt-br/guide/migrating-4.md +++ b/pt-br/guide/migrating-4.md @@ -1,10 +1,10 @@ --- layout: page title: Migrando para o 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. menu: guide lang: pt-br -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. +redirect_from: " " --- # Migrando para o Express 4 @@ -27,8 +27,7 @@ Este artigo cobre: Existem várias mudanças significativas no Express 4:
        -
      • Mudanças no núcleo e sistemas middleware do Express. As -dependências no Connect e middlewares integrados foram removidos, de forma que você mesmo deve incluir os middlewares. +
      • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
      • Mudanças no sistema de roteamento.
      • Várias outras mudanças.
      • @@ -36,8 +35,8 @@ dependências no Connect e middlewares integrados foram removidos, de forma que Consulte também: -* [Novos recursos no 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) -* [Migrando do 3.x para o 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) +- [Novos recursos no 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) +- [Migrando do 3.x para o 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)

        Mudanças no núcleo e sistemas middleware do Express @@ -59,7 +58,7 @@ Sem os middlewares integrados, você deve incluir explicitamente todos os middle A tabela a seguir lista os middlewares do Express 3 e suas contrapartes no Express 4. - + @@ -91,7 +90,7 @@ A tabela a seguir lista os middlewares do Express 3 e suas contrapartes no Expre -
        Express 3Express 4
        Express 3Express 4
        express.bodyParser body-parser + multer
        serve-index
        express.static serve-static
        + Aqui está a [lista completa](https://github.com/senchalabs/connect#middleware) de middlewares do Express 4. @@ -105,11 +104,12 @@ em seguida ler o valor do parâmetro a partir do manipulador de rota. Por exemplo: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

        O sistema de roteamento

        @@ -124,10 +124,11 @@ sistema de roteamento possui dois novos recursos para ajudá-lo a organizar suas rotas: {: .doclist } -* Um novo método, `app.route()`, para criar -manipuladores de rotas encadeáveis para um caminho de rota. -* Uma nova classe, `express.Router`, para -criar manipuladores de rotas modulares montáveis + +- Um novo método, `app.route()`, para criar + manipuladores de rotas encadeáveis para um caminho de rota. +- Uma nova classe, `express.Router`, para + criar manipuladores de rotas modulares montáveis

        O método app.route()

        @@ -141,13 +142,13 @@ são definidos usando a função `app.route()`. ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -173,16 +174,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -194,7 +195,7 @@ Em seguida, carregue o módulo roteador no aplicativo: ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -211,7 +212,7 @@ Outras mudanças A seguinte tabela lista outras pequenas, porém importantes, mudanças no Express 4: - + @@ -324,7 +325,7 @@ cookie. Use `res.cookie()` para funcionalidades adicionais. -
        Objeto Descrição
        +

        Exemplo de migração de aplicativo

        @@ -369,7 +370,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -410,17 +411,17 @@ $ npm install serve-favicon morgan method-override express-session body-parser m Faça as seguintes alterações no `app.js`: 1. As funções de middleware integradas do Express `express.favicon`, - `express.logger`, `express.methodOverride`, - `express.session`, `express.bodyParser` e - `express.errorHandler` não estão mais disponíveis no objeto `express`. É -preciso instalar manualmente as alternativas e carregá-las no aplicativo. + `express.logger`, `express.methodOverride`, + `express.session`, `express.bodyParser` e + `express.errorHandler` não estão mais disponíveis no objeto `express`. É + preciso instalar manualmente as alternativas e carregá-las no aplicativo. 2. Não é mais necessário carregar a função `app.router`. - Ela não é um objeto válido para aplicativos Express 4, portanto -remova o código do `app.use(app.router);`. + Ela não é um objeto válido para aplicativos Express 4, portanto + remova o código do `app.use(app.router);`. 3. Certifique-se deque as funções de middleware sejam carregadas na ordem correta - carregar a -`errorHandler` após carregar as rotas de aplicativo. + `errorHandler` após carregar as rotas de aplicativo.

        Aplicativo da Versão 4

        @@ -442,7 +443,7 @@ atualizar o `package.json` como a seguir: "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -511,7 +512,7 @@ carregá-lo não é necessário, e o aplicativo pode ser iniciado simplesmente desta forma: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -529,7 +530,7 @@ $ node . ``` Carregue [http://localhost:3000](http://localhost:3000) - e veja a página inicial sendo renderizada pelo Express 4. +e veja a página inicial sendo renderizada pelo Express 4.

        Fazendo o upgrade para o gerador de aplicativos do Express 4

        @@ -557,9 +558,8 @@ Agora instale o novo gerador: $ npm install -g express-generator ``` -Dependendo de como os seus privilégios de arquivos e diretórios -estão configurados, pode ser necessário executar este comando com -`sudo`. +Dependendo de como os seus privilégios de arquivos e diretórios estão +configurados, pode ser necessário executar este comando com `sudo`. Agora o comando `express` no seu sistema está atualizado para o gerador do Express 4. @@ -570,10 +570,11 @@ As opções e o uso do comando permanecem em grande parte as mesmas, com as seguintes exceções: {: .doclist } -* Foi removida a opção `--sessions`. -* Foi removida a opção `--jshtml`. -* Foi incluída a opção `--hogan` para -suportar o [Hogan.js](http://twitter.github.io/hogan.js/). + +- Foi removida a opção `--sessions`. +- Foi removida a opção `--jshtml`. +- Foi incluída a opção `--hogan` para + suportar o [Hogan.js](http://twitter.github.io/hogan.js/).

        Exemplo

        @@ -629,7 +630,7 @@ lugar: ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -647,7 +648,7 @@ app.js"`. Você agora moveu a funcionalidade do `./bin/www` de volta para o -`app.js`. Esta mudança não é recomendada, mas o +`app.js`. Esta mudança não é recomendada, mas o exercício ajuda você a entender como o arquivo `./bin/www` funciona, e porque o arquivo `app.js` não é mais iniciado por conta própria. diff --git a/pt-br/guide/migrating-5.md b/pt-br/guide/migrating-5.md old mode 100755 new mode 100644 index bed6392d87..c0b70303e7 --- a/pt-br/guide/migrating-5.md +++ b/pt-br/guide/migrating-5.md @@ -1,31 +1,26 @@ --- layout: page title: Migrando para o Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: pt-br -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # Migrando para o Express 5

        Visão Geral

        -O Express 5.0 ainda está no estágio de liberação alfa, mas aqui -está uma prévia das mudanças que estarão na liberação e como migrar -seu aplicativo do Express 4 app para o Express 5. - O Express 5 não é muito diferente do Express 4: As mudanças na -API não são tão significantes quanto as do 3.0 para o 4.0. Apesar de +API não são tão significantes quanto as do 3.0 para o 4.0. Apesar de a API básica permanecer a mesma, ainda existem mudanças disruptivas; em outras palavras um programa do Express 4 existente pode não funcionar se você atualizá-lo para usar o Express 5. -Para instalar o alfa mais recente e ter uma prévia do Express -5, digite o seguinte comando no diretório raiz do seu aplicativo: +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -```bash -$ npm install "express@5" --save +```sh +npm install "express@5" ``` É possível em seguida executar seus testes automatizados para @@ -35,14 +30,25 @@ seu aplicativo para verificar quais erros ocorrem. Você descobrirá imediatamente se o aplicativo utiliza quaisquer métodos ou propriedades que não são suportados. -

        Mudanças no Express 5

        +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: + +```sh +npx @expressjs/codemod upgrade +``` + +If you want to run a specific codemod, you can run the following command: + +```sh +npx @expressjs/codemod name-of-the-codemod +``` -Aqui está a lista de mudanças (até a liberação alpha 2) que -irão afetá-lo como um usuário do Express. -Consulte por -[solicitação -de pull](https://github.com/expressjs/express/pull/2237) para obter uma lista de todas funcionalidades -planejadas. +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

        Mudanças no Express 5

        **Métodos e propriedades removidas** @@ -54,26 +60,40 @@ planejadas.
      • req.param(name)
      • res.json(obj, status)
      • res.jsonp(obj, status)
      • +
      • res.redirect('back') and res.location('back')
      • +
      • res.redirect(url, status)
      • res.send(body, status)
      • res.send(status)
      • res.sendfile()
      • +
      • router.param(fn)
      • +
      • express.static.mime
      • +
      • express:router debug logs
      -**Mudadas** +**Melhorias** -**Melhorias** +**Mudadas** -

      Métodos e propriedades removidas

      +### Métodos e propriedades removidas Se estiver usando qualquer um desses métodos ou propriedades no seu aplicativo, ele irá quebrar. Portanto, será necessário alterar @@ -88,8 +108,30 @@ Inicialmente `del` era usada ao invés de `delete`, porque `delete` é uma palavra-chave reservada no JavaScript. Entretanto, a partir do ECMAScript 6, `delete` e outras palavras-chave reservadas podem -legalmente ser usadas como nomes de propriedades. É possível ler a -discussão que levou à descontinuação da função `app.del` aqui. +legalmente ser usadas como nomes de propriedades. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

      app.param(fn)

      @@ -101,13 +143,44 @@ foi descontinuada desde a v4.11.0, e o Express 5 não a suporta mais de nenhuma Os seguintes nomes de métodos podem ser pluralizados. No Express 4, o uso dos métodos antigos resultava em um aviso de -descontinuação. O Express 5 não os suporta mais de forma nenhuma: +descontinuação. O Express 5 não os suporta mais de forma nenhuma: Express 5 no longer supports them at all: + +`req.acceptsLanguage()` é substituído por `req.acceptsLanguages()`. `req.acceptsCharset()` é substituído por `req.acceptsCharsets()`. `req.acceptsEncoding()` é substituído por `req.acceptsEncodings()`. -`req.acceptsLanguage()` é substituído por `req.acceptsLanguages()`. +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

      Dois pontos no começo (:) do nome do app.param(name, fn)

      @@ -127,25 +200,143 @@ menciona os dois pontos no início. Este é um método potencialmente confuso e perigoso de recuperação de dados de formulário foi removido. Você precisará agora especificamente olhar para o nome do parâmetro enviado no objeto `req.params`, `req.body`, ou `req.query`. +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +``` +

      res.json(obj, status)

      O Express 5 não suporta mais a assinatura `res.json(obj, status)`. Ao invés disso, configure o status e então encadeie-o ao método `res.json()` assim: `res.status(status).json(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +``` +

      res.jsonp(obj, status)

      O Express 5 não suporta mais a assinatura `res.jsonp(obj, status)`. Ao invés disso, configure o status e então encadeie-o ao método `res.jsonp()` assim: `res.status(status).jsonp(obj)`. -

      res.send(body, status)

      +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

      res.redirect(url, status)

      O Express 5 não suporta mais a assinatura `res.send(obj, status)`. Ao invés disso, configure o status e então encadeie-o ao método `res.send()` assim: `res.status(status).send(obj)`. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

      res.redirect('back') and res.location('back')

      + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +``` + +

      res.send(body, status)

      + +Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +``` +

      res.send(status)

      -O Express 5 não suporta mais a assinatura res.send(status), onde *`status`* +O Express 5 não suporta mais a assinatura res.send(status), onde _`status`_ é um número. Ao invés disso, use a função `res.sendStatus(statusCode)`, que configura o código do status do cabeçalho de resposta HTTP e envia a versão de texto do @@ -157,14 +348,168 @@ converte-lo para um sequência de caracteres, para que o Express não o interprete como uma tentativa de usar a assinatura antiga não suportada. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +``` +

      res.sendfile()

      A função `res.sendfile()` foi substituída pela versão em formato camel-case `res.sendFile()` no Express 5. +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

      router.param(fn)

      + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. Ela +foi descontinuada desde a v4.11.0, e o Express 5 não a suporta mais de nenhuma forma. + +

      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. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

      express:router debug logs

      + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

      Mudadas

      +

      Path route matching syntax

      + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. Por exemplo: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

      Rejected promises handled from middleware and handlers

      + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

      express.urlencoded

      + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

      app.listen

      + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +Por exemplo: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

      app.router

      O objeto `app.router`, que foi removido no @@ -172,6 +517,10 @@ Express 4, está de volta no Express 5. Na nove versão, este objeto é apenas uma referência para o roteador Express base, diferentemente do Express 3, onde um aplicativo tinha que carregá-lo explicitamente. +

      req.body

      + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. +

      req.host

      No Express 4, a função `req.host` @@ -180,13 +529,21 @@ Express 5 o número da porta é mantido.

      req.query

      -No Express 4.7 e do Express 5 para frente, o analisador -sintático de consulta pode aceitar `false` para -desativar a análise sintática de sequência de consulta quando desejar -usar sua própria função para a lógica de análise sintática de -sequência de consultas. +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". -

      Melhorias

      +

      res.clearCookie

      + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

      res.status

      + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

      res.vary

      + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### Melhorias

      res.render()

      @@ -194,3 +551,7 @@ Este método agora impinge comportamento assíncrono para todos os mecanismos de visualização, evitando erros causados pelos mecanismos de visualização que tinham uma implementação síncrona e que violavam a interface recomendada. + +

      Brotli encoding support

      + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/pt-br/guide/overriding-express-api.md b/pt-br/guide/overriding-express-api.md new file mode 100644 index 0000000000..f1bfc5eccb --- /dev/null +++ b/pt-br/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: pt-br +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/pt-br/guide/routing.md b/pt-br/guide/routing.md old mode 100755 new mode 100644 index 59631a6645..59eaffac72 --- a/pt-br/guide/routing.md +++ b/pt-br/guide/routing.md @@ -1,10 +1,10 @@ --- layout: page title: Roteamento no Express +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: pt-br -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # Roteamento @@ -13,18 +13,16 @@ O _Roteamento_ refere-se a como os _endpoints_ de uma aplicação (URIs) respond Para uma introdução ao roteamento, consulte [Roteamento básico](/{{ page.lang }}/starter/basic-routing.html). Rotas são definidas utilizando métodos do objeto `app` do Express que correspondem aos métodos HTTP; -por exemplo, `app.get()` para lidar com requisições GET e `app.post()` para requisições POST. -Para a lista completa, veja [app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD). -Você também pode utilizar [app.all()](/{{ page.lang }}/4x/api.html#app.all) para lidar com todos os métodos HTTP -e [app.use()](/{{ page.lang }}/4x/api.html#app.use) para especificar middleware como funções _callback_ +por exemplo, `app.get()` para lidar com requisições GET e `app.post()` para requisições POST. Para a lista completa, veja [app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD). Você também pode utilizar [app.all()](/{{ page.lang }}/4x/api.html#app.all) para lidar com todos os métodos HTTP +e [app.use()](/{{ page.lang }}/4x/api.html#app.use) para especificar middleware como funções _callback_ (Veja [Usando middlewares](/{{ page.lang }}/guide/using-middleware.html) para mais detalhes). -Esses métodos de roteamento especificam uma função _callback_ a ser chamada quando a aplicação -recebe uma requisição à rota e método HTTP especificados. Em outras palavras, a aplicação "escuta" -requisições que se encaixam nas rotas e métodos especificados e, quando há alguma correspondência, +Esses métodos de roteamento especificam uma função _callback_ a ser chamada quando a aplicação +recebe uma requisição à rota e método HTTP especificados. Em outras palavras, a aplicação "escuta" +requisições que se encaixam nas rotas e métodos especificados e, quando há alguma correspondência, chama a função _callback_ especificada. -Na realidade, métodos de roteamento podem possuir mais de uma função _callback_ como argumento. +Na realidade, métodos de roteamento podem possuir mais de uma função _callback_ como argumento. Com múltiplas funções, é importante passar `next` como argumento da função e chamar `next()` para passar o controle para a próxima. O código a seguir é um exemplo de uma rota muito básica. @@ -33,7 +31,7 @@ O código a seguir é um exemplo de uma rota muito básica. const express = require('express') const app = express() -// Responde com 'hello world' quando uma requisição é feita à homepage +// respond with "hello world" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('hello world') }) @@ -49,14 +47,14 @@ aplicativo que estão definidas para os métodos GET e POST. ```js -// rota do método GET +// GET method route app.get('/', (req, res) => { - res.send('requisição GET à homepage') + res.send('GET request to the homepage') }) -// rota do método POST +// POST method route app.post('/', (req, res) => { - res.send('requisição POST à homepage') + res.send('POST request to the homepage') }) ``` @@ -66,18 +64,12 @@ Pra uma lista completa, veja [app.METHOD](/{{ page.lang }}/4x/api.html#app.METHO Existe um método de roteamento especial, `app.all()`, que não é derivado de nenhum método HTTP. Este método é usado para carregar funções de middleware em um -caminho para todos os métodos de solicitação. - -No exemplo a seguir, o manipulador irá ser executado para -solicitações para "/secret" se você estiver usando GET, POST, PUT, -DELETE, ou qualquer outro método de solicitação HTTP que é suportado -no [módulo -http](https://nodejs.org/api/http.html#http_http_methods). +caminho para todos os métodos de solicitação. 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('/secreto', (req, res, next) => { - console.log('Acessando a área secreta ...') - next() // passa o controle pro próximo manipulador +app.all('/secret', (req, res, next) => { + console.log('Accessing the secret section ...') + next() // pass control to the next handler }) ``` @@ -88,45 +80,65 @@ definem os terminais em que as solicitações podem ser feitas. Caminhos de rota podem ser sequências de caracteres, padrões de sequência, ou expressões regulares. -
      - O Express usa o [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) para verificar a correspondência de caminhos de rota; consulte a -documentação do path-to-regexp para obter todas as possibilidades nas definições de caminhos de rota. O [Express -Route Tester](http://forbeslindesay.github.io/express-route-tester/) é uma ferramenta útil para testar rotas básicas do Express, apesar de não suportar a correspondência de padrões. -
      +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
      -Sequências de consulta não fazem parte dos caminhos de rota. -
      +{% include admonitions/caution.html content=caution-character %} -Aqui estão alguns exemplos de caminhos de rota baseados em sequências de caracteres +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} -Este caminho de rota corresponde a solicitações à rota raiz, `/`. +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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. O Express +Route Tester é uma ferramenta útil para testar rotas básicas do Express, apesar de não suportar a correspondência de padrões. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. + +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Aqui estão alguns exemplos de caminhos de rota baseados em sequências de caracteres + +Este caminho de rota irá corresponder a solicitações ao `/qualquer.texto`. ```js app.get('/', (req, res) => { - res.send('raiz') + res.send('root') }) ``` Este caminho de rota irá corresponder a solicitações ao `/ajuda`. ```js -app.get('/ajuda', (req, res) => { - res.send('ajuda') +app.get('/about', (req, res) => { + res.send('about') }) ``` -Este caminho de rota irá corresponder a solicitações ao `/qualquer.texto`. +Este caminho de rota corresponde a solicitações à rota raiz, `/`. ```js -app.get('/qualquer.texto', (req, res) => { - res.send('qualquer.texto') +app.get('/random.text', (req, res) => { + res.send('random.text') }) ``` -Aqui estão alguns exemplos de caminhos de rota baseados em padrões de sequência +### Aqui estão alguns exemplos de caminhos de rota baseados em padrões de sequência -Este caminho de rota irá corresponder ao `acd` e `abcd`. +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} + +Este caminho de rota irá corresponder ao `/abe` e `/abcde`. ```js app.get('/ab?cd', (req, res) => { @@ -150,7 +162,7 @@ app.get('/ab*cd', (req, res) => { }) ``` -Este caminho de rota irá corresponder ao `/abe` e `/abcde`. +Este caminho de rota irá corresponder ao `acd` e `abcd`. ```js app.get('/ab(cd)?e', (req, res) => { @@ -158,13 +170,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
      -Os caracteres ?, +, *, e () são subconjuntos de suas contrapartes em -expressões regulares. O hífen (-) e o ponto (.) são interpretados -literalmente por caminhos baseados em sequências de caracteres. -
      - -Exemplos de caminhos de rota baseados em expressões regulares: +### Exemplos de caminhos de rota baseados em expressões regulares: Este caminho de rota irá corresponder a qualquer coisa com um "a" no nome. @@ -185,6 +191,73 @@ app.get(/.*fly$/, (req, res) => { }) ``` +

      +Sequências de consulta não fazem parte dos caminhos de rota. +

      + +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. + +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
      +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} +

      Manipuladores de rota

      É possível fornecer várias funções _callback_ @@ -199,11 +272,11 @@ Manipuladores de rota podem estar na forma de uma função, uma matriz de funções, ou combinações de ambas, como mostrado nos seguintes exemplos. -Uma única função _callback_ pode manipular uma rota. Por exemplo: +Uma única função _callback_ pode manipular uma rota. Por exemplo: ```js -app.get('/exemplo/a', (req, res) => { - res.send('A diz olá!') +app.get('/example/a', (req, res) => { + res.send('Hello from A!') }) ``` @@ -211,49 +284,54 @@ Mais de uma função _callback_ pode manipular uma rota (certifique-se de especificar o objeto `next`). Por exemplo: ```js -app.get('/exemplo/b', (req, res, next) => { - console.log('a resposta será enviada para a próxima função ...') +app.get('/example/b', (req, res, next) => { + console.log('the response will be sent by the next function ...') next() }, (req, res) => { - res.send('B diz olá!') + res.send('Hello from B!') }) ``` Uma matriz de funções _callback_ podem manipular uma -rota. Por exemplo: +rota. Por exemplo: ```js const cb0 = function (req, res, next) { console.log('CB0') next() } + const cb1 = function (req, res, next) { console.log('CB1') next() } + const cb2 = function (req, res) { - res.send('C diz olá!') + res.send('Hello from C!') } -app.get('/exemplo/c', [cb0, cb1, cb2]) + +app.get('/example/c', [cb0, cb1, cb2]) ``` Uma combinação de funções independentes e matrizes de funções -podem manipular uma rota. Por exemplo: +podem manipular uma rota. Por exemplo: ```js const cb0 = function (req, res, next) { console.log('CB0') next() } + const cb1 = function (req, res, next) { console.log('CB1') next() } + app.get('/example/d', [cb0, cb1], (req, res, next) => { - console.log('a resposta será enviada pela próxima função ...') + console.log('the response will be sent by the next function ...') next() }, (req, res) => { - res.send('D diz olá!') + res.send('Hello from D!') }) ``` @@ -265,17 +343,17 @@ ciclo solicitação-resposta. Se nenhum destes métodos forem chamados a partir de um manipulador de rota, a solicitação do cliente será deixada em suspenso. -| Método | Descrição -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Solicita que seja efetuado o download de um arquivo -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Termina o processo de resposta. -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envia uma resposta JSON. -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Envia uma resposta JSON com suporta ao JSONP. -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redireciona uma solicitação. -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Renderiza um modelo de visualização. -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envia uma resposta de vários tipos. -| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Envia um arquivo como um fluxo de octeto. -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Configura o código do status de resposta e envia a sua representação em sequência de caracteres como o corpo de resposta. +| Método | Descrição | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | Solicita que seja efetuado o download de um arquivo | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | Termina o processo de resposta. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | Envia uma resposta JSON. | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | Envia uma resposta JSON com suporta ao JSONP. | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | Redireciona uma solicitação. | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Renderiza um modelo de visualização. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | Envia uma resposta de vários tipos. | +| [res.sendFile](/{{ page.lang }}/4x/api.html#res.sendFile) | Envia um arquivo como um fluxo de octeto. | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Configura o código do status de resposta e envia a sua representação em sequência de caracteres como o corpo de resposta. |

      app.route()

      @@ -285,15 +363,15 @@ Como o caminho é especificado em uma localização única, criar rotas modulare Aqui está um exemplo de manipuladores de rotas encadeáveis que são definidos usando `app.route()`. ```js -app.route('/livro') +app.route('/book') .get((req, res) => { - res.send('Retorna um livro aleatório') + res.send('Get a random book') }) .post((req, res) => { - res.send('Adiciona um livro') + res.send('Add a book') }) .put((req, res) => { - res.send('Atualiza o livro') + res.send('Update the book') }) ``` @@ -316,31 +394,43 @@ seguinte conteúdo: ```js const express = require('express') const router = express.Router() -// middleware específico para este roteador -router.use((req, res, next) => { - console.log('Horário: ', Date.now()) + +// middleware that is specific to this router +const timeLog = (req, res, next) => { + console.log('Time: ', Date.now()) next() -}) -// define a rota da homepage +} +router.use(timeLog) + +// define the home page route router.get('/', (req, res) => { - res.send('Homepage de pássaros') + res.send('Birds home page') }) -// define a rota 'ajuda' -router.get('/ajuda', (req, res) => { - res.send('Ajuda sobre pássaros') +// define the about route +router.get('/about', (req, res) => { + res.send('About birds') }) + module.exports = router ``` Em seguida, carregue o módulo roteador no aplicativo: ```js -const passaros = require('./passaros') +const birds = require('./birds') + // ... -app.use('/passaros', passaros) + +app.use('/birds', birds) ``` O aplicativo será agora capaz de manipular solicitações aos caminhos `/passaros` e `/passaros/ajuda`, assim como chamar a função de middleware `timeLog` que é específica para a rota. + +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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/pt-br/guide/using-middleware.md b/pt-br/guide/using-middleware.md old mode 100755 new mode 100644 index 0eabac0e3c..a9ac056b38 --- a/pt-br/guide/using-middleware.md +++ b/pt-br/guide/using-middleware.md @@ -1,10 +1,10 @@ --- layout: page title: Usando middlewares do Express +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: pt-br -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # Usando middlewares @@ -13,7 +13,7 @@ O Express é uma estrutura web de roteamento e middlewares que tem uma funcionalidade mínima por si só: Um aplicativo do Express é essencialmente uma série de chamadas de funções de middleware. -Funções de *Middleware* são funções que tem acesso +Funções de _Middleware_ são funções que tem acesso ao [objeto de solicitação](/{{ page.lang }}/4x/api.html#req) (`req`), o [objeto de resposta](/{{ page.lang }}/4x/api.html#res) (`res`), e a próxima função de middleware no ciclo @@ -22,10 +22,10 @@ comumente denotada por uma variável chamada `next`. Funções de middleware podem executar as seguintes tarefas: -* Executar qualquer código. -* Fazer mudanças nos objetos de solicitação e resposta. -* Encerrar o ciclo de solicitação-resposta. -* Chamar a próxima função de middleware na pilha. +- Executar qualquer código. +- Fazer mudanças nos objetos de solicitação e resposta. +- Encerrar o ciclo de solicitação-resposta. +- Chamar a próxima função de middleware na pilha. Se a atual função de middleware não terminar o ciclo de solicitação-resposta, ela precisa chamar `next()` @@ -34,11 +34,11 @@ contrário, a solicitação ficará suspensa. Um aplicativo Express pode usar os seguintes tipos de middleware: - - [Middleware de nível do aplicativo](#middleware.application) - - [Middleware de nível de roteador](#middleware.router) - - [Middleware de manipulação de erros](#middleware.error-handling) - - [Middleware integrado](#middleware.built-in) - - [Middleware de Terceiros](#middleware.third-party) +- [Middleware de nível do aplicativo](#middleware.application) +- [Middleware de nível de roteador](#middleware.router) +- [Middleware de manipulação de erros](#middleware.error-handling) +- [Middleware integrado](#middleware.built-in) +- [Middleware de Terceiros](#middleware.third-party) É possível carregar middlewares de nível de roteador e de nível do aplicativo com um caminho de montagem opcional. É possível também carregar uma série de funções de middleware juntas, o que cria uma sub-pilha do sistema de middleware em um ponto de montagem. @@ -56,6 +56,7 @@ montagem. A função é executada sempre que o aplicativo receber uma solicitação. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -120,16 +121,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` -Para pular o restante das funções de middleware de uma pilha de -middlewares do roteador, chame `next('route')` -para passar o controle para a próxima rota. -**NOTA**: O `next('route')` irá -funcionar apenas em funções de middleware que são carregadas usando -as funções `app.METHOD()` ou `router.METHOD()`. +`redirect` + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} Este exemplo mostra uma sub-pilha de middleware que manipula solicitações GET no caminho `/user/:id`. @@ -139,15 +143,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +É possível ter mais do que um diretório estático por aplicativo: + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -160,6 +185,7 @@ instância do `express.Router()`. ```js const router = express.Router() ``` + Carregue os middlewares de nível de roteador usando as funções `router.use()` e `router.METHOD()`. O seguinte código de exemplo replica o sistema de middleware @@ -167,6 +193,7 @@ que é mostrado acima para o middleware de nível do aplicativo, usando um middleware de nível de roteador: ```js +const express = require('express') const app = express() const router = express.Router() @@ -190,7 +217,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -205,10 +232,37 @@ router.get('/user/:id', (req, res, next) => { // mount the router on the app app.use('/', router) ``` + +Para obter mais detalhes sobre a função `serve-static` e suas opções, consulte: documentação do[serve-static](https://github.com/expressjs/serve-static). + +Este exemplo mostra uma sub-pilha de middleware que manipula +solicitações GET no caminho `/user/:id`. + +```js +const express = require('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) +}) +``` +

      Middleware de manipulação de erros

      -Middlewares de manipulação de erros sempre levam *quatro* argumentos. Você deve fornecer quatro argumentos para identificá-lo como uma +Middlewares de manipulação de erros sempre levam *quatro* argumentos. Você deve fornecer quatro argumentos para identificá-lo como uma função de middleware de manipulação de erros. Mesmo se você não precisar usar o objeto `next`, você deve especificá-lo para manter a assinatura. Caso contrário, o objeto @@ -236,61 +290,14 @@ consulte [Manipulação de erros](/{{ page.lang }}/guide/error-handling.html). Desde a versão 4.x, o Express não depende mais do [Connect](https://github.com/senchalabs/connect). Com exceção da `express.static`, todas as funções de middleware que eram previamente incluídas com o Express estão agora -em módulos separados. Visualize [a lista -de funções de middleware](https://github.com/senchalabs/connect#middleware). - -

      express.static(root, [options])

      - -A única função de middleware integrada no Express é a -`express.static`. Esta função é baseada no -[serve-static](https://github.com/expressjs/serve-static), -e é responsável por entregar os ativos estáticos de um aplicativo do -Express. - -O argumento `root` especifica o diretório raiz -a partir do qual entregar os ativos estáticos. - -O objeto opcional `options` pode ter as -seguintes propriedades: - -| Propriedade | Descrição | Tipo | Padrão | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Opção para entregar dotfiles. Os valores possíveis são "allow", "deny", e "ignore" | Sequência de caracteres | "ignore" | -| `etag` | Ativa ou desativa a geração de etag | Booleano | `true` | -| `extensions` | Configura os fallbacks de extensão de arquivo | Matriz | `[]` | -| `index` | Envia o arquivo de índice do diretório. Configure `false` para desativar a indexação de diretórios. | Variado | "index.html" | - `lastModified` | Configura o cabeçalho `Last-Modified` para a última data de modificação do arquivo no sistema operacional. Os valores possíveis são `true` ou `false`. | Booleano | `true` | -| `maxAge` | Configura a propriedade max-age do cabeçalho Cache-Control, em milissegundos ou uma sequência de caracteres no [formato ms](https://www.npmjs.org/package/ms) | Número | 0 | -| `redirect` | Redireciona para o "/" final quando o caminho do arquivo é um diretório. | Booleano | `true` | -| `setHeaders` | Função para configurar cabeçalhos HTTP para entregar com o arquivo. | Função | | +em módulos separados. Visualize a lista +de funções de middleware. Aqui está um exemplo de uso da função de middleware `express.static` com um objeto options elaborado: -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -É possível ter mais do que um diretório estático por aplicativo: - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` - -Para obter mais detalhes sobre a função `serve-static` e suas opções, consulte: documentação do[serve-static](https://github.com/expressjs/serve-static). +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**

      Middleware de Terceiros

      diff --git a/pt-br/guide/using-template-engines.md b/pt-br/guide/using-template-engines.md old mode 100755 new mode 100644 index 2838920497..f328bff5f9 --- a/pt-br/guide/using-template-engines.md +++ b/pt-br/guide/using-template-engines.md @@ -1,22 +1,28 @@ --- layout: page title: Usando mecanismos de modelo com o Express +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: pt-br -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- # Usando mecanismos de modelo com o Express -Antes do Express poder renderizar arquivos de modelo, as -seguintes configurações do aplicativo devem ser configuradas: +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. -* `views`, é o diretório onde os arquivos de -modelo estão localizados. Por exemplo: `app.set('views', -'./views')` -* `view engine`, o mecanismo de modelo a ser -usado. Por Exemplo: `app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, é o diretório onde os arquivos de + modelo estão localizados. Por exemplo: `app.set('views', + './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, o mecanismo de modelo a ser + usado. Por Exemplo: `app.set('view engine', 'pug')` Em seguida instale o pacote npm correspondente ao mecanismo de modelo: @@ -34,6 +40,7 @@ Alguns mecanismos de modelo não seguem esta convenção. A biblioteca [Consolidate.js](https://www.npmjs.org/package/consolidate) segue esta convenção mapeando todos os mecanismos de modelo populares do Node.js, e portanto funciona de forma harmoniosa com o Express. +
      Após o mecanismo de visualização estar configurado, você não @@ -71,5 +78,4 @@ app.get('/', (req, res) => { Ao fazer uma solicitação à página inicial, o arquivo `index.pug` será renderizado como HTML. -Para aprender mais sobre como mecanismos de modelo funcionam no -Express, consulte: ["Desenvolvendo mecanismos de para o Express"](/{{ page.lang }}/advanced/developing-template-engines.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/pt-br/guide/writing-middleware.md b/pt-br/guide/writing-middleware.md old mode 100755 new mode 100644 index b34126d161..eb5d781ed0 --- a/pt-br/guide/writing-middleware.md +++ b/pt-br/guide/writing-middleware.md @@ -1,17 +1,17 @@ --- layout: page title: Escrevendo middlewares para uso em aplicativos do Express +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: pt-br -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- -# Escrevendo middlewares pra uso em aplicativos do Express +# Escrevendo middlewares para uso em aplicativos do Express

      Visão Geral

      -Funções de *Middleware* são funções que tem acesso +Funções de _Middleware_ são funções que tem acesso ao [objeto de solicitação](/{{ page.lang }}/4x/api.html#req) (`req`), o [objeto de resposta](/{{ page.lang }}/4x/api.html#res) (`res`), e a próxima função de middleware no ciclo @@ -20,10 +20,10 @@ comumente denotada por uma variável chamada `next`. Funções de middleware podem executar as seguintes tarefas: -* Executar qualquer código. -* Fazer mudanças nos objetos de solicitação e resposta. -* Encerrar o ciclo de solicitação-resposta. -* Chamar o próximo middleware na pilha. +- Executar qualquer código. +- Fazer mudanças nos objetos de solicitação e resposta. +- Encerrar o ciclo de solicitação-resposta. +- Chamar o próximo middleware na pilha. Se a atual função de middleware não terminar o ciclo de solicitação-resposta, ela precisa chamar `next()` @@ -32,12 +32,12 @@ contrário, a solicitação ficará suspensa. O exemplo a seguir mostra os elementos de uma chamada de função de middleware: - -
      + +
      Caminho (rota) para o qual a função de middleware é aplicada.
      @@ -51,8 +51,15 @@ O exemplo a seguir mostra os elementos de uma chamada de função de middleware:
      Elements of a middleware function call -
      O método HTTP para o qual a função de middleware é aplicada.
      +
      O método HTTP para o qual a função de middleware é aplicada.
      +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. + +

      Exemplo

      + Aqui está um exemplo de um simples aplicativo "Hello World" do Express, para o qual serão definidas duas funções de middleware: +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 const express = require('express') @@ -65,8 +72,7 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

      Desenvolvimento

      - +

      Middleware function myLogger

      Aqui está um exemplo simples de uma função de middleware chamada "myLogger". Esta função apenas imprime "LOGGED" quando uma solicitação para o aplicativo passa por ela. A função de middleware é designada para uma variável chamada `myLogger`. @@ -79,12 +85,13 @@ const myLogger = function (req, res, next) { ```
      -Observe a chamada acima para `next()`. A chamada +Observe a chamada acima para `next()`. A chamada desta função chama a próxima função de middleware no aplicativo. A função `next()` não faz parte do Node.js ou da API Express, mas é o terceiro argumento que é passado para a função de middleware. A função `next()` poderia ter -qualquer nome, mas por convenção ela é sempre chamada de "next". Para +qualquer nome, mas por convenção ela é sempre chamada de "next". +Para evitar confusão, sempre use esta convenção.
      @@ -113,7 +120,6 @@ Sempre que o aplicativo recebe uma chamada, ele imprime a mensagem "LOGGED" no t A ordem de carregamento do middleware é importante: funções de middleware que são carregadas primeiro também são executadas primeiro. - Se `myLogger` é carregada após a rota para o caminho raiz, a chamada nunca chegará a ela e o aplicativo não imprimirá "LOGGED", pois o manipulador de rota do caminho raiz @@ -122,6 +128,8 @@ encerra o ciclo de solicitação-resposta. A função de middleware `myLogger` simplesmente imprime uma mensagem, e em seguida passa a solicitação para a próxima função de middleware na pilha chamando a função `next()`. +

      Middleware function requestTime

      + O próximo exemplo inclui uma propriedade chamada `requestTime` ao objeto da solicitação. Iremos chamar esta função de middleware de "requestTime". @@ -157,10 +165,57 @@ app.get('/', (req, res) => { app.listen(3000) ``` + Ao fazer uma solicitação para a raiz do aplicativo, o aplicativo agora exibe o registro de data e hora da sua solicitação no navegador. +

      Middleware function validateCookies

      + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
      + Como você tem acesso ao objeto da solicitação, ao objeto de resposta, à próxima função de middleware na pilha, e à API completa do Node.js, as possibilidades com as funções de middleware são ilimitadas. @@ -168,3 +223,28 @@ Node.js, as possibilidades com as funções de middleware são ilimitadas. Para obter mais informações sobre middlewares no Express, consulte: [Usando middlewares no Express](/{{ page.lang }}/guide/using-middleware.html). + +

      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 +module.exports = 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') + +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. diff --git a/pt-br/resources/community.md b/pt-br/resources/community.md old mode 100755 new mode 100644 index a7edb67c7e..58b6a5de5a --- a/pt-br/resources/community.md +++ b/pt-br/resources/community.md @@ -1,10 +1,10 @@ --- layout: page title: Comunidade do Express +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: pt-br -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # Comunidade @@ -60,3 +60,33 @@ uma solicitação de recurso abre um ticket no [issue queue](https://github.com/ Veja dezenas de aplicativos Express [exemplos](https://github.com/expressjs/express/tree/master/examples) no repositório temos de tudo, desde design de API e autenticação até integração de mecanismo de template. + +## 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. + +# Branding of Express.js + +## 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. + +
      +
      +

      Logotype

      + Express.js logo + + + Express.js logo + +
      +
      +

      Logomark

      + Express.js mark + + + Express.js mark + +
      +
      +
      \ No newline at end of file diff --git a/pt-br/resources/contributing.md b/pt-br/resources/contributing.md new file mode 100644 index 0000000000..268a9e6523 --- /dev/null +++ b/pt-br/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: pt-br +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Comitê técnico + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/pt-br/resources/glossary.md b/pt-br/resources/glossary.md old mode 100755 new mode 100644 index 4a4bca818b..7efa3dcee4 --- a/pt-br/resources/glossary.md +++ b/pt-br/resources/glossary.md @@ -1,16 +1,14 @@ --- layout: page title: Glossário do Express +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. menu: resources lang: pt-br -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. +redirect_from: " " --- # Glossário -
      Este é atualmente um rascunho de trabalho
      - ### aplicativo Em geral, um ou mais programas que são designados a executar @@ -20,11 +18,11 @@ também se referir a um [objeto app](/{{ page.lang }}/api.html#express). ### API -Interface de programação de aplicativos. Especifique o significado da abreviação no seu primeiro uso. +Interface de programação de aplicativos. Especifique o significado da abreviação no seu primeiro uso. ### Express -Uma estrutura web rápida, flexível e minimalista para aplicativos Node.js. Em +Uma estrutura web rápida, flexível e minimalista para aplicativos Node.js. Em geral, "Express" é preferido a "Express.js," apesar de que o último ser aceitável. ### libuv @@ -36,34 +34,48 @@ assíncrona, primeiramente desenvolvida para uso pelo Node.js. Uma função que é chamada pela camada de roteamento do Express antes do manipulador final da solicitação, e assim ficando no meio, -entre uma solicitação bruta a rota final desejada. Alguns poucos +entre uma solicitação bruta a rota final desejada. Alguns poucos pontos de refinamento da terminologia envolvendo middleware: - * `var foo = require('middleware')` é -chamado *requerendo* ou *usando* um módulo -do Node.js. Então a instrução `var mw = foo()` -tipicamente retorna o middleware. - * `app.use(mw)` é chamado *incluindo -o middleware na pilha global de processamento*. - * `app.get('/foo', mw, function (req, res) { ... })` -é chamado *incluindo o middleware para a pilha de -processamento do "GET /foo" *. +- `var foo = require('middleware')` é + chamado _requerendo_ ou _usando_ um módulo + do Node.js. Então a instrução `var mw = foo()` + tipicamente retorna o middleware. +- `app.use(mw)` é chamado _incluindo + o middleware na pilha global de processamento_. +- `app.get('/foo', mw, function (req, res) { ... })` + é chamado \*incluindo o middleware para a pilha de + processamento do "GET /foo" \*. ### Node.js Uma plataforma de software que é usada para construir aplicativos de rede escaláveis. O Node.js usa o JavaScript como linguagem de script, e alcança rendimentos altos através de E/S não -bloqueante e um loop de eventos de thread única. Consulte [nodejs.org](http://nodejs.org/). **Nota +bloqueante e um loop de eventos de thread única. Consulte [nodejs.org](http://nodejs.org/). **Nota de uso**: Inicialmente, "Node.js," posteriormente "Node". ### open-source, open source Quando usado como adjetivo, colocar o hífen; por exemplo "Este é um software open-source". Consulte -[Software -Open-source na Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Nota: Apesar de ser comum não -colocar o hífen neste termo, estamos usando as regras padrões do -Inglês para colocar o hífen em adjetivos compostos. +Software +Open-source na Wikipedia. + +{% capture english-rules %} + +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. + +{% endcapture %} + +{% include admonitions/note.html content=english-rules %} + +### solicitação + +Uma solicitação HTTP. Um cliente envia uma mensagem HTTP para +um servidor, que retorna uma resposta. A solicitação deve usar um dos +vários +métodos +de solicitação como GET, POST, e assim por diante. ### resposta @@ -74,18 +86,10 @@ solicitação no corpo da mensagem. ### rota -Parte de uma URL que identifica um recurso. Por exemplo, em +Parte de uma URL que identifica um recurso. Por exemplo, em `http://foo.com/products/id`, "/products/id" é a rota. ### roteador Consulte [roteador](/{{ page.lang }}/4x/api.html#router) na referência da API. - -### solicitação - -Uma solicitação HTTP. Um cliente envia uma mensagem HTTP para -um servidor, que retorna uma resposta. A solicitação deve usar um dos -vários -[métodos -de solicitação](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) como GET, POST, e assim por diante. diff --git a/pt-br/resources/middleware.md b/pt-br/resources/middleware.md old mode 100755 new mode 100644 index d8b0236d6c..8206149706 --- a/pt-br/resources/middleware.md +++ b/pt-br/resources/middleware.md @@ -1,76 +1,44 @@ --- -layout: page +layout: middleware title: Middleware do Express +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. menu: resources lang: pt-br -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. +redirect_from: " " +module: mw-home --- -# Middleware de Terceiros +## Middleware do Express Aqui estão alguns módulos middleware do Express: - - - [body-parser](https://github.com/expressjs/body-parser): anteriormente `express.bodyParser`, `json`, e `urlencoded`. - Consulte também: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression): anteriormente `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus): Módulos de middleware do Connect/Express para entrega otimizada de imagens. Alterna imagens para `.webp` ou `.jxr`, se possível. - - [connect-timeout](https://github.com/expressjs/timeout): anteriormente `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser): anteriormente `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session): anteriormente `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler): anteriormente `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug): ferramenta não obstrutiva de desenvolvimento que inclui uma guia com informações sobre variáveis de modelo (locais), sessão corrente, dados de solicitação úteis e mais para o seu aplicativo. - - [express-partial-response](https://github.com/nemtsov/express-partial-response): módulo de middleware do Express para filtrar partes das respostas JSON baseado nos `fields` da sequência de consultas; usando a Resposta parcial da API do Google. - - - [express-session](https://github.com/expressjs/session): anteriormente `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn): Módulo middleware do Express para usar um CDN para ativos estáticos, com suporte a múltiplos hosts (Por exemplo: cdn1.host.com, cdn2.host.com). - - [express-slash](https://github.com/ericf/express-slash): Módulo middleware do Express para pessoas rigorosas quanto ao uso de barras no fim. - - - [express-stormpath](https://github.com/stormpath/stormpath-express): Módulo middleware do Express para armazenamento de usuário, autenticação, autorização,SSO e segurança de dados. - - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize): módulo middleware para redirecionamento de solicitações HTTP contendo letras maiúsculas para a forma canônica minúscula. - - - [helmet](https://github.com/helmetjs/helmet): módulo para ajudar a proteger seus aplicativos configurando vários cabeçalhos HTTP. - - [join-io](https://github.com/coderaiser/join-io "join-io"): módulo para junção de arquivos em tempo de execução para reduzir a contagem de solicitações. - - [method-override](https://github.com/expressjs/method-override): anteriormente `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan): anteriormente `logger` - - [passport](https://github.com/jaredhanson/passport): módulo middleware do Express para autenticação. - - [response-time](https://github.com/expressjs/response-time): anteriormente `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon): anteriormente `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index): anteriormente `express.directory` - - [serve-static](https://github.com/expressjs/serve-static): módulo para entregar conteúdo estático. - - [static-expiry](https://github.com/paulwalker/connect-static-expiry): URLs identificadas ou Armazenamento em cache de Cabeçalhos para ativos estáticos incluindo suporte para um ou mais domínios externos. - - - [vhost](https://github.com/expressjs/vhost): anteriormente `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers): módulo middleware do Express que fornece métodos auxiliares comuns para as visualizações. - - - [sriracha-admin](https://github.com/hdngr/siracha): módulo middleware do Express que gera dinamicamente um site de administração para o Mongoose. - -Alguns módulos de middleware anteriormente incluídos com o -Connect não são mais suportados pelo time Connect/Express. Estes -módulos foram substituídos por um módulo alternativo, ou devem ser -substituídos por um módulo melhor. Use uma das alternativas a seguir: - - - - express.cookieParser - - [cookies](https://github.com/jed/cookies) e [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) - -Para obter mais módulos middleware, consulte: - - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| Middleware module | Descrição | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | + +## Para obter mais módulos middleware, consulte: + +These are some additional popular middleware modules. + +{% include community-caveat.html %} + +| Middleware module | Descrição | +| ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [st](https://github.com/isaacs/st) | [helmet](https://github.com/helmetjs/helmet): módulo para ajudar a proteger seus aplicativos configurando vários cabeçalhos HTTP. | +| [passport](https://github.com/jaredhanson/passport): módulo middleware do Express para autenticação. | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/pt-br/resources/middleware/body-parser.md b/pt-br/resources/middleware/body-parser.md new file mode 100644 index 0000000000..3236d01955 --- /dev/null +++ b/pt-br/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: pt-br +redirect_from: " " +module: body-parser +--- diff --git a/pt-br/resources/middleware/compression.md b/pt-br/resources/middleware/compression.md new file mode 100644 index 0000000000..1801e2f5f2 --- /dev/null +++ b/pt-br/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: pt-br +redirect_from: " " +module: compression +--- diff --git a/pt-br/resources/middleware/connect-rid.md b/pt-br/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..4a5ff346c8 --- /dev/null +++ b/pt-br/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: pt-br +redirect_from: " " +module: connect-rid +--- diff --git a/pt-br/resources/middleware/cookie-parser.md b/pt-br/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..5362f893ee --- /dev/null +++ b/pt-br/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: pt-br +redirect_from: " " +module: cookie-parser +--- diff --git a/pt-br/resources/middleware/cookie-session.md b/pt-br/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..567d635435 --- /dev/null +++ b/pt-br/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: pt-br +redirect_from: " " +module: cookie-session +--- diff --git a/pt-br/resources/middleware/cors.md b/pt-br/resources/middleware/cors.md new file mode 100644 index 0000000000..117ea9657e --- /dev/null +++ b/pt-br/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: pt-br +redirect_from: " " +module: cors +--- diff --git a/pt-br/resources/middleware/errorhandler.md b/pt-br/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..01b87dc844 --- /dev/null +++ b/pt-br/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: pt-br +redirect_from: " " +module: errorhandler +--- diff --git a/pt-br/resources/middleware/method-override.md b/pt-br/resources/middleware/method-override.md new file mode 100644 index 0000000000..ba5153021a --- /dev/null +++ b/pt-br/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: pt-br +redirect_from: " " +module: method-override +--- diff --git a/pt-br/resources/middleware/morgan.md b/pt-br/resources/middleware/morgan.md new file mode 100644 index 0000000000..dde14143af --- /dev/null +++ b/pt-br/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: pt-br +redirect_from: " " +module: morgan +--- diff --git a/pt-br/resources/middleware/multer.md b/pt-br/resources/middleware/multer.md new file mode 100644 index 0000000000..40e3106322 --- /dev/null +++ b/pt-br/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: pt-br +redirect_from: " " +module: multer +--- diff --git a/pt-br/resources/middleware/response-time.md b/pt-br/resources/middleware/response-time.md new file mode 100644 index 0000000000..022e967ac7 --- /dev/null +++ b/pt-br/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: pt-br +redirect_from: " " +module: response-time +--- diff --git a/pt-br/resources/middleware/serve-favicon.md b/pt-br/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..7aa8d9f689 --- /dev/null +++ b/pt-br/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: pt-br +redirect_from: " " +module: serve-favicon +--- diff --git a/pt-br/resources/middleware/serve-index.md b/pt-br/resources/middleware/serve-index.md new file mode 100644 index 0000000000..3be11de0a9 --- /dev/null +++ b/pt-br/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: pt-br +redirect_from: " " +module: serve-index +--- diff --git a/pt-br/resources/middleware/serve-static.md b/pt-br/resources/middleware/serve-static.md new file mode 100644 index 0000000000..5e64fd3ebe --- /dev/null +++ b/pt-br/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: pt-br +redirect_from: " " +module: serve-static +--- diff --git a/pt-br/resources/middleware/session.md b/pt-br/resources/middleware/session.md new file mode 100644 index 0000000000..7022e69fed --- /dev/null +++ b/pt-br/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: pt-br +redirect_from: " " +module: session +--- diff --git a/pt-br/resources/middleware/timeout.md b/pt-br/resources/middleware/timeout.md new file mode 100644 index 0000000000..a8e3b6cc7a --- /dev/null +++ b/pt-br/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: pt-br +redirect_from: " " +module: timeout +--- diff --git a/pt-br/resources/middleware/vhost.md b/pt-br/resources/middleware/vhost.md new file mode 100644 index 0000000000..b907bc5b6b --- /dev/null +++ b/pt-br/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: pt-br +redirect_from: " " +module: vhost +--- diff --git a/pt-br/resources/utils.md b/pt-br/resources/utils.md new file mode 100644 index 0000000000..4bb961407b --- /dev/null +++ b/pt-br/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: pt-br +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | Descrição | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/pt-br/starter/basic-routing.md b/pt-br/starter/basic-routing.md old mode 100755 new mode 100644 index d0457e7ffc..f51e4d3c58 --- a/pt-br/starter/basic-routing.md +++ b/pt-br/starter/basic-routing.md @@ -1,16 +1,15 @@ --- layout: page title: Roteamento básico no Express +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. menu: starter lang: pt-br -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. +redirect_from: " " --- # Roteamento Básico -O *Roteamento* refere-se à determinação de como um +O _Roteamento_ refere-se à determinação de como um aplicativo responde a uma solicitação do cliente por um endpoint específico, que é uma URI (ou caminho) e um método de solicitação HTTP específico (GET, POST, e assim por diante). @@ -19,6 +18,7 @@ Cada rota pode ter uma ou mais funções de manipulação, que são executadas quando a rota é correspondida. A definição de rotas aceita a seguinte estrutura: + ```js app.METHOD(PATH, HANDLER) ``` @@ -72,3 +72,5 @@ app.delete('/user', (req, res) => { ``` Para obter mais detalhes sobre roteamento, consulte o [guia de roteamento](/{{ page.lang }}/guide/routing.html). + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/pt-br/starter/examples.md b/pt-br/starter/examples.md index 14e56527a9..d2d3951294 100644 --- a/pt-br/starter/examples.md +++ b/pt-br/starter/examples.md @@ -4,7 +4,7 @@ title: Exemplos do Express description: Explore uma coleção de exemplos de aplicações em Express.js cobrindo diversos casos de uso, integrações e configurações avançadas para te ajudar a aprender e construir seus projetos. menu: starter lang: pt-br -redirect_from: "/starter/examples.html" +redirect_from: " " --- {% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} diff --git a/pt-br/starter/faq.md b/pt-br/starter/faq.md old mode 100755 new mode 100644 index dbf369c247..aa61eb3c19 --- a/pt-br/starter/faq.md +++ b/pt-br/starter/faq.md @@ -1,11 +1,10 @@ --- layout: page title: Pergunta mais Frequentes do Express +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: pt-br -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # Perguntas mais frequentes @@ -21,14 +20,14 @@ Rotas e outras lógicas específicas do aplicativo podem ficar em quantos arquivos quiser, em qualquer estrutura de diretórios que preferir. Visualize os seguintes exemplos para obter inspiração: -* [Listagens de rota](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [Mapa de rota](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [Controladores com estilo MVC](https://github.com/expressjs/express/tree/master/examples/mvc) +- [Listagens de rota](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [Mapa de rota](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [Controladores com estilo MVC](https://github.com/expressjs/express/tree/master/examples/mvc) Além disso, existem extensões de terceiros para o Express, que simplificam alguns desses padrões: -* [Roteamento engenhoso](https://github.com/expressjs/express-resource) +- [Resourceful routing](https://github.com/expressjs/express-resource) ## Como eu defino modelos? @@ -42,11 +41,10 @@ uma estrutura baseada no Express que é centrada em modelos. ## Como posso autenticar usuários? Autenticação é outra área muito opinada que o Express não -se arrisca a entrar. Você pode usar qualquer esquema que desejar. +se arrisca a entrar. Você pode usar qualquer esquema que desejar. Para um esquema simples com nome de usuário / senha, consulte -[este -exemplo](https://github.com/expressjs/express/tree/master/examples/auth). - +este +exemplo. ## Quais mecanismos de modelo o Express suporta? @@ -59,6 +57,8 @@ cache de mecanismo de modelo, consulte o projeto para obter suporte. Mecanismos de modelo não listados podem ainda assim suportar a assinatura do Express. +[Roteamento engenhoso](https://github.com/expressjs/express-resource) + ## Como manipulo respostas 404? No Express, respostas 404 não são o resultado de um erro, @@ -71,10 +71,13 @@ funções) para manipular uma resposta 404: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## Como configuro um manipulador de erros? Você define middlewares de manipulação de erros da mesma forma @@ -98,3 +101,10 @@ se você tiver um arquivo específico, use a função `res.sendFile()`. Se estiver entregando muitos ativos a partir de um diretório, use a função de middleware `express.static()`. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/pt-br/starter/generator.md b/pt-br/starter/generator.md old mode 100755 new mode 100644 index 5938cae34b..41dd8f7f14 --- a/pt-br/starter/generator.md +++ b/pt-br/starter/generator.md @@ -1,10 +1,10 @@ --- layout: page title: Gerador de aplicativos do Express +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: pt-br -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Gerador de aplicativos do Express @@ -12,10 +12,17 @@ description: Learn how to use the Express application generator tool to quickly Use a ferramenta geradora de aplicativos, `express`, para rapidamente criar uma estrutura básica de aplicativo. -Instale o `express` com o comando a seguir: +You can run the application generator with the `npx` command (available in 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: ```bash -$ npm install express-generator -g +$ npm install -g express-generator +$ express ``` Exiba as opções de comando com a opção `-h`: @@ -23,7 +30,7 @@ Exiba as opções de comando com a opção `-h`: ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -34,14 +41,14 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` Por exemplo, o seguinte cria um aplicativo do Express chamado _myapp_ -no diretório atualmente em funcionamento: +no diretório atualmente em funcionamento: The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -84,8 +91,13 @@ No Windows, use este comando: > set DEBUG=myapp:* & npm start ``` -Em seguida carregue `http://localhost:3000/` no seu navegador para acessar o aplicativo. +Instale o `express` com o comando a seguir: + +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` +Em seguida carregue `http://localhost:3000/` no seu navegador para acessar o aplicativo. O aplicativo gerado possui a seguinte estrutura de diretórios: @@ -112,6 +124,7 @@ O aplicativo gerado possui a seguinte estrutura de diretórios: ```
      -A estrutura de aplicativo criada pelo gerador é apenas uma das várias maneiras de estruturar aplicativos do Express. -É possível utilizar esta estrutura ou modificá-la para melhor se adequar às suas necessidades. +A estrutura de aplicativo criada pelo gerador é apenas uma das várias maneiras de estruturar aplicativos do Express. É possível utilizar esta estrutura ou modificá-la para melhor se adequar às suas necessidades.
      + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/pt-br/starter/hello-world.md b/pt-br/starter/hello-world.md old mode 100755 new mode 100644 index 7f3561f064..7fa1e0e674 --- a/pt-br/starter/hello-world.md +++ b/pt-br/starter/hello-world.md @@ -1,10 +1,10 @@ --- layout: page title: Exemplo "Hello World" do Express +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: pt-br -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Exemplo Hello World @@ -16,12 +16,6 @@ que cria a estrutura para um aplicativo completo com inúmeros arquivos JavaScri propósitos.
      -Primeiro crie um diretório chamado `myapp`, -mude para ele e execute o `npm init`. Em seguida -instale o `express` como uma dependência, de acordo com o [guia de instalação](/{{ page.lang }}/starter/installing.html). - -No diretório `myapp`, crie um arquivo chamado `app.js` e inclua o seguinte código: - ```js const express = require('express') const app = express() @@ -38,9 +32,17 @@ app.listen(port, () => { O aplicativo inicia um servidor e escuta a porta 3000 por conexões. O aplicativo responde com "Hello World!" à solicitações -para a URL raiz (`/`) ou *rota*. Para +para a URL raiz (`/`) ou _rota_. Para todos os outros caminhos, ele irá responder com um **404 Não Encontrado**. +### Running Locally + +Primeiro crie um diretório chamado `myapp`, +mude para ele e execute o `npm init`. Em seguida +instale o `express` como uma dependência, de acordo com o [guia de instalação](/{{ page.lang }}/starter/installing.html). + +No diretório `myapp`, crie um arquivo chamado `app.js` e inclua o seguinte código: +
      O `req` (solicitação) e `res` (resposta) são os mesmos objetos que o Node fornece, para que seja @@ -58,3 +60,4 @@ $ node app.js Em seguida, carregue [http://localhost:3000/](http://localhost:3000/) em um navegador para visualizar a saída +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/pt-br/starter/installing.md b/pt-br/starter/installing.md old mode 100755 new mode 100644 index c700ce67d4..40a2e39900 --- a/pt-br/starter/installing.md +++ b/pt-br/starter/installing.md @@ -1,10 +1,10 @@ --- layout: page title: Instalando o Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: pt-br -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # Instalação @@ -12,6 +12,9 @@ description: Learn how to install Express.js in your Node.js environment, includ Assumindo que já tenha instalado o [Node.js](https://nodejs.org/), crie um diretório para conter o seu aplicativo, e torne-o seu diretório ativo. +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -29,7 +32,7 @@ Este comando solicita por várias coisas, como o nome e versão do seu aplicativ Por enquanto, é possível simplesmente pressionar RETURN para aceitar os padrões para a maioria deles, com as seguintes exceções: -```bash +``` entry point: (index.js) ``` @@ -41,21 +44,22 @@ Agora instale o Express no diretório `myapp` e salve-o na lista de dependências. Por exemplo: ```bash -$ npm install express --save +$ npm install express ``` Para instalar o Express temporariamente não o inclua na lista de dependências, omita a opção `--save`: ```bash -$ npm install express +$ npm install express --no-save ```
      Módulos do Node instalados com a opção `--save` são incluídas na lista `dependencies` no arquivo -`package.json`. -Posteriormente, executando `npm install` no diretório +`package.json`. Posteriormente, executando `npm install` no diretório `app` irá automaticamente instalar os módulos na lista de dependências.
      + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/pt-br/starter/static-files.md b/pt-br/starter/static-files.md old mode 100755 new mode 100644 index 6db8ce828b..fbf878218f --- a/pt-br/starter/static-files.md +++ b/pt-br/starter/static-files.md @@ -1,10 +1,10 @@ --- layout: page title: Entregando arquivos estáticos no Express +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: pt-br -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # Entregando arquivos estáticos no Express @@ -13,9 +13,16 @@ Para entregar arquivos estáticos como imagens, arquivos CSS, e arquivos JavaScript, use a função de middleware `express.static` integrada no Express. -Passe o nome do diretório que contém os ativos estáticos para a -função de middleware `express.static` para iniciar a -entregar os arquivos diretamente. Por exemplo, use o código a seguir +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](/{{page.lang}}/4x/api.html#express.static). + +Por exemplo, use o código a seguir para entregar imagens, arquivos CSS, e arquivos JavaScript em um diretório chamado `public`: @@ -50,6 +57,11 @@ O Express consulta os arquivos na ordem em que você configurar os diretórios estáticos com a função de middleware `express.static`. +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + Para criar um prefixo de caminho virtual (onde o caminho não existe realmente no sistema de arquivos) para arquivos que são entregues pela função `express.static`, @@ -82,3 +94,7 @@ entregar. const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/pt-br/support/index.md b/pt-br/support/index.md index b387d86047..e67453d918 100644 --- a/pt-br/support/index.md +++ b/pt-br/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: pt-br --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/zh-cn/3x/api.md b/zh-cn/3x/api.md old mode 100755 new mode 100644 index 695781f32f..778f33db6a --- a/zh-cn/3x/api.md +++ b/zh-cn/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - API 参考 -lang: zh-cn -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. +lang: en +redirect_from: " " --- +
      **Express 3.x 不再受到维护** - 自上次更新(2015 年 8 月 1 日)以来 3.x 中已知和未知的安全问题和性能问题都尚未处理。因此强烈建议您使用最新版本的 Express。 -
      - -

      3.x API

      +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. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
      - - {% include api/en/3x/res.md %} +

      3.x API

      - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
      diff --git a/zh-cn/4x/api.md b/zh-cn/4x/api.md old mode 100755 new mode 100644 index 9cfe526374..bc8b86bea4 --- a/zh-cn/4x/api.md +++ b/zh-cn/4x/api.md @@ -2,27 +2,26 @@ layout: api version: 4x title: Express 4.x - API 参考 -lang: zh-cn -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. +lang: en +redirect_from: " " --- +

      4.x API

      - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
      diff --git a/zh-cn/5x/api.md b/zh-cn/5x/api.md index dd09ec17af..1ce7a641d6 100644 --- a/zh-cn/5x/api.md +++ b/zh-cn/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - API 参考 -lang: zh-cn -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. +lang: en +redirect_from: " " ---

      5.x API

      -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/zh-cn/advanced/best-practice-performance.md b/zh-cn/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 34e131f102..22b4087b67 --- a/zh-cn/advanced/best-practice-performance.md +++ b/zh-cn/advanced/best-practice-performance.md @@ -1,104 +1,95 @@ --- layout: page title: 在生产环境中使用 Express 的性能最佳实践 +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced -lang: zh-cn -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +lang: en +redirect_from: " " --- # 生产环境最佳实践:性能和可靠性 -## 概述 - 本文讨论了部署到生产环境的 Express 应用程序的性能和可靠性最佳实践。 -本主题明显属于“DevOps”范畴,涵盖了传统的开发和运行流程。因此,本信息也相应地分为两个部分: - -* [代码中的注意事项](#code)(开发部分)。 -* [环境/设置中的注意事项](#env)(运行部分)。 +This topic clearly falls into the "devops" world, spanning both traditional development and operations. Accordingly, the information is divided into two parts: - +- [代码中的注意事项](#code)(开发部分)。 + - 通过 Gzip 压缩,有助于显著降低响应主体的大小,从而提高 Web 应用程序的速度。可使用[压缩](https://www.npmjs.com/package/compression)中间件进行 Express 应用程序中的 gzip 压缩。例如: + - 不使用同步函数 + - 正确进行日志记录 + - [Handle exceptions properly](#handle-exceptions-properly) +- Things to do in your environment / setup (the ops part): + - 将 NODE_ENV 设置为“production” + - Node 应用程序在遇到未捕获的异常时会崩溃。您需要确保应用程序经过彻底测试,能够处理所有异常,这一点最为重要(请参阅[正确处理异常](#exceptions)以了解详细信息)。但是,作为一种防故障措施,请实施一种机制,确保应用程序崩溃后可以自动重新启动。 + - 在集群应用程序中,个别工作进程的崩溃并不会影响其余的进程。除了性能优势,故障隔离是运行应用程序进程集群的另一原因。每当工作进程崩溃时,请确保始终使用 cluster.fork() 来记录事件并生成新进程。 + - 高速缓存请求结果 + - 使用负载均衡器 + - 逆向代理位于 Web 应用程序之前,除了将请求转发给应用程序外,还对请求执行支持性操作。它还可以处理错误页、压缩、高速缓存、文件服务和负载均衡等功能。 -## 代码中的注意事项 +## Things to do in your code {#in-code} 以下是为改进应用程序性能而在代码中要注意的事项: -* 使用 gzip 压缩 -* 不使用同步函数 -* 使用中间件提供静态文件 -* 正确进行日志记录 -* 正确处理异常 +- 通过 Gzip 压缩,有助于显著降低响应主体的大小,从而提高 Web 应用程序的速度。可使用[压缩](https://www.npmjs.com/package/compression)中间件进行 Express 应用程序中的 gzip 压缩。例如: +- 不使用同步函数 +- 正确进行日志记录 +- [Handle exceptions properly](#handle-exceptions-properly) ### 使用 gzip 压缩 -通过 Gzip 压缩,有助于显著降低响应主体的大小,从而提高 Web 应用程序的速度。可使用[压缩](https://www.npmjs.com/package/compression)中间件进行 Express 应用程序中的 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: ```js const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` -对于生产环境中的大流量网站,实施压缩的最佳位置是在反向代理层级(请参阅[使用反向代理](#proxy))。在此情况下,不需要使用压缩中间件。有关在 Nginx 中启用 gzip 压缩的详细信息,请参阅 Nginx 文档中的 [ngx_http_gzip_module 模块](http://nginx.org/en/docs/http/ngx_http_gzip_module.html)。 +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. 对于生产环境中的大流量网站,实施压缩的最佳位置是在反向代理层级(请参阅[使用反向代理](#proxy))。在此情况下,不需要使用压缩中间件。有关在 Nginx 中启用 gzip 压缩的详细信息,请参阅 Nginx 文档中的 [ngx_http_gzip_module 模块](http://nginx.org/en/docs/http/ngx_http_gzip_module.html)。 ### 不使用同步函数 -同步函数和方法会阻止执行进程的运行,直至其返回。对同步函数的每次调用可能在数微秒或数毫秒后返回,但是在大流量网站中,这些调用的累积返回时间也相当可观,会影响到应用程序的性能。因此应避免在生产环境中使用同步函数。 +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 和许多模块提供函数的同步和异步版本,但是在生产环境中请始终使用异步版本。只有在初始启动时才适合使用同步函数。 +虽然 Node 和许多模块提供函数的同步和异步版本,但是在生产环境中请始终使用异步版本。只有在初始启动时才适合使用同步函数。 The only time when a synchronous function can be justified is upon initial startup. -如果您使用 Node.js 4.0+ 或 io.js 2.1.0+,那么可以使用 `--trace-sync-io` 命令行标记,每当应用程序使用同步 API 时就显示一条警告消息和堆栈跟踪。当然,您不会希望在生产环境中实际使用此功能,这只是为了确保代码已准备好用于生产环境。请参阅 [node 命令行选项文档](https://nodejs.org/api/cli.html#cli_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#cli_trace_sync_io) for more information. -### 正确进行日志记录 +### 正确处理异常 -一般而言,从应用程序进行日志记录有两个原因:出于调试目的和出于记录应用程序活动目的(基本上就是除调试以外的其他所有事项)。通过使用 `console.log()` 或 `console.err()` 在终端上显示日志消息是开发过程中的常见做法。但是,如果目标是终端或文件,[这些函数就是同步的](https://nodejs.org/api/console.html#console_console_1),因此,除非要将输出通过管道传到另一个程序,否则上述函数就不适合用于生产环境。 +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 -如果您出于调试目的进行日志记录,请使用 [debug](https://www.npmjs.com/package/debug) 这样的特殊调试模块,而不要使用 `console.log()`。此模块支持您使用 DEBUG 环境变量来控制将哪些调试消息(如果有)发送到 `console.err()`。为了确保应用程序完全采用异步方式,仍需要将 `console.err()` 通过管道传到另一个程序。但您并不会真的希望在生产环境中进行调试,对吧? +如果您出于调试目的进行日志记录,请使用 [debug](https://www.npmjs.com/package/debug) 这样的特殊调试模块,而不要使用 `console.log()`。此模块支持您使用 DEBUG 环境变量来控制将哪些调试消息(如果有)发送到 `console.err()`。为了确保应用程序完全采用异步方式,仍需要将 `console.err()` 通过管道传到另一个程序。但您并不会真的希望在生产环境中进行调试,对吧? 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? #### 出于应用程序活动目的 -如果要对应用程序活动进行日志记录(例如,跟踪流量或 API 调用),请使用 [Winston](https://www.npmjs.com/package/winston) 或 [Bunyan](https://www.npmjs.com/package/bunyan) 之类的日志记录库,而不要使用 `console.log()`。要了解这两个库的详细对比,请参阅 StrongLoop 博客帖子 [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/)。 - - +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. ### 正确处理异常 -Node 应用程序在遇到未捕获的异常时会崩溃。不处理异常并采取相应的措施会导致 Express 应用程序崩溃并脱机。如果您按照以下[确保应用程序自动重新启动](#restart)中的建议执行,那么应用程序可以从崩溃中恢复。幸运的是,Express 应用程序的启动时间一般很短。然而,应当首先立足于避免崩溃,为此,需要正确处理异常。 +Node 应用程序在遇到未捕获的异常时会崩溃。不处理异常并采取相应的措施会导致 Express 应用程序崩溃并脱机。如果您按照以下[确保应用程序自动重新启动](#restart)中的建议执行,那么应用程序可以从崩溃中恢复。幸运的是,Express 应用程序的启动时间一般很短。然而,应当首先立足于避免崩溃,为此,需要正确处理异常。 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. 要确保处理所有异常,请使用以下方法: -* [使用 try-catch](#try-catch) -* [使用 promise](#promises) +- [使用 try-catch](#try-catch) +- [使用 promise](#promises) -在深入了解这些主题之前,应该对 Node/Express 错误处理有基本的了解:使用 error-first 回调并在中间件中传播错误。Node 将“error-first 回调”约定用于从异步函数返回错误,回调函数的第一个参数是错误对象,后续参数中包含结果数据。为了表明没有错误,可将 null 值作为第一个参数传递。回调函数必须相应地遵循“error-first”回调约定,以便有意义地处理错误。在 Express 中,最佳做法是使用 next() 函数,通过中间件链来传播错误。 +在深入了解这些主题之前,应该对 Node/Express 错误处理有基本的了解:使用 error-first 回调并在中间件中传播错误。Node 将“error-first 回调”约定用于从异步函数返回错误,回调函数的第一个参数是错误对象,后续参数中包含结果数据。为了表明没有错误,可将 null 值作为第一个参数传递。回调函数必须相应地遵循“error-first”回调约定,以便有意义地处理错误。在 Express 中,最佳做法是使用 next() 函数,通过中间件链来传播错误。 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. 有关错误处理基本知识的更多信息,请参阅: -* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/)(StrongLoop 博客) - -#### 请勿执行以下操作 - -*请勿*侦听 `uncaughtException` 事件,当异常像气泡一样在事件循环中一路回溯时,就会发出该事件。为 `uncaughtException` 添加事件侦听器将改变进程遇到异常时的缺省行为;进程将继续运行而不理会异常。这貌似是防止应用程序崩溃的好方法,但是在遇到未捕获的异常之后仍继续运行应用程序是一种危险的做法,不建议这么做,因为进程状态可能会变得不可靠和不可预测。 - -此外,`uncaughtException` 被公认为[比较粗糙](https://nodejs.org/api/process.html#process_event_uncaughtexception),[建议](https://github.com/nodejs/node-v0.x-archive/issues/2582)从内核中将其移除。所以侦听 `uncaughtException` 并不是个好主意。这就是为何我们推荐诸如多个进程和虚拟机管理器之类的方案:崩溃后重新启动通常是从错误中恢复的最可靠方法。 - -我们也不建议使用[域](https://nodejs.org/api/domain.html)。它一般并不能解决问题,是一种不推荐使用的模块。 - - +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### 使用 try-catch -Try-catch 是一种 JavaScript 语言构造,可用于捕获同步代码中的异常。例如,使用 try-catch 来处理 JSON 解析错误(如下所示)。 +Try-catch 是一种 JavaScript 语言构造,可用于捕获同步代码中的异常。例如,使用 try-catch 来处理 JSON 解析错误(如下所示)。 Use try-catch, for example, to handle JSON parsing errors as shown below. -使用诸如 [JSHint](http://jshint.com/) 或 [JSLint](http://www.jslint.com/) 之类的工具有助于查找类似[未定义变量的引用错误](http://www.jshint.com/docs/options/#undef)这样的隐含异常。 - -以下示例使用 try-catch 来处理潜在的进程崩溃异常。 -此中间件函数接受名为“params”的查询字段参数(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) => { @@ -115,162 +106,126 @@ app.get('/search', (req, res) => { }) ``` -然而,try-catch 仅适用于同步代码。而由于 Node 平台主要采用异步方式(尤其在生产环境中),因此 try-catch 不会捕获大量异常。 - - +However, try-catch works only for synchronous code. 然而,try-catch 仅适用于同步代码。而由于 Node 平台主要采用异步方式(尤其在生产环境中),因此 try-catch 不会捕获大量异常。 #### 使用 promise -Promise 可以处理使用 `then()` 的异步代码块中的任何异常(显式和隐式)。只需将 `.catch(next)` 添加到 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)` ```js -app.get('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -现在,所有异步和同步错误都会传播到错误中间件。 - -然而,有两则警告: - -1. 所有异步代码必须返回 Promise(除了发射器)。如果特定库未返回 Promise,请使用类似 [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html) 的助手函数来转换基本对象。 -2. 事件发射器(比如流)仍然会导致未捕获的异常。所以请确保正确处理错误事件;例如: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -有关使用 Promise 来处理错误的更多信息,请参阅: +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. -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +#### What not to do - +_请勿_侦听 `uncaughtException` 事件,当异常像气泡一样在事件循环中一路回溯时,就会发出该事件。为 `uncaughtException` 添加事件侦听器将改变进程遇到异常时的缺省行为;进程将继续运行而不理会异常。这貌似是防止应用程序崩溃的好方法,但是在遇到未捕获的异常之后仍继续运行应用程序是一种危险的做法,不建议这么做,因为进程状态可能会变得不可靠和不可预测。 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` 被公认为[比较粗糙](https://nodejs.org/api/process.html#process_event_uncaughtexception),[建议](https://github.com/nodejs/node-v0.x-archive/issues/2582)从内核中将其移除。所以侦听 `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. -以下是为改进应用程序性能而在系统环境中要注意的事项: +我们也不建议使用[域](https://nodejs.org/api/domain.html)。它一般并不能解决问题,是一种不推荐使用的模块。 It generally doesn't solve the problem and is a deprecated module. -* 将 NODE_ENV 设置为“production” -* 确保应用程序能够自动重新启动 -* 在集群中运行应用程序 -* 高速缓存请求结果 -* 使用负载均衡器 -* 使用逆向代理 +## Things to do in your environment / setup -### 将 NODE_ENV 设置为“production” +{#in-environment} -NODE_ENV 环境变量指定运行应用程序的环境(通常是开发或者生产环境)。为了改进性能,最简单的方法是将 NODE_ENV 设置为“production”。 +以下是为改进应用程序性能而在系统环境中要注意的事项: -将 NODE_ENV 设置为“production”会使 Express: +- 将 NODE_ENV 设置为“production” +- Node 应用程序在遇到未捕获的异常时会崩溃。您需要确保应用程序经过彻底测试,能够处理所有异常,这一点最为重要(请参阅[正确处理异常](#exceptions)以了解详细信息)。但是,作为一种防故障措施,请实施一种机制,确保应用程序崩溃后可以自动重新启动。 +- 在集群应用程序中,个别工作进程的崩溃并不会影响其余的进程。除了性能优势,故障隔离是运行应用程序进程集群的另一原因。每当工作进程崩溃时,请确保始终使用 cluster.fork() 来记录事件并生成新进程。 +- 高速缓存请求结果 +- 使用负载均衡器 +- 逆向代理位于 Web 应用程序之前,除了将请求转发给应用程序外,还对请求执行支持性操作。它还可以处理错误页、压缩、高速缓存、文件服务和负载均衡等功能。 -* 高速缓存视图模板。 -* 高速缓存从 CSS 扩展生成的 CSS 文件。 -* 生成简短的错误消息。 +### 将 NODE_ENV 设置为“production” -[测试表明](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/)仅仅这样做就可以使应用程序性能提高 3 倍多! +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`. -如果您需要编写特定于环境的代码,可以使用 `process.env.NODE_ENV` 来检查 NODE_ENV 的值。请注意,检查任何环境变量的值都会导致性能下降,所以应该三思而行。 +将 NODE_ENV 设置为“production”会使 Express: -在开发中,通常会在交互式 shell 中设置环境变量,例如,使用 `export` 或者 `.bash_profile` 文件。但是一般而言,您不应在生产服务器上执行此操作;而是应当使用操作系统的初始化系统(systemd 或 Upstart)。下一节提供如何使用初始化系统的常规详细信息,但是设置 NODE_ENV 对于性能非常重要(且易于操作),所以会在此重点介绍。 +- 高速缓存视图模板。 +- 高速缓存从 CSS 扩展生成的 CSS 文件。 +- 生成简短的错误消息。 -对于 Upstart,请使用作业文件中的 `env` 关键字。例如: +[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! -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` +如果您需要编写特定于环境的代码,可以使用 `process.env.NODE_ENV` 来检查 NODE_ENV 的值。请注意,检查任何环境变量的值都会导致性能下降,所以应该三思而行。 Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. -有关更多信息,请参阅 [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables)。 +在开发中,通常会在交互式 shell 中设置环境变量,例如,使用 `export` 或者 `.bash_profile` 文件。但是一般而言,您不应在生产服务器上执行此操作;而是应当使用操作系统的初始化系统(systemd 或 Upstart)。下一节提供如何使用初始化系统的常规详细信息,但是设置 NODE_ENV 对于性能非常重要(且易于操作),所以会在此重点介绍。 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` 伪指令。例如: +对于 systemd,请使用单元文件中的 `Environment` 伪指令。例如: For example: ```sh # /etc/systemd/system/myservice.service Environment=NODE_ENV=production ``` -有关更多信息,请参阅 [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html)。 - -如果在使用 StrongLoop Process Manager,还可以[在将 StrongLoop PM 作为服务安装时设置环境变量](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables)。 +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### 确保应用程序能够自动重新启动 -在生产环境中,您肯定不希望应用程序脱机。这意味着需要确保在应用程序崩溃的情况下以及服务器自身崩溃的情况下应用程序都能够重新启动。虽然您不希望这两种情况发生,但是必须未雨绸缪,以防不测: +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: -* 使用进程管理器在应用程序(和 Node)崩溃时将其重新启动。 -* 在操作系统崩溃时,使用操作系统提供的初始化系统重新启动进程管理器。还可以在没有进程管理器的情况下使用初始化系统。 +- 使用进程管理器在应用程序(和 Node)崩溃时将其重新启动。 +- 在操作系统崩溃时,使用操作系统提供的初始化系统重新启动进程管理器。还可以在没有进程管理器的情况下使用初始化系统。 It's also possible to use the init system without a process manager. -Node 应用程序在遇到未捕获的异常时会崩溃。您需要确保应用程序经过彻底测试,能够处理所有异常,这一点最为重要(请参阅[正确处理异常](#exceptions)以了解详细信息)。但是,作为一种防故障措施,请实施一种机制,确保应用程序崩溃后可以自动重新启动。 +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 server.js` 或类似项启动应用程序。但是在生产环境中执行此操作会导致灾难。如果应用程序崩溃,它会脱机,直到其重新启动为止。为了确保应用程序在崩溃后可以重新启动,请使用进程管理器。进程管理器是一种应用程序“容器”,用于促进部署,提供高可用性,并支持用户在运行时管理应用程序。 +在开发中,只需在命令行从 `node server.js` 或类似项启动应用程序。但是在生产环境中执行此操作会导致灾难。如果应用程序崩溃,它会脱机,直到其重新启动为止。为了确保应用程序在崩溃后可以重新启动,请使用进程管理器。进程管理器是一种应用程序“容器”,用于促进部署,提供高可用性,并支持用户在运行时管理应用程序。 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. 除了在应用程序崩溃时将其重新启动外,进程管理器还可以执行以下操作: -* 获得对运行时性能和资源消耗的洞察。 -* 动态修改设置以改善性能。 -* 控制集群(StrongLoop PM 和 pm2)。 - -Node 的最流行进程管理器包括: - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -要了解对这三种进程管理器的逐个功能的比较,请参阅 [http://strong-pm.io/compare/](http://strong-pm.io/compare/)。 +- 获得对运行时性能和资源消耗的洞察。 +- 动态修改设置以改善性能。 +- Control clustering (pm2). -即使应用程序会不时崩溃,使用其中任何进程管理器都足以使其成功启动。 - -但 StrongLoop PM 有许多专门针对生产部署的功能。您可以使用该管理器以及相关的 StrongLoop 工具执行以下功能: - -* 在本地构建和打包应用程序,然后将其安全地部署到生产系统。 -* 在应用程序由于任何原因而崩溃时自动将其重新启动。 -* 远程管理集群。 -* 查看 CPU 概要文件和堆快照,以优化性能和诊断内存泄漏。 -* 查看应用程序的性能指标。 -* 轻松地扩展到具有 Nginx 负载均衡器集成控制的多个主机。 - -如以下所述,在使用初始化系统将 StrongLoop PM 作为操作系统服务安装后,StrongLoop PM 会在系统重新启动时自动重新启动。这样,就可以确保应用程序进程和集群持久保持运行。 +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. #### 使用初始化系统 -下一层的可靠性是确保在服务器重新启动时应用程序可以重新启动。系统仍然可能由于各种原因而宕机。为了确保在服务器崩溃后应用程序可以重新启动,请使用内置于操作系统的初始化系统。目前主要使用两种初始化系统:[systemd](https://wiki.debian.org/systemd) 和 [Upstart](http://upstart.ubuntu.com/)。 +下一层的可靠性是确保在服务器重新启动时应用程序可以重新启动。系统仍然可能由于各种原因而宕机。为了确保在服务器崩溃后应用程序可以重新启动,请使用内置于操作系统的初始化系统。目前主要使用两种初始化系统:[systemd](https://wiki.debian.org/systemd) 和 [Upstart](http://upstart.ubuntu.com/)。 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 应用程序: -* 在进程管理器中运行应用程序,使用初始化系统将进程管理器安装为服务。进程管理器将在应用程序崩溃时将其重新启动,初始化系统则在操作系统重新启动时重新启动进程管理器。这是建议使用的方法。 -* 通过初始化系统直接运行应用程序(和 Node)。这样做要简单些,但是无法发挥使用进程管理器的额外优点。 +- 在进程管理器中运行应用程序,使用初始化系统将进程管理器安装为服务。进程管理器将在应用程序崩溃时将其重新启动,初始化系统则在操作系统重新启动时重新启动进程管理器。这是建议使用的方法。 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 作为其缺省初始化系统。 +Systemd 是一个 Linux 系统和服务管理器。大多数主要 Linux 分发版采用 systemd 作为其缺省初始化系统。 Most major Linux distributions have adopted systemd as their default init system. -systemd 服务配置文件称为*单元文件*,扩展名为 .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] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -292,142 +247,67 @@ Restart=always [Install] WantedBy=multi-user.target ``` -有关 systemd 的更多信息,请参阅 [systemd 参考(联机帮助页)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)。 -##### 作为 systemd 服务的 StrongLoop PM - -可以轻松地将 StrongLoop Process Manager 作为 systemd 服务安装。这样做之后,当服务器重新启动时,它会自动重新启动 StrongLoop PM,后者又会重新启动所管理的所有应用程序。 - -要将 StrongLoop PM 作为 systemd 服务安装: - -```bash -$ sudo sl-pm-install --systemd -``` -使用以下命令启动此服务: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -有关更多信息,请参阅[Setting up a production host](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10)(StrongLoop 文档)。 - -##### Upstart - -Upstart 是在许多 Linux 分发版上提供的一种系统工具,用于在系统启动期间启动某些任务和服务,在系统关闭期间停止这些任务和服务,以及对这些任务和服务进行监督。可以将 Express 应用程序或进程管理器配置为服务,这样 Upstart 会在其崩溃时自动将其重新启动。 - -Upstart 服务以作业配置文件(也称为“作业”)形式定义,扩展名为 `.conf`。以下示例说明如何为名为“myapp”的应用程序创建名为“myapp”的作业,其主文件位于 `/projects/myapp/index.js`。 - -在 `/etc/init/` 中创建名为 `myapp.conf` 的文件,其中包含以下内容(请将粗体文本替换为系统和应用程序的值): - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn +有关 systemd 的更多信息,请参阅 [systemd 参考(联机帮助页)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)。 -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` +### 在集群中运行应用程序 -注:此脚本需要 Ubuntu 12.04-14.10 上受支持的 Upstart 1.4 或更新版本。 +在多核系统中,可以通过启动进程的集群,将 Node 应用程序的性能提升多倍。一个集群运行此应用程序的多个实例,理想情况下一个 CPU 核心上运行一个实例,从而在实例之间分担负载和任务。 A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances. -由于此作业配置为在系统启动时运行,因此应用程序将随操作系统一起启动,并在应用程序崩溃或者系统宕机后自动重新启动。 +![Balancing between application instances using the cluster API](/images/clustering.png) -除了自动重新启动此应用程序,Upstart 还支持您使用以下命令: +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. -* `start myapp` - 启动应用程序 -* `restart myapp` - 重新启动应用程序 -* `stop myapp` - 停止应用程序。 +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(). -有关 Upstart 的更多信息,请参阅 [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook)。 +#### 使用 Node 的集群模块 -##### 作为 Upstart 服务的 StrongLoop PM +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. -可以轻松地将 StrongLoop Process Manager 作为 Upstart 服务安装。这样做之后,当服务器重新启动时,它会自动重新启动 StrongLoop PM,后者又会重新启动所管理的所有应用程序。 +#### Using PM2 -要将 StrongLoop PM 作为 Upstart 1.4 服务安装: +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). -```bash -$ sudo sl-pm-install -``` +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 -$ sudo /sbin/initctl start strong-pm +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -注:在不支持 Upstart 1.4 的系统上,这些命令略有不同。请参阅 [Setting up a production host](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10)(StrongLoop 文档),以了解更新信息。 - -### 在集群中运行应用程序 - -在多核系统中,可以通过启动进程的集群,将 Node 应用程序的性能提升多倍。一个集群运行此应用程序的多个实例,理想情况下一个 CPU 核心上运行一个实例,从而在实例之间分担负载和任务。 - - - -重要信息:由于应用程序实例作为单独的进程运行,因此它们不会共享同一内存空间。也就是说,对象位于应用程序每个实例的本地。因此,无法在应用程序代码中保存状态。然而,可以使用 [Redis](http://redis.io/) 之类的内存中数据存储器来存储与会话相关的数据和状态。此警告适用于几乎所有形式的水平扩展(无论是多个进程的集群还是多个物理服务器的集群)。 +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. -在集群应用程序中,个别工作进程的崩溃并不会影响其余的进程。除了性能优势,故障隔离是运行应用程序进程集群的另一原因。每当工作进程崩溃时,请确保始终使用 cluster.fork() 来记录事件并生成新进程。 - -#### 使用 Node 的集群模块 - -可以使用 Node 的[集群模块](https://nodejs.org/docs/latest/api/cluster.html)来建立集群。这使主进程可以生成工作进程并在工作进程之间分配传入连接。然而,使用可以自动执行此操作的众多工具中的一种(例如 [node-pm](https://www.npmjs.com/package/node-pm) 或 [cluster-service](https://www.npmjs.com/package/cluster-service)),要比直接使用此模块好得多。 - -#### 使用 StrongLoop PM - -如果将应用程序部署到 StrongLoop Process Manager (PM),那么可以利用集群*而不必*修改应用程序代码。 - -如果使用 StrongLoop Process Manager (PM) 运行应用程序,它会在集群中自动运行此应用程序,所生成的工作进程数等于系统中的 CPU 核心数。您可以使用 slc 命令行工具手动更改集群中工作进程的数量,而不必停止应用程序。 - -例如,假设要将应用程序部署到 prod.foo.com,并且 StrongLoop PM 正在端口 8701(缺省值)上侦听,那么可使用 slc 将集群大小设置为 8: +Once running, the application can be scaled like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ pm2 scale my-app 2 ``` -有关使用 StrongLoop PM 建立集群的更多信息,请参阅 StrongLoop 文档中的[集群](https://docs.strongloop.com/display/SLC/Clustering)。 +For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation. ### 高速缓存请求结果 提高生产环境性能的另一种策略是对请求的结果进行高速缓存,以便应用程序不需要为满足同一请求而重复执行操作。 -使用 [Varnish](https://www.varnish-cache.org/) 或 [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/)(另请参阅 [Nginx Caching](https://serversforhackers.com/nginx-caching/))之类的高速缓存服务器,可以显著提高应用程序的速度和性能。 +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. ### 使用负载均衡器 -无论应用程序如何优化,单个实例都只能处理有限的负载和流量。扩展应用程序的一种方法是运行此应用程序的多个实例,并通过负载均衡器分配流量。设置负载均衡器可以提高应用程序的性能和速度,并使可扩展性远超单个实例可以达到的水平。 - -负载均衡器通常是逆向代理,用于编排进出多个应用程序实例和服务器的流量。可以使用 [Nginx](http://nginx.org/en/docs/http/load_balancing.html) 或 [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) 轻松地为应用程序设置负载均衡器。 - -对于负载均衡功能,可能必须确保与特定会话标识关联的请求连接到产生请求的进程。这称为*会话亲缘关系*或者*粘性会话*,可通过以上的建议来做到这一点:将 Redis 之类的数据存储器用于会话数据(取决于您的应用程序)。要了解相关讨论,请参阅 [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/)。 +无论应用程序如何优化,单个实例都只能处理有限的负载和流量。扩展应用程序的一种方法是运行此应用程序的多个实例,并通过负载均衡器分配流量。设置负载均衡器可以提高应用程序的性能和速度,并使可扩展性远超单个实例可以达到的水平。 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. -#### 将 StrongLoop PM 与 Nginx 负载均衡器一起使用 +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). -[StrongLoop Process Manager](http://strong-pm.io/) 与 Nginx Controller 集成,从而能够方便地配置多主机生产环境配置。有关更多信息,请参阅 [Scaling to multiple servers](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers)(StrongLoop 文档)。 - +对于负载均衡功能,可能必须确保与特定会话标识关联的请求连接到产生请求的进程。这称为_会话亲缘关系_或者_粘性会话_,可通过以上的建议来做到这一点:将 Redis 之类的数据存储器用于会话数据(取决于您的应用程序)。要了解相关讨论,请参阅 [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/)。 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/). ### 使用逆向代理 -逆向代理位于 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 腾出资源来执行专门的应用程序任务。因此,建议在生产环境中,在 [Nginx](https://www.nginx.com/) 或 [HAProxy](http://www.haproxy.org/) 之类的逆向代理背后运行 Express。 +通过将无需了解应用程序状态的任务移交给逆向代理,可以使 Express 腾出资源来执行专门的应用程序任务。因此,建议在生产环境中,在 [Nginx](https://www.nginx.com/) 或 [HAProxy](http://www.haproxy.org/) 之类的逆向代理背后运行 Express。 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. diff --git a/zh-cn/advanced/best-practice-security.md b/zh-cn/advanced/best-practice-security.md old mode 100755 new mode 100644 index a314370058..06bc381275 --- a/zh-cn/advanced/best-practice-security.md +++ b/zh-cn/advanced/best-practice-security.md @@ -1,79 +1,173 @@ --- layout: page title: 生产环境中 Express 的安全最佳实践 +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced -lang: zh-cn -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +lang: en +redirect_from: " " --- # 生产环境最佳实践:安全 ## 概述 -术语*“生产”*表示软件生命周期中应用程序或 API 可供最终用户或使用者正常使用的阶段。而在*“开发”*阶段中,您仍然积极编写和测试代码,应用程序并未对外部开发访问。对应的系统环境分别被称为*生产*和*开发*环境。 +术语\*“生产”_表示软件生命周期中应用程序或 API 可供最终用户或使用者正常使用的阶段。而在_“开发”_阶段中,您仍然积极编写和测试代码,应用程序并未对外部开发访问。对应的系统环境分别被称为_生产_和_开发\*环境。 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. -开发和生产环境的设置通常不同,需求也天差地别。在开发环境中没问题的做法在生产环境中可能就无法接受。例如,在开发环境中,可能需要对错误进行详细日志记录以便进行调试,而同一行为在生产环境中可能会成为安全问题。在开发环境中,无需担心可扩展性、可靠性和性能,而这些方面在生产环境中就是关键问题。 +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. + +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} 本文讨论了部署到生产环境的 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) + - [hsts](https://github.com/helmetjs/hsts) 用于设置 `Strict-Transport-Security` 头,实施安全的服务器连接 (HTTP over SSL/TLS)。 + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) 用于移除 `X-Powered-By` 头。 + - [Reduce fingerprinting](#reduce-fingerprinting) + - `domain` - 表示 cookie 的域;用于和请求 URL 的服务器的域进行比较。如果匹配,那么接下来检查路径属性。 + - 相反,[cookie-session](https://www.npmjs.com/package/cookie-session) 中间件实现 cookie 支持的存储:它将整个会话序列化到 cookie 中,而不只是会话键。仅当会话数据相对较小,且易于编码为原语值(而不是对象)时,才使用此中间件。尽管假设浏览器支持每个 cookie 至少 4096 字节以确保不会超过限制,但是每个域的大小不会超过 4093 字节。另外请注意,客户机可以访问 cookie 数据,所以,如果有任何理由将其保持安全或隐藏状态,那么 express-session 可能是更好的选择。 + - 使用缺省会话 cookie 名称会使应用程序对攻击敞开大门。`X-Powered-By` 之类的值会造成问题:潜在攻击者可以利用这样的值对服务器采集“指纹”,并相应地确定攻击目标。 + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure) + - 最后说明一点,和任何其他 Web 应用程序一样,Express 应用程序也容易受到各种基于 Web 的攻击。请熟悉已知的 [Web 漏洞](https://www.owasp.org/www-project-top-ten/)并采取相应的预防措施。 + - [Additional considerations](#additional-considerations) + ## 请勿使用不推荐或者存在漏洞的 Express 版本 -Express 2.x 和 3.x 不再得到维护。不会纠正这些版本中的安全问题和性能问题。请勿使用这些版本!如果您尚未迁移到 V4,请按照[迁移指南](/{{ page.lang }}/guide/migrating-4.html)进行迁移。 +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](/{{ page.lang }}/guide/migrating-4.html) or consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). -还请确保您未使用[安全性更新页面](/{{ page.lang }}/advanced/security-updates.html)中列出的任何存在漏洞的 Express 版本。如果在使用,请更新到某个稳定发行版,首选为最新版本。 +Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](/{{ page.lang }}/advanced/security-updates.html). If you are, update to one of the stable releases, preferably the latest. ## 使用 TLS -如果应用程序处理或传输敏感数据,请使用[传输层安全性](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)。 +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). -您可能很熟悉安全套接字层 (SSL) 加密。[TLS 就是下一代的 SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx) 。换言之,如果您以前使用 SSL,请考虑升级到 TLS。一般而言,我们建议使用 Nginx 来处理 TLS。要获取在 Nginx(和其他服务器)上配置 TLS 的优秀参考信息,请参阅 [Recommended Server Configurations](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations) (Mozilla Wiki)。 +You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). 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). 此外,可以使用一种方便的 [Let's Encrypt](https://letsencrypt.org/about/) 工具来获取免费的 TLS 证书,这是由[因特网安全研究组 (ISRG)](https://letsencrypt.org/isrg/) 提供的免费、自动化的开放式认证中心 (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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## 使用 Helmet [Helmet](https://www.npmjs.com/package/helmet) 通过适当地设置 HTTP 头,帮助您保护应用程序避免一些众所周知的 Web 漏洞。 -Helmet 实际上只使用以下九个较小中间件函数的集合,这些功能用于设置与安全相关的 HTTP 头: +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: -* [csp](https://github.com/helmetjs/csp) 用于设置 `Content-Security-Policy` 头,帮助抵御跨站点脚本编制攻击和其他跨站点注入攻击。 -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) 用于移除 `X-Powered-By` 头。 -* [hsts](https://github.com/helmetjs/hsts) 用于设置 `Strict-Transport-Security` 头,实施安全的服务器连接 (HTTP over SSL/TLS)。 -* [ieNoOpen](https://github.com/helmetjs/ienoopen) 用于为 IE8+ 设置 `X-Download-Options`。 -* [noCache](https://github.com/helmetjs/nocache) 用于设置 `Cache-Control` 和 Pragma 头,以禁用客户端高速缓存。 -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) 用于设置 `X-Content-Type-Options`,以防止攻击者以 MIME 方式嗅探浏览器发出的响应中声明的 content-type。 -* [frameguard](https://github.com/helmetjs/frameguard) 用于设置 `X-Frame-Options` 头,提供 [clickjacking](https://www.owasp.org/index.php/Clickjacking) 保护。 -* [xssFilter](https://github.com/helmetjs/x-xss-protection) 用于设置 `X-XSS-Protection`,在最新的 Web 浏览器中启用跨站点脚本编制 (XSS) 过滤器。 +- `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 +- `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 +- `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 + +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. 像安装其他模块一样安装 Helmet: ```bash -$ npm install --save helmet +$ npm install helmet ``` 然后将其用于您的代码: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### 至少禁用 X-Powered-By 头 +## Reduce fingerprinting -如果不希望使用 Helmet,那么至少应禁用 `X-Powered-By` 头。攻击者可能会使用该头(缺省情况下已启用)来检测运行 Express 的应用程序,然后发动针对特定目标的攻击。 +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. -所以,最佳实践是使用 `app.disable()` 方法禁用此头: +By default, Express sends the `X-Powered-By` response header that you can +disable using the `app.disable()` method: ```js app.disable('x-powered-by') ``` -如果使用 `helmet.js`,它会为您执行此功能。 +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## 安全地使用 cookie @@ -81,16 +175,16 @@ app.disable('x-powered-by') 有两个主要的中间件 cookie 会话模块: -* [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` 中间件。 +- [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` 中间件。 -这两个模块之间的主要差异是它们保存 cookie 会话数据的方式。[express-session](https://www.npmjs.com/package/express-session) 中间件将会话数据存储在服务器上;它仅将会话标识(而非会话数据)保存在 cookie 中。缺省情况下,它使用内存中存储,并不旨在用于生产环境。在生产环境中,需要设置可扩展的会话存储;请参阅[兼容的会话存储](https://github.com/expressjs/session#compatible-session-stores)列表。 +The main difference between these two modules is how they save cookie session data. 这两个模块之间的主要差异是它们保存 cookie 会话数据的方式。[express-session](https://www.npmjs.com/package/express-session) 中间件将会话数据存储在服务器上;它仅将会话标识(而非会话数据)保存在 cookie 中。缺省情况下,它使用内存中存储,并不旨在用于生产环境。在生产环境中,需要设置可扩展的会话存储;请参阅[兼容的会话存储](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) 中间件实现 cookie 支持的存储:它将整个会话序列化到 cookie 中,而不只是会话键。仅当会话数据相对较小,且易于编码为原语值(而不是对象)时,才使用此中间件。尽管假设浏览器支持每个 cookie 至少 4096 字节以确保不会超过限制,但是每个域的大小不会超过 4093 字节。另外请注意,客户机可以访问 cookie 数据,所以,如果有任何理由将其保持安全或隐藏状态,那么 express-session 可能是更好的选择。 +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 名称 -使用缺省会话 cookie 名称会使应用程序对攻击敞开大门。`X-Powered-By` 之类的值会造成问题:潜在攻击者可以利用这样的值对服务器采集“指纹”,并相应地确定攻击目标。 +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 名称;例如,使用 [express-session](https://www.npmjs.com/package/express-session) 中间件: @@ -100,19 +194,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### 设置 cookie 安全性选项 设置以下 cookie 选项来增强安全性: -* `secure` - 确保浏览器只通过 HTTPS 发送 cookie。 -* `httpOnly` - 确保 cookie 只通过 HTTP(S)(而不是客户机 JavaScript)发送,这有助于防御跨站点脚本编制攻击。 -* `domain` - 表示 cookie 的域;用于和请求 URL 的服务器的域进行比较。如果匹配,那么接下来检查路径属性。 -* `path` - 表示 cookie 的路径;用于和请求路径进行比较。如果路径和域都匹配,那么在请求中发送 cookie。 -* `expires` - 用于为持久性 cookie 设置到期日期。 +- `secure` - 确保浏览器只通过 HTTPS 发送 cookie。 +- `httpOnly` - 确保 cookie 只通过 HTTP(S)(而不是客户机 JavaScript)发送,这有助于防御跨站点脚本编制攻击。 +- `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` - 表示 cookie 的路径;用于和请求路径进行比较。如果路径和域都匹配,那么在请求中发送 cookie。 If this and domain match, then send the cookie in the request. +- `expires` - 用于为持久性 cookie 设置到期日期。 以下是使用 [cookie-session](https://www.npmjs.com/package/cookie-session) 中间件的示例: @@ -132,23 +225,59 @@ app.use(session({ 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. + +[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) + +## 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. + +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` + +If you want to stay more secure, consider [Snyk](https://snyk.io/). -以下是来自非常出色的 [Node.js 安全核对表](https://blog.risingstack.com/node-js-security-checklist/)的一些进一步建议。请参阅此博客帖子以了解关于这些建议的所有详细信息: +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: -* 实施速率限制,防止针对认证的暴力攻击。实现这一点的一种方式是使用 [StrongLoop API ](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/)来强制实施速率限制策略。或者,可以使用诸如 [express-limiter](https://www.npmjs.com/package/express-limiter) 的中间件,但是这样做需要对代码作些修改。 -* 始终过滤和净化用户输入,防御跨站点脚本编制 (XSS) 和命令注入攻击。 -* 使用参数化查询或预编译的语句来防御 SQL 注入攻击。 -* 使用开源的 [sqlmap](http://sqlmap.org/) 工具来检测应用程序中的 SQL 注入漏洞。 -* 使用 [nmap](https://nmap.org/) 和 [sslyze](https://github.com/nabla-c0d3/sslyze) 工具来测试 SSL 密码、密钥和重新协商的配置以及证书的有效性。 -* 使用 [safe-regex](https://www.npmjs.com/package/safe-regex) 来确保正则表达式不易受到[正则表达式拒绝服务](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻击。 +```bash +$ npm install -g snyk +$ cd your-app +``` + +Use this command to test your application for vulnerabilities: + +```bash +$ snyk test +``` + +### 避免其他已知的漏洞 + +关注 [Node 安全项目](https://npmjs.com/advisories)公告,这可能会影响 Express 或应用程序使用的其他模块。一般而言,Node 安全项目是有关 Node 安全性的知识和工具的出色资源。 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. + +## 其他注意事项 -## 避免其他已知的漏洞 +以下是来自非常出色的 [Node.js 安全核对表](https://blog.risingstack.com/node-js-security-checklist/)的一些进一步建议。请参阅此博客帖子以了解关于这些建议的所有详细信息: Refer to that blog post for all the details on these recommendations: -关注 [Node 安全项目](https://npmjs.com/advisories)公告,这可能会影响 Express 或应用程序使用的其他模块。一般而言,Node 安全项目是有关 Node 安全性的知识和工具的出色资源。 +- 始终过滤和净化用户输入,防御跨站点脚本编制 (XSS) 和命令注入攻击。 +- 使用参数化查询或预编译的语句来防御 SQL 注入攻击。 +- 使用开源的 [sqlmap](http://sqlmap.org/) 工具来检测应用程序中的 SQL 注入漏洞。 +- 使用 [nmap](https://nmap.org/) 和 [sslyze](https://github.com/nabla-c0d3/sslyze) 工具来测试 SSL 密码、密钥和重新协商的配置以及证书的有效性。 +- 使用 [safe-regex](https://www.npmjs.com/package/safe-regex) 来确保正则表达式不易受到[正则表达式拒绝服务](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻击。 -最后说明一点,和任何其他 Web 应用程序一样,Express 应用程序也容易受到各种基于 Web 的攻击。请熟悉已知的 [Web 漏洞](https://www.owasp.org/www-project-top-ten/)并采取相应的预防措施。 +[helmet]: <如果使用 `helmet.js`,它会为您执行此功能。> \ No newline at end of file diff --git a/zh-cn/advanced/developing-template-engines.md b/zh-cn/advanced/developing-template-engines.md old mode 100755 new mode 100644 index 1fbdd2cfdc..4bdf5d8030 --- a/zh-cn/advanced/developing-template-engines.md +++ b/zh-cn/advanced/developing-template-engines.md @@ -1,15 +1,15 @@ --- layout: page title: 为 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. menu: advanced -lang: zh-cn -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. +lang: en +redirect_from: " " --- # 为 Express 开发模板引擎 -可以使用 `app.engine(ext, callback)` 方法创建自己的模板引擎。`ext` 表示文件扩展名,而 `callback` 表示模板引擎函数,它接受以下项作为参数:文件位置、选项对象和回调函数。 +可以使用 `app.engine(ext, callback)` 方法创建自己的模板引擎。`ext` 表示文件扩展名,而 `callback` 表示模板引擎函数,它接受以下项作为参数:文件位置、选项对象和回调函数。 `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. 以下代码示例实现非常简单的模板引擎以呈现 `.ntl` 文件。 @@ -17,9 +17,10 @@ description: Learn how to develop custom template engines for Express.js using a const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

      ${options.message}

      `) return callback(null, rendered) }) @@ -28,16 +29,19 @@ app.set('views', './views') // specify the views directory app.set('view engine', 'ntl') // register the template engine ``` -应用程序现在能够呈现 `.ntl` 文件。在 `views` 目录中创建名为 `index.ntl` 且包含以下内容的文件: +Your app will now be able to render `.ntl` files. 应用程序现在能够呈现 `.ntl` 文件。在 `views` 目录中创建名为 `index.ntl` 且包含以下内容的文件: ```pug #title# #message# ``` + 然后,在应用程序中创建以下路径: + ```js app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -您向主页发出请求时,`index.ntl` 将呈现为 HTML。 + +您向主页发出请求时,`index.ntl` 将呈现为 HTML。 \ No newline at end of file diff --git a/zh-cn/advanced/healthcheck-graceful-shutdown.md b/zh-cn/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..36d5592626 --- /dev/null +++ b/zh-cn/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: en +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### 示例 + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/zh-cn/advanced/security-updates.md b/zh-cn/advanced/security-updates.md old mode 100755 new mode 100644 index 6ccb9ba822..b3aca83e3e --- a/zh-cn/advanced/security-updates.md +++ b/zh-cn/advanced/security-updates.md @@ -1,47 +1,90 @@ --- layout: page title: Express 安全性更新 +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced -lang: zh-cn -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +lang: en +redirect_from: " " --- # 安全更新
      +Node.js vulnerabilities directly affect Express. Node.js 漏洞直接影响 Express。因此,请[监视 Node.js 漏洞](https://nodejs.org /en/blog/vulnerability/)并确保使用最新稳定版的 Node.js。 +
      以下列举了在指定版本更新中修复的 Express 漏洞。 +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径披露漏洞 - * 4.10.7 - * 在 `express.static`([公告](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中修复了开放重定向漏洞。 - * 4.8.8 - * 在 `express.static`([公告](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 在某些情况下可能会泄漏 `fd`,这会影响 `express.static` 和 `res.sendfile`。恶意请求会导致 `fd` 泄漏并最终导致 `EMFILE` 错误和服务器无响应。 - * 4.8.0 - * 查询字符串中具有极高数量索引的稀疏数组会导致进程耗尽内存并使服务器崩溃。 - * 极端嵌套查询字符串对象会导致进程阻塞并使服务器暂时无响应。 +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径披露漏洞 +- 4.10.7 + - 在 `express.static`([公告](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中修复了开放重定向漏洞。 +- 4.8.8 + - 在 `express.static`([公告](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 在某些情况下可能会泄漏 `fd`,这会影响 `express.static` 和 `res.sendfile`。恶意请求会导致 `fd` 泄漏并最终导致 `EMFILE` 错误和服务器无响应。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 4.8.0 + - 查询字符串中具有极高数量索引的稀疏数组会导致进程耗尽内存并使服务器崩溃。 + - 极端嵌套查询字符串对象会导致进程阻塞并使服务器暂时无响应。 ## 3.x - * 3.19.1 - * 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径披露漏洞 - * 3.19.0 - * 在 `express.static`([公告](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中修复了开放重定向漏洞。 - * 3.16.10 - * 在 `express.static` 中修复了目录遍历漏洞。 - * 3.16.6 - * Node.js 0.10 在某些情况下可能会泄漏 `fd`,这会影响 `express.static` 和 `res.sendfile`。恶意请求会导致 `fd` 泄漏并最终导致 `EMFILE` 错误和服务器无响应。 - * 3.16.0 - * 查询字符串中具有极高数量索引的稀疏数组会导致进程耗尽内存并使服务器崩溃。 - * 极端嵌套查询字符串对象会导致进程阻塞并使服务器暂时无响应。 - * 3.3.0 - * 不受支持的方法覆盖尝试的 404 响应易于受到跨站点脚本编制攻击。 +
      + **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. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
      + +- 3.19.1 + - 修复了 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路径披露漏洞 +- 3.19.0 + - 在 `express.static`([公告](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中修复了开放重定向漏洞。 +- 3.16.10 + - 在 `express.static` 中修复了目录遍历漏洞。 +- 3.16.6 + - Node.js 0.10 在某些情况下可能会泄漏 `fd`,这会影响 `express.static` 和 `res.sendfile`。恶意请求会导致 `fd` 泄漏并最终导致 `EMFILE` 错误和服务器无响应。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 3.16.0 + - 查询字符串中具有极高数量索引的稀疏数组会导致进程耗尽内存并使服务器崩溃。 + - 极端嵌套查询字符串对象会导致进程阻塞并使服务器暂时无响应。 +- 3.3.0 + - 不受支持的方法覆盖尝试的 404 响应易于受到跨站点脚本编制攻击。 \ No newline at end of file diff --git a/zh-cn/api.md b/zh-cn/api.md old mode 100755 new mode 100644 index be4562f33c..a7d47e3261 --- a/zh-cn/api.md +++ b/zh-cn/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - API 参考 -lang: zh-cn -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +version: 5x +title: Express 5.x - API 参考 +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. +lang: en +redirect_from: " " --- -
      - -

      4.x API

      - - - {% include api/en/4x/express.md %} +
      +

      5.x API

      + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
      diff --git a/zh-cn/changelog/index.md b/zh-cn/changelog/index.md new file mode 100644 index 0000000000..d64a7855b7 --- /dev/null +++ b/zh-cn/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: en +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
      + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
        +
      • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
        +
      • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
        +
      • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
        +
      • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
      • + +
      • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
      • + +
      • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
      • + +
      • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
      • + +
      • + Starting with this version, Express supports Node.js 18.x. +
      • + +
      • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
      • + +
      • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
      • + +
      • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
      • + +
      • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
      • + +
      • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
      • + +
      • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
        +
      • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
        +
      • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
      • + +
      • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
      • + +
      • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
      • + +
      • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
      • + +
      • + Starting with this version, Express supports Node.js 14.x. +
      • + +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
        +
      • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
        +
      • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
      • + +
      • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
      • + +
      • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
      • + +
      • + Starting with this version, Express supports Node.js 10.x and 12.x. +
      • + +
      • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
      • + +
      • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
        +
      • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
        +
      • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
      • + +
      • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
      • + +
      • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
        +
      • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
        +
      • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
        +
      • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
      • + +
      • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
      • + +
      • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
      • + +
      • + Starting with this version, Express supports Node.js 8.x. +
      • + +
      • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
      • + +
      • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
      • + +
      • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
      • + +
      • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
      • + +
      • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
        +
      • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
      • + +
      • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
      • + +
      • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
        +
      • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
        +
      • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
      • + +
      • + Fix error when `res.set` cannot add charset to `Content-Type`. +
      • + +
      • + Fix missing `` in HTML document. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
        +
      • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
        +
      • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
        +
      • + Starting with this version, Express supports Node.js 7.x. +
      • + +
      • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
      • + +
      • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
      • + +
      • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
        +
      • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
        +
      • + Starting with this version, Express supports Node.js 6.x. +
      • + +
      • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
      • + +
      • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
      • + +
      • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
      • + +
      • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
      • + +
      • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
      • + +
      • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
      • + +
      • + IP address resolution with proxies has been greatly improved. +
      • + +
      • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
      • +
      + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
      diff --git a/zh-cn/guide/behind-proxies.md b/zh-cn/guide/behind-proxies.md old mode 100755 new mode 100644 index 96584cebba..473ea7a608 --- a/zh-cn/guide/behind-proxies.md +++ b/zh-cn/guide/behind-proxies.md @@ -1,20 +1,22 @@ --- layout: page title: 代理背后的 Express +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. menu: guide -lang: zh-cn -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. +lang: en +redirect_from: " " --- # 代理背后的 Express -在代理背后运行 Express 应用程序时,可使用 [app.set()](/{{ page.lang }}/4x/api.html#app.set) 将应用程序变量 `trust proxy` 设置为下表中所列的某个值。 +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.
      -尽管不设置应用程序变量 `trust proxy` 该应用程序也不会运行失败,但是它会误将代理的 IP 地址注册为客户机 IP 地址(除非配置了 `trust proxy`)。 +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.
      +在代理背后运行 Express 应用程序时,可使用 [app.set()](/{{ page.lang }}/4x/api.html#app.set) 将应用程序变量 `trust proxy` 设置为下表中所列的某个值。 + @@ -23,15 +25,23 @@ description: Learn how to configure Express.js applications to work correctly be - + - +
      类型
      如果为 `true`,那么客户机的 IP 地址将用作 `X-Forwarded-*` 头中最左侧的条目。 如果为 `false`,那么该应用程序将被视为直接面对因特网,而客户机的 IP 地址则派生自 `req.connection.remoteAddress`。这是缺省设置。 + + +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. + +
      +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. +
      IP 地址IP addresses -要信任的 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` +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: + +- 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` 您可以按以下某种方法设置 IP 地址: @@ -42,20 +52,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -如果指定 IP 地址或子网,那么会在地址确定过程中排除这些项,而将最接近应用程序服务器的不受信任的 IP 地址确定为客户机的 IP 地址。 +如果指定 IP 地址或子网,那么会在地址确定过程中排除这些项,而将最接近应用程序服务器的不受信任的 IP 地址确定为客户机的 IP 地址。 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. +
      数字 -信任来自正面代理服务器的第 `n` 个中继段,以此作为客户机。 +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. + +
      +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. +
      函数Function -定制信任实现。仅当您知道自己要做什么时,方可使用该选项。 - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -63,20 +77,22 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
      -设置非 `false` `trust proxy` 值会导致三个重大变化: +Enabling `trust proxy` will have the following impact:
      • [req.hostname](/{{ page.lang }}/api.html#req.hostname) 的值派生自 `X-Forwarded-Host` 头中设置的值(可以由客户机或代理设置此值)。
      • `X-Forwarded-Proto` 可以由逆向代理设置,以告知应用程序:它是 `https` 还是 `http`,或者甚至是无效名称。该值由 [req.protocol](/{{ page.lang }}/api.html#req.protocol) 反映。 + This value is reflected by [req.protocol](/{{ page.lang }}/api.html#req.protocol).
      • [req.ip](/{{ page.lang }}/api.html#req.ip) 和 [req.ips](/{{ page.lang }}/api.html#req.ips) 值由 `X-Forwarded-For` 的地址列表填充。
      -`trust proxy` 设置由使用 [proxy-addr](https://www.npmjs.com/package/proxy-addr) 包实现。有关更多信息,请参阅其文档。 +`trust proxy` 设置由使用 [proxy-addr](https://www.npmjs.com/package/proxy-addr) 包实现。有关更多信息,请参阅其文档。 For more information, see its documentation. diff --git a/zh-cn/guide/database-integration.md b/zh-cn/guide/database-integration.md old mode 100755 new mode 100644 index c48d891c5e..90f708f3a1 --- a/zh-cn/guide/database-integration.md +++ b/zh-cn/guide/database-integration.md @@ -1,32 +1,35 @@ --- layout: page title: Express 数据库集成 +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide -lang: zh-cn -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +lang: en +redirect_from: " " --- # 数据库集成 -要将数据库连接到 Express 应用程序,只需在该应用程序中为数据库装入相应的 Node.js 驱动程序。本文档简要说明如何在 Express 应用程序中为数据库系统添加和使用某些最流行的 Node.js 模块: - -* [Cassandra](#cassandra) -* [Couchbase](#couchbase) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongodb) -* [Neo4j](#neo4j) -* [Oracle](#oracle) -* [PostgreSQL](#postgresql) -* [Redis](#redis) -* [SQL Server](#sql-server) -* [SQLite](#sqlite) -* [Elasticsearch](#elasticsearch) +要将数据库连接到 Express 应用程序,只需在该应用程序中为数据库装入相应的 Node.js 驱动程序。本文档简要说明如何在 Express 应用程序中为数据库系统添加和使用某些最流行的 Node.js 模块: This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app: + +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongodb) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgresql) +- [Redis](#redis) +- [SQL Server](#sql-server) +- [SQLite](#sqlite) +- [Elasticsearch](#elasticsearch)
      + 这些数据库驱动程序是众多可用数据库驱动程序的一部分。要了解其他选项,请在 [npm](https://www.npmjs.com/) 站点上搜索。 + For other options, +search on the [npm](https://www.npmjs.com/) site.
      ## Cassandra @@ -193,7 +196,7 @@ connection.end() $ npm install mongodb ``` -### 示例(v2.*) +### 示例(v2.\*) ```js const MongoClient = require('mongodb').MongoClient @@ -209,7 +212,7 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { }) ``` -### 示例(v3.*) +### 示例(v3.\*) ```js const MongoClient = require('mongodb').MongoClient @@ -231,27 +234,31 @@ MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { ## Neo4j -**模块**:[apoc](https://github.com/hacksparrow/apoc) +**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver) ### 安装 ```bash -$ npm install apoc +$ npm install neo4j-driver ``` ### 示例 ```js -const apoc = require('apoc') - -apoc.query('match (n) return n').exec().then( - (response) => { - console.log(response) - }, - (fail) => { - console.log(fail) - } -) +const neo4j = require('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 @@ -260,7 +267,7 @@ apoc.query('match (n) return n').exec().then( ### 安装 - 注意: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation). +注意: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation). ```bash $ npm install oracledb @@ -302,7 +309,7 @@ getEmployee(101) ## PostgreSQL -**模块**:[pg](https://github.com/brianc/node-postgres) +**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise) ### 安装 diff --git a/zh-cn/guide/debugging.md b/zh-cn/guide/debugging.md old mode 100755 new mode 100644 index 7bf705caf1..f5051d2919 --- a/zh-cn/guide/debugging.md +++ b/zh-cn/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: 调试 Express +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide -lang: zh-cn -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +lang: en +redirect_from: " " --- # 调试 Express @@ -18,7 +18,7 @@ $ DEBUG=express:* node index.js 在 Windows 上,使用对应的命令。 ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` 在 [Express 生成器](/{{ page.lang }}/starter/generator.html)所生成的缺省应用程序上运行此命令将显示以下输出: @@ -59,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -87,7 +87,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`,以此类推。 Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on. ## `express` 生成的应用程序 @@ -104,3 +104,27 @@ $ DEBUG=sample-app:* node ./bin/www ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/zh-cn/guide/error-handling.md b/zh-cn/guide/error-handling.md old mode 100755 new mode 100644 index 6da4d06770..d96b5025a5 --- a/zh-cn/guide/error-handling.md +++ b/zh-cn/guide/error-handling.md @@ -1,15 +1,193 @@ --- layout: page title: Express 错误处理 +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide -lang: zh-cn -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +lang: en +redirect_from: " " --- # 错误处理 -错误处理中间件函数的定义方式与其他中间件函数基本相同,差别在于错误处理函数有四个自变量而不是三个:`(err, req, res, next)`:例如: +_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. + +## 如果将错误传递到 `next()` 且未在错误处理程序中进行处理,那么该错误将由内置的错误处理程序处理;错误将写入客户机的堆栈跟踪内。堆栈跟踪不包含在生产环境中。 + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + +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: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +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: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +如果将任何项传递到 `next()` 函数(除了字符串 `'route'`),那么 Express 会将当前请求视为处于错误状态,并跳过所有剩余的非错误处理路由和中间件函数。如果您希望以某种方式处理此错误,必须如下一节中所述创建一个错误处理路由。 + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. For example: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. For example: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +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('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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 随附一个内置的错误处理程序,负责处理应用程序中可能遇到的任何错误。这个缺省的错误处理中间件函数添加在中间件函数集的末尾。 This default error-handling middleware function is added at the end of the middleware function stack. + +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. + +
      +将环境变量 `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. + +如果在开始写响应之后调用 `next()` 时出错(例如,如果在以流式方式将响应传输到客户机时遇到错误),Express 缺省错误处理程序会关闭连接并使请求失败。 + +因此,在添加定制错误处理程序时,如果头已发送到客户机,您可能希望委托给 Express 中的缺省错误处理机制处理: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## Writing error handlers + +错误处理中间件函数的定义方式与其他中间件函数基本相同,差别在于错误处理函数有四个自变量而不是三个:`(err, req, res, next)`:例如: For example: ```js app.use((err, req, res, next) => { @@ -24,7 +202,10 @@ app.use((err, req, res, next) => { const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic @@ -33,13 +214,19 @@ app.use((err, req, res, next) => { 中间件函数中的响应可以采用您首选的任何格式,例如,HTML 错误页、简单消息或 JSON 字符串。 -出于组织(和更高级框架)的目的,可以定义若干错误处理中间件函数,这和对常规中间件函数的处理很相似。例如,如果您希望为使用 `XHR` 发出的请求以及未使用此对象发出的请求定义错误处理程序,可以使用以下命令: +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: ```js const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -57,6 +244,8 @@ function logErrors (err, req, res, next) { 也是在此示例中,`clientErrorHandler` 定义如下,错误会显式传递到下一项: +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) { if (req.xhr) { @@ -66,6 +255,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + “catch-all”`errorHandler` 函数可以如下实现: ```js @@ -75,17 +265,16 @@ function errorHandler (err, req, res, next) { } ``` -如果将任何项传递到 `next()` 函数(除了字符串 `'route'`),那么 Express 会将当前请求视为处于错误状态,并跳过所有剩余的非错误处理路由和中间件函数。如果您希望以某种方式处理此错误,必须如下一节中所述创建一个错误处理路由。 - -如果一个路由处理程序具有多个回调函数,那么可以使用 `route` 参数跳至下一个路由处理程序。例如: +如果一个路由处理程序具有多个回调函数,那么可以使用 `route` 参数跳至下一个路由处理程序。例如: For example: ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -94,32 +283,11 @@ app.get('/a_route_behind_paywall', }) }) ``` + 在此示例中,将跳过 `getPaidContent` 处理程序,而将继续执行 `/a_route_behind_paywall` 的 `app` 中所有剩余的处理程序。
      -对 `next()` 和 `next(err)` 的调用会表明当前处理程序是否完整以及处于何种状态。`next(err)` 将跳过链中所有剩余的处理程序(设置为按上述方式处理错误的处理程序除外)。 -
      - -## 缺省错误处理程序 -Express 随附一个内置的错误处理程序,负责处理应用程序中可能遇到的任何错误。这个缺省的错误处理中间件函数添加在中间件函数集的末尾。 - -如果将错误传递到 `next()` 且未在错误处理程序中进行处理,那么该错误将由内置的错误处理程序处理;错误将写入客户机的堆栈跟踪内。堆栈跟踪不包含在生产环境中。 - -
      -将环境变量 `NODE_ENV` 设置为 `production`,以生产方式运行此应用程序。 +对 `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.
      - -如果在开始写响应之后调用 `next()` 时出错(例如,如果在以流式方式将响应传输到客户机时遇到错误),Express 缺省错误处理程序会关闭连接并使请求失败。 - -因此,在添加定制错误处理程序时,如果头已发送到客户机,您可能希望委托给 Express 中的缺省错误处理机制处理: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/zh-cn/guide/migrating-4.md b/zh-cn/guide/migrating-4.md old mode 100755 new mode 100644 index 8a3d0a8dad..c5fd488741 --- a/zh-cn/guide/migrating-4.md +++ b/zh-cn/guide/migrating-4.md @@ -1,17 +1,17 @@ --- layout: page title: 迁移到 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. menu: guide -lang: zh-cn -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. +lang: en +redirect_from: " " --- # 迁移到 Express 4

      概述

      -Express 4 对 Express 3 进行了重大更改,这意味着,如果您在现有 Express 3 应用程序的依赖项中更新了 Express 版本,那么该应用程序将无法工作。 +Express 4 is a breaking change from Express 3. Express 4 对 Express 3 进行了重大更改,这意味着,如果您在现有 Express 3 应用程序的依赖项中更新了 Express 版本,那么该应用程序将无法工作。 本文讲述: @@ -26,23 +26,26 @@ Express 4 对 Express 3 进行了重大更改,这意味着,如果您在现 Express 4 中进行了若干重大更改: 另请参阅: -* [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)。 +- [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)。

      对 Express 核心和中间件系统的更改。

      -Express 4 不再依赖于 Connect,从其核心移除了所有内置的中间件(除了 `express.static` 函数)。这意味着 Express 现在是独立的路由和中间件 Web 框架,Express 的版本控制和发行不受中间件更新的影响。 +Express 4 不再依赖于 Connect,从其核心移除了所有内置的中间件(除了 `express.static` 函数)。这意味着 Express 现在是独立的路由和中间件 Web 框架,Express 的版本控制和发行不受中间件更新的影响。 This means that +Express is now an independent routing and middleware web framework, and +Express versioning and releases are not affected by middleware updates. -由于没有内置中间件,因此您必须显式添加所需的所有中间件才能运行应用程序。只需执行以下步骤: +由于没有内置中间件,因此您必须显式添加所需的所有中间件才能运行应用程序。只需执行以下步骤: Simply follow these steps: 1. 安装模块:`npm install --save ` 2. 在应用程序中需要此模块:`require('module-name')` @@ -51,7 +54,7 @@ Express 4 不再依赖于 Connect,从其核心移除了所有内置的中间 下表列出了 Express 3 中间件及其在 Express 4 中的对应组件。 - + @@ -83,23 +86,26 @@ Express 4 不再依赖于 Connect,从其核心移除了所有内置的中间 -
      Express 3Express 4
      Express 3Express 4
      express.bodyParser body-parser + multer
      serve-index
      express.static serve-static
      +
      可参考 Express 4 中间件的[完整列表](https://github.com/senchalabs/connect#middleware)。 -在大多数情况下,可以将旧的 V3 中间件替换为 Express 4 的对应组件。有关详细信息,请参阅 GitHub 中的模块文档。 +在大多数情况下,可以将旧的 V3 中间件替换为 Express 4 的对应组件。有关详细信息,请参阅 GitHub 中的模块文档。 For details, see the module documentation in +GitHub.

      app.use 可以使用参数

      在 V4 中,您可以使用变量参数来定义装入中间件函数的路径,然后从路由处理程序读取参数的值。 例如: +For example: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

      路由系统

      @@ -109,31 +115,35 @@ app.use('/book/:id', function (req, res, next) { 定义路由的方式并未改变,但是路由系统新增了两个功能,用于帮助组织路由: {: .doclist } -* 一个新方法 `app.route()`,用于为路由路径创建可链接的路由处理程序。 -* 一个新类 `express.Router`,用于创建可安装的模块化路由处理程序。 + +- 一个新方法 `app.route()`,用于为路由路径创建可链接的路由处理程序。 +- 一个新类 `express.Router`,用于创建可安装的模块化路由处理程序。

      app.route() 方法

      -新的 `app.route()` 方法使您可以为路由路径创建可链接的路由处理程序。创建模块化路由很有帮助,因为在单一位置指定路径,所以可以减少冗余和输入错误。有关路由的更多信息,请参阅 [`Router()` 文档](/{{ page.lang }}/4x/api.html#router)。 +新的 `app.route()` 方法使您可以为路由路径创建可链接的路由处理程序。创建模块化路由很有帮助,因为在单一位置指定路径,所以可以减少冗余和输入错误。有关路由的更多信息,请参阅 [`Router()` 文档](/{{ page.lang }}/4x/api.html#router)。 Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more +information about routes, see [`Router()` documentation](/{{ page.lang }}/4x/api.html#router). 以下是使用 `app.route()` 函数定义的链式路由处理程序的示例。 ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ```

      express.Router

      -有助于组织路由的另一个功能是新类 `express.Router`,可用于创建可安装的模块化路由处理程序。`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. 有助于组织路由的另一个功能是新类 `express.Router`,可用于创建可安装的模块化路由处理程序。`Router` 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。 以下示例将路由器创建为模块,在其中装入中间件,定义一些路由,然后安装在主应用程序的路径中。 @@ -144,16 +154,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -165,7 +175,7 @@ module.exports = router ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -179,7 +189,7 @@ app.use('/birds', birds) 下表列出 Express 4 中虽小但重要的其他更改: - + @@ -192,7 +202,10 @@ app.use('/birds', birds) `http.createServer()` @@ -200,7 +213,9 @@ app.use('/birds', birds) `app.configure()` @@ -280,15 +295,18 @@ app.use('/birds', birds) `res.setHeader('Set-Cookie', val)` -
      对象 描述
      + 不再需要 `http` 模块,除非您要直接使用它 (socket.io/SPDY/HTTPS)。可以使用 `app.listen()` 函数来启动此应用程序。 + The app can be started by using the +`app.listen()` function.
      +The `app.configure()` function has been removed. 已移除 `app.configure()` 函数。使用 `process.env.NODE_ENV` 或 `app.get('env')` 功能来检测环境并相应配置该应用程序。 +
      +Functionality is now limited to setting the basic cookie value. 功能现在已限制为设置基本 cookie 值。将 `res.cookie()` 用于增添的功能。 +
      +

      应用程序迁移示例

      以下是将 Express 3 应用程序迁移到 Express 4 的示例。 涉及的文件包括 `app.js` 和 `package.json`。 +下一步,将 `package.json` 文件中的 `"start": "node ./bin/www"` 更改为 `"start": "node app.js"`。

      V3 应用程序 @@ -327,7 +345,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -363,9 +381,11 @@ $ npm install serve-favicon morgan method-override express-session body-parser m 对 `app.js` 进行以下更改: -1. Express 内置中间件函数 `express.favicon`、`express.logger`、`express.methodOverride`、`express.session`、`express.bodyParser` 和 `express.errorHandler` 不再可用于 `express` 对象。您必须手动安装其替代项,然后在应用程序中装入。 +1. Express 内置中间件函数 `express.favicon`、`express.logger`、`express.methodOverride`、`express.session`、`express.bodyParser` 和 `express.errorHandler` 不再可用于 `express` 对象。您必须手动安装其替代项,然后在应用程序中装入。 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. + 不再需要装入 `app.router` 函数。它不是有效的 Express 4 应用程序对象,所以移除了 `app.use(app.router);` 代码。 3. 确保以正确顺序装入中间件函数 - 在装入应用程序路由之后装入 `errorHandler`。 @@ -388,7 +408,7 @@ $ npm install serve-favicon morgan method-override express-session body-parser m "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -399,7 +419,7 @@ $ npm install serve-favicon morgan method-override express-session body-parser m

      app.js

      -随后,移除无效代码,装入所需中间件,并根据需要进行其他更改。`app.js` 文件如下: +随后,移除无效代码,装入所需中间件,并根据需要进行其他更改。`app.js` 文件如下: The `app.js` file will look like this: ```js var http = require('http') @@ -453,7 +473,7 @@ server.listen(app.get('port'), () => { 除非您需要直接使用 `http` 模块 (socket.io/SPDY/HTTPS),否则不需要将其装入,可按以下方式启动此应用程序: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -462,7 +482,7 @@ app.listen(app.get('port'), function () {

      运行应用程序

      -迁移过程完成,此应用程序现在是 Express 4 版本。要进行确认,可使用以下命令启动此应用程序: +迁移过程完成,此应用程序现在是 Express 4 版本。要进行确认,可使用以下命令启动此应用程序: To confirm, start the app by using the following command: ```bash $ node . @@ -485,12 +505,14 @@ $ npm uninstall -g express 根据您的文件和目录特权的配置方式,可能需要使用 `sudo` 来运行此命令。 立即安装新的生成器: +Now install the new generator: + ```bash $ npm install -g express-generator ``` 根据您的文件和目录特权的配置方式,可能需要使用 `sudo` 来运行此命令。 - +立即安装新的生成器: 现在,系统上的 `express` 命令已更新到 Express 4 生成器。 @@ -499,9 +521,10 @@ $ npm install -g express-generator 命令选项和用法大体保持相同,但也存在以下例外: {: .doclist } -* 已移除 `--sessions` 选项。 -* 已移除 `--jshtml` 选项。 -* 已添加 `--hogan` 选项来支持 [Hogan.js](http://twitter.github.io/hogan.js/)。 + +- 已移除 `--sessions` 选项。 +- 已移除 `--jshtml` 选项。 +- 已添加 `--hogan` 选项来支持 [Hogan.js](http://twitter.github.io/hogan.js/)。

      示例

      @@ -523,16 +546,20 @@ $ npm start 如果查看 `package.json` 文件中的 npm 启动脚本,可以注意到启动应用程序的实际命令是 `node ./bin/www`,而过去在 Express 3 中,该命令是 `node app.js`。 -因为 Express 4 生成器生成的 `app.js` 文件现在是 Node.js 模块,所以不再能够将其作为应用程序独立启动(除非修改代码)。必须在 Node.js 文件中加载此模块,并通过 Node.js 文件启动。在此情况下,Node.js 文件是 `./bin/www`。 +因为 Express 4 生成器生成的 `app.js` 文件现在是 Node.js 模块,所以不再能够将其作为应用程序独立启动(除非修改代码)。必须在 Node.js 文件中加载此模块,并通过 Node.js 文件启动。在此情况下,Node.js 文件是 `./bin/www`。 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 应用程序或启动此应用程序,`bin` 目录或无扩展名的 `www` 文件都不是必需的。它们只是生成器提出的建议,可随意根据自己的需求进行修改。 +对于创建 Express 应用程序或启动此应用程序,`bin` 目录或无扩展名的 `www` 文件都不是必需的。它们只是生成器提出的建议,可随意根据自己的需求进行修改。 They are +just suggestions made by the generator, so feel free to modify them to suit your +needs. 如果不想使用 `www` 目录,而是保持“Express 3 风格”,请删除 `app.js` 文件末尾的 `module.exports = app;` 行,然后将以下代码粘贴在到该位置: ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -543,6 +570,9 @@ var server = app.listen(app.get('port'), function () { var debug = require('debug')('app4') ``` -下一步,将 `package.json` 文件中的 `"start": "node ./bin/www"` 更改为 `"start": "node app.js"`。 - 现在,您已将 `./bin/www` 的功能恢复为 `app.js`。不建议进行此更改,但是此练习可以帮助您理解 `./bin/www` 文件的工作方式,以及为何 `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. diff --git a/zh-cn/guide/migrating-5.md b/zh-cn/guide/migrating-5.md old mode 100755 new mode 100644 index e6201465b1..c3c0ff4a20 --- a/zh-cn/guide/migrating-5.md +++ b/zh-cn/guide/migrating-5.md @@ -1,32 +1,45 @@ --- layout: page title: 迁移到 Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide -lang: zh-cn -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +lang: en +redirect_from: " " --- # 迁移到 Express 5

      概述

      -Express 5.0 仍然处于 α 测试发布阶段,但我们可以在这里先睹为快,了解一下这个发行版中的变化以及如何将 Express 4 应用程序迁移到 Express 5。 +Express 5 与 Express 4 的差异不是很大:对 API 的更改不像 3.0 到 4.0 升级那样大刀阔斧。虽然基本 API 保持相同,但仍有一些重大更改;换言之,如果将现有 Express 4 程序更新为使用 Express 5,那么该程序可能无法工作。 Therefore, an application built with Express 4 might not work if you update it to use Express 5. -Express 5 与 Express 4 的差异不是很大:对 API 的更改不像 3.0 到 4.0 升级那样大刀阔斧。虽然基本 API 保持相同,但仍有一些重大更改;换言之,如果将现有 Express 4 程序更新为使用 Express 5,那么该程序可能无法工作。 +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -要安装最新的 α 测试版以预览 Express 5,请在应用程序根目录中输入以下命令: +```sh +npm install "express@5" +``` + +随后,可以运行自动化测试以查看哪些地方发生故障,然后根据以下列出的更新修复问题。在解决测试故障问题之后,运行应用程序以查看发生哪些错误。如果应用程序使用任何不受支持的方法或属性,您马上就可以发现。 After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported. + +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: -```bash -$ npm install "express@5" --save +```sh +npx @expressjs/codemod upgrade ``` -随后,可以运行自动化测试以查看哪些地方发生故障,然后根据以下列出的更新修复问题。在解决测试故障问题之后,运行应用程序以查看发生哪些错误。如果应用程序使用任何不受支持的方法或属性,您马上就可以发现。 +If you want to run a specific codemod, you can run the following command: -

      Express 5 中的更改

      +```sh +npx @expressjs/codemod name-of-the-codemod +``` -以下是将影响 Express 用户的更改的列表(截至在 α R2)。 -请参阅 [pull request](https://github.com/expressjs/express/pull/2237) 以查看所有计划功能的列表。 +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

      Express 5 中的更改

      **已移除的方法和属性** @@ -38,96 +51,455 @@ $ npm install "express@5" --save
    • req.param(name)
    • res.json(obj, status)
    • res.jsonp(obj, status)
    • +
    • res.redirect('back') and res.location('back')
    • +
    • res.redirect(url, status)
    • res.send(body, status)
    • res.send(status)
    • res.sendfile()
    • +
    • router.param(fn)
    • +
    • express.static.mime
    • +
    • express:router debug logs
    -**已更改** +**改进** -**改进** +**已更改** -

    已移除的方法和属性

    +### 已移除的方法和属性 -如果在应用程序中使用任何已删除的方法或属性,应用程序将崩溃。所以,需要在更新到 V5 之后更改应用程序。 +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.

    app.del()

    -Express 5 不再支持 `app.del()` 函数。如果使用此函数,将抛出错误。要注册 HTTP DELETE 路由,请使用 `app.delete()` 函数。 +Express 5 不再支持 `app.del()` 函数。如果使用此函数,将抛出错误。要注册 HTTP DELETE 路由,请使用 `app.delete()` 函数。 If you use this function, an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead. + +最初之所以使用 `del` 而不是 `delete`,是因为 `delete` 是 JavaScript 中的保留关键字。但在 ECMAScript 6 时,`delete` 和其他保留关键字可以合法地用作属性名称。您可以在此阅读该讨论,这导致我们在此不推荐使用 `app.del` 函数。 However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` -最初之所以使用 `del` 而不是 `delete`,是因为 `delete` 是 JavaScript 中的保留关键字。但在 ECMAScript 6 时,`delete` 和其他保留关键字可以合法地用作属性名称。您可以在此阅读该讨论,这导致我们在此不推荐使用 `app.del` 函数。 +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

    app.param(fn)

    -`app.param(fn)` 特征符用于修改 `app.param(name, fn)` 函数的行为。自 V4.11.0 起不推荐使用该特征符,而 Express 5 完全不再提供支持。 +`app.param(fn)` 特征符用于修改 `app.param(name, fn)` 函数的行为。自 V4.11.0 起不推荐使用该特征符,而 Express 5 完全不再提供支持。 It has been deprecated since v4.11.0, and Express 5 no longer supports it at all.

    复数的方法名称

    -以下方法名称已加复数。在 Express 4 中,使用旧方法时会出现不推荐使用的警告。Express 5 则完全不再支持: +The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all: + +`req.acceptsLanguage()` 由 `req.acceptsLanguages()` 取代。 `req.acceptsCharset()` 由 `req.acceptsCharsets()` 取代。 `req.acceptsEncoding()` 由 `req.acceptsEncodings()` 取代。 -`req.acceptsLanguage()` 由 `req.acceptsLanguages()` 取代。 +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    app.param(name, fn) 的名称中的前置冒号 (:)

    -`app.param(name, fn)` 函数名称中的前置冒号字符 (:) 是 Express 3 的遗留问题,为了向后兼容性,Express 4 提供支持但会显示不推荐使用的提醒。而 Express 5 则静默忽略它,使用不带前置冒号的名称参数。 +`app.param(name, fn)` 函数名称中的前置冒号字符 (:) 是 Express 3 的遗留问题,为了向后兼容性,Express 4 提供支持但会显示不推荐使用的提醒。而 Express 5 则静默忽略它,使用不带前置冒号的名称参数。 Express 5 will silently ignore it and use the name parameter without prefixing it with a colon. 如果您遵循 [app.param](/{{ page.lang }}/4x/api.html#app.param) 的 Express 4 文档进行开发,那么不会影响代码,因为文档中没有提及前置冒号。

    req.param(name)

    -已移除用于检索表单数据的方法,因为这可能引起混淆,而且很危险。现在,您需要在 `req.params`、`req.body` 或 `req.query` 对象中专门寻找提交的参数名称。 +This potentially confusing and dangerous method of retrieving form data has been removed. 已移除用于检索表单数据的方法,因为这可能引起混淆,而且很危险。现在,您需要在 `req.params`、`req.body` 或 `req.query` 对象中专门寻找提交的参数名称。 + +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +```

    res.json(obj, status)

    -Express 5 不再支持特征符 `res.json(obj, status)`。而是设置状态,然后将其链接到 `res.json()` 方法,如下所示:`res.status(status).json(obj)`。 +Express 5 不再支持特征符 `res.json(obj, status)`。而是设置状态,然后将其链接到 `res.json()` 方法,如下所示:`res.status(status).json(obj)`。 Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +```

    res.jsonp(obj, status)

    -Express 5 不再支持特征符 `res.jsonp(obj, status)`。而是设置状态,然后将其链接到 `res.jsonp()` 方法,如下所示:`res.status(status).jsonp(obj)`。 +Express 5 不再支持特征符 `res.jsonp(obj, status)`。而是设置状态,然后将其链接到 `res.jsonp()` 方法,如下所示:`res.status(status).jsonp(obj)`。 Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    + +Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +```

    res.send(body, status)

    -Express 5 不再支持特征符 `res.send(obj, status)`。而是设置状态,然后将其链接到 `res.send()` 方法,如下所示:`res.status(status).send(obj)`。 +Express 5 不再支持特征符 `res.send(obj, status)`。而是设置状态,然后将其链接到 `res.send()` 方法,如下所示:`res.status(status).send(obj)`。 Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +```

    res.send(status)

    -Express 5 不再支持特征符 res.send(status),其中 *`status`* 是数字。而是使用 `res.sendStatus(statusCode)` 函数,它会设置 HTTP 响应头状态码并发送该代码的文字版:“Not Found”、“Internal Server Error”等。 -如果需要使用 `res.send()` 函数来发送数字,请对该数字加上引号以将其转换为字符串,以便 Express 不会将其解释为尝试使用不受支持的旧特征符。 +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. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +```

    res.sendfile()

    在 Express 5 中,`res.sendfile()` 函数已由驼峰式大小写版本 `res.sendFile()` 替换。 +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. + +

    express.static.mime

    + +In Express 5, `mime` is no longer an exported property of the `static` field. +Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    已更改

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. For example: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +For example: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    -在 Express 4 中已移除的 `app.router` 对象在 Express 5 中已恢复。在新版本中,此对象只是对 Express 基本路由器的引用,不像在 Express 3 中应用程序必须显式将该路由器装入。 +在 Express 4 中已移除的 `app.router` 对象在 Express 5 中已恢复。在新版本中,此对象只是对 Express 基本路由器的引用,不像在 Express 3 中应用程序必须显式将该路由器装入。 In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it. + +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default.

    req.host

    -在 Express 4 中,如果存在端口号,`req.host` 函数会错误地将其剥离。在 Express 5 中,则会保留端口号。 +在 Express 4 中,如果存在端口号,`req.host` 函数会错误地将其剥离。在 Express 5 中,则会保留端口号。 In Express 5, the port number is maintained.

    req.query

    -在 Express 4.7 以及 Express 5 之后,如果您希望使用自己的查询字符串解析逻辑函数,查询解析器选项可以接受 `false` 以禁用查询字符串解析。 +The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from "extended" to "simple". -

    改进

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### 改进

    res.render()

    现在,此方法为所有查看引擎强制执行异步行为,避免具有同步实现以及违反建议接口的查看引擎所导致的错误。 + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/zh-cn/guide/overriding-express-api.md b/zh-cn/guide/overriding-express-api.md new file mode 100644 index 0000000000..0ff0e90f4f --- /dev/null +++ b/zh-cn/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: en +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/zh-cn/guide/routing.md b/zh-cn/guide/routing.md old mode 100755 new mode 100644 index 7b853d2e28..08e82ab29f --- a/zh-cn/guide/routing.md +++ b/zh-cn/guide/routing.md @@ -1,20 +1,27 @@ --- layout: page title: Express 路由 +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide -lang: zh-cn -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +lang: en +redirect_from: " " --- # 路由 -*路由*表示应用程序端点 (URI) 的定义以及端点响应客户机请求的方式。 +_路由_表示应用程序端点 (URI) 的定义以及端点响应客户机请求的方式。 有关路由的简介,请参阅[基本路由](/{{ page.lang }}/starter/basic-routing.html)。 +For an introduction to routing, see [Basic routing](/{{ page.lang }}/starter/basic-routing.html). -我们所使用的 app 与 HTTP 方法相对应的 Express 对象方法来定义路由,如 ```app.get()``` 用于处理 GET 请求,而 ```app.post``` 则用于处理 POST 请求。 +我们所使用的 app 与 HTTP 方法相对应的 Express 对象方法来定义路由,如 `app.get()` 用于处理 GET 请求,而 `app.post` 则用于处理 POST 请求。 For a full list, +see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) for details). -这些路由方法都指定了回调函数(或者:“处理程序函数”),当程序接收到指定的路由(端点)的时候(也就是说 HTTP 方法请求时被调用),来调用回调函数,换句话说就是应用程序监听与指定路由和方法匹配的请求,当检测到匹配时,他会调用对应的回调函数。 +这些路由方法都指定了回调函数(或者:“处理程序函数”),当程序接收到指定的路由(端点)的时候(也就是说 HTTP 方法请求时被调用),来调用回调函数,换句话说就是应用程序监听与指定路由和方法匹配的请求,当检测到匹配时,他会调用对应的回调函数。 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 +to the next callback. 以下代码是非常基本的路由示例。 @@ -22,7 +29,7 @@ description: Learn how to define and use routes in Express.js applications, incl const express = require('express') const app = express() -// 当对主页发出 GET 请求时,响应“hello world” +// respond with "hello world" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('hello world') }) @@ -46,15 +53,10 @@ app.post('/', (req, res) => { }) ``` -Express 支持对应于 HTTP 方法的以下路由方法:`get`、`post`、`put`、`head`、`delete`、`options`、`trace`、`copy`、`lock`、`mkcol`、`move`、`purge`、`propfind`、`proppatch`、`unlock`、`report`、`mkactivity`、`checkout`、`merge`、`m-search`、`notify`、`subscribe`、`unsubscribe`、`patch`、`search` 和 `connect`。 - -
    -要路由会转换为无效 JavaScript 变量名称的方法,请使用括号表示法。例如,`app['m-search']('/', function ...` -
    +Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -有一种特殊路由方法:`app.all()`,它并非派生自 HTTP 方法。该方法用于在所有请求方法的路径中装入中间件函数。 - -在以下示例中,无论您使用 GET、POST、PUT、DELETE 还是在 [http 模块](https://nodejs.org/api/http.html#http_http_methods)中支持的其他任何 HTTP 请求方法,都将为针对“/secret”的请求执行处理程序。 +有一种特殊路由方法:`app.all()`,它并非派生自 HTTP 方法。该方法用于在所有请求方法的路径中装入中间件函数。 在以下示例中,无论您使用 GET、POST、PUT、DELETE 还是在 [http 模块](https://nodejs.org/api/http.html#http_http_methods)中支持的其他任何 HTTP 请求方法,都将为针对“/secret”的请求执行处理程序。 ```js app.all('/secret', (req, res, next) => { @@ -65,19 +67,36 @@ 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 Route Tester](http://forbeslindesay.github.io/express-route-tester/) 是用于测试基本 Express 路由的便捷工具,但是它不支持模式匹配。 -
    +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
    -查询字符串不是路由路径的一部分。 -
    +{% include admonitions/caution.html content=caution-character %} -以下是基于字符串的路由路径的一些示例。 +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} -此路由路径将请求与根路由 `/` 匹配。 +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. + +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### 以下是基于字符串的路由路径的一些示例。 + +此路由路径将请求与 `/random.text` 匹配。 ```js app.get('/', (req, res) => { @@ -93,7 +112,7 @@ app.get('/about', (req, res) => { }) ``` -此路由路径将请求与 `/random.text` 匹配。 +此路由路径将请求与根路由 `/` 匹配。 ```js app.get('/random.text', (req, res) => { @@ -101,9 +120,13 @@ app.get('/random.text', (req, res) => { }) ``` -以下是基于字符串模式的路由路径的一些示例。 +### 以下是基于字符串模式的路由路径的一些示例。 -此路由路径将匹配 `acd` 和 `abcd`。 +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} + +此路由路径将匹配 `/abe` 和 `/abcde`。 ```js app.get('/ab?cd', (req, res) => { @@ -127,7 +150,7 @@ app.get('/ab*cd', (req, res) => { }) ``` -此路由路径将匹配 `/abe` 和 `/abcde`。 +此路由路径将匹配 `acd` 和 `abcd`。 ```js app.get('/ab(cd)?e', (req, res) => { @@ -135,11 +158,7 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
    -字符 ?、+、* 和 () 是其正则表达式同应项的子集。基于字符串的路径按字面理解连字符 (-) 和点 (.)。 -
    - -基于正则表达式的路由路径的示例: +### 基于正则表达式的路由路径的示例: 此路由路径将匹配名称中具有“a”的所有路由。 @@ -157,13 +176,78 @@ app.get(/.*fly$/, (req, res) => { }) ``` -

    路由处理程序

    +

    路由处理程序

    -您可以提供多个回调函数,以类似于[中间件](/{{ page.lang }}/guide/using-middleware.html)的行为方式来处理请求。唯一例外是这些回调函数可能调用 `next('route')` 来绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,在没有理由继续执行当前路由的情况下,可将控制权传递给后续路由。 +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. -路由处理程序的形式可以是一个函数、一组函数或者两者的结合,如以下示例中所示。 +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` + +
    +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} + +

    Route handlers

    + +您可以提供多个回调函数,以类似于[中间件](/{{ page.lang }}/guide/using-middleware.html)的行为方式来处理请求。唯一例外是这些回调函数可能调用 `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. + +Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples. + +单个回调函数可以处理一个路由。例如: For example: ```js app.get('/example/a', (req, res) => { @@ -171,7 +255,7 @@ app.get('/example/a', (req, res) => { }) ``` -多个回调函数可以处理一个路由(确保您指定 `next` 对象)。例如: +多个回调函数可以处理一个路由(确保您指定 `next` 对象)。例如: For example: ```js app.get('/example/b', (req, res, next) => { @@ -181,7 +265,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -一组回调函数可以处理一个路由。例如: + +一组回调函数可以处理一个路由。例如: For example: ```js const cb0 = function (req, res, next) { @@ -201,7 +286,7 @@ const cb2 = function (req, res) { app.get('/example/c', [cb0, cb1, cb2]) ``` -独立函数与一组函数的组合可以处理一个路由。例如: +独立函数与一组函数的组合可以处理一个路由。例如: For example: ```js const cb0 = function (req, res, next) { @@ -224,24 +309,25 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => {

    响应方法

    -下表中响应对象 (`res`) 的方法可以向客户机发送响应,并终止请求/响应循环。如果没有从路由处理程序调用其中任何方法,客户机请求将保持挂起状态。 +下表中响应对象 (`res`) 的方法可以向客户机发送响应,并终止请求/响应循环。如果没有从路由处理程序调用其中任何方法,客户机请求将保持挂起状态。 If none of these methods are called from a route handler, the client request will be left hanging. -| 方法 | 描述 -|----------------------|-------------------------------------- -| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | 提示将要下载文件。 -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | 结束响应进程。 -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | 发送 JSON 响应。 -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | 在 JSONP 的支持下发送 JSON 响应。 -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 重定向请求。 -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | 呈现视图模板。 -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 发送各种类型的响应。 -| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 以八位元流形式发送文件。 -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | 设置响应状态码并以响应主体形式发送其字符串表示。 +| 方法 | 描述 | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | 提示将要下载文件。 | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | 结束响应进程。 | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | 发送 JSON 响应。 | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | 在 JSONP 的支持下发送 JSON 响应。 | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 重定向请求。 | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | 呈现视图模板。 | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 发送各种类型的响应。 | +| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 以八位元流形式发送文件。 | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | 设置响应状态码并以响应主体形式发送其字符串表示。 |

    app.route()

    您可以使用 `app.route()` 为路由路径创建可链接的路由处理程序。 因为在单一位置指定路径,所以可以减少冗余和输入错误。有关路由的更多信息,请参阅 [Router() 文档](/{{ page.lang }}/4x/api.html#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](/{{ page.lang }}/5x/api.html#router). 以下是使用 `app.route()` 定义的链式路由处理程序的示例。 @@ -260,7 +346,7 @@ app.route('/book')

    express.Router

    -使用 `express.Router` 类来创建可安装的模块化路由处理程序。`Router` 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。 +使用 `express.Router` 类来创建可安装的模块化路由处理程序。`Router` 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。 A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app". 以下示例将路由器创建为模块,在其中装入中间件,定义一些路由,然后安装在主应用程序的路径中。 @@ -271,10 +357,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -292,9 +380,15 @@ module.exports = router ```js const birds = require('./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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/zh-cn/guide/using-middleware.md b/zh-cn/guide/using-middleware.md old mode 100755 new mode 100644 index 22a8fee984..a47e12499c --- a/zh-cn/guide/using-middleware.md +++ b/zh-cn/guide/using-middleware.md @@ -1,45 +1,46 @@ --- layout: page title: 使用 Express 中间件 +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide -lang: zh-cn -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +lang: en +redirect_from: " " --- # 使用中间件 Express 是一个路由和中间件 Web 框架,其自身只具有最低程度的功能:Express 应用程序基本上是一系列中间件函数调用。 -*中间件*函数能够访问[请求对象](/{{ page.lang }}/4x/api.html#req) (`req`)、[响应对象](/{{ page.lang }}/4x/api.html#res) (`res`) 以及应用程序的请求/响应循环中的下一个中间件函数。下一个中间件函数通常由名为 `next` 的变量来表示。 +_中间件_函数能够访问[请求对象](/{{ page.lang }}/4x/api.html#req) (`req`)、[响应对象](/{{ page.lang }}/4x/api.html#res) (`res`) 以及应用程序的请求/响应循环中的下一个中间件函数。下一个中间件函数通常由名为 `next` 的变量来表示。 The next middleware function is commonly denoted by a variable named `next`. 中间件函数可以执行以下任务: -* 执行任何代码。 -* 对请求和响应对象进行更改。 -* 结束请求/响应循环。 -* 调用堆栈中的下一个中间件函数。 +- 执行任何代码。 +- 对请求和响应对象进行更改。 +- 结束请求/响应循环。 +- 调用堆栈中的下一个中间件函数。 -如果当前中间件函数没有结束请求/响应循环,那么它必须调用 `next()`,以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。 +如果当前中间件函数没有结束请求/响应循环,那么它必须调用 `next()`,以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。 Otherwise, the request will be left hanging. Express 应用程序可以使用以下类型的中间件: - - [应用层中间件](#middleware.application) - - [路由器层中间件](#middleware.router) - - [错误处理中间件](#middleware.error-handling) - - [内置中间件](#middleware.built-in) - - [第三方中间件](#middleware.third-party) +- [应用层中间件](#middleware.application) +- [路由器层中间件](#middleware.router) +- [错误处理中间件](#middleware.error-handling) +- [内置中间件](#middleware.built-in) +- [第三方中间件](#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.

    应用层中间件

    使用 `app.use()` 和 `app.METHOD()` 函数将应用层中间件绑定到[应用程序对象](/{{ page.lang }}/4x/api.html#app)的实例,其中 `METHOD` 是中间件函数处理的请求的小写 HTTP 方法(例如 GET、PUT 或 POST)。 -此示例显示没有安装路径的中间件函数。应用程序每次收到请求时执行该函数。 +This example shows a middleware function with no mount path. The function is executed every time the app receives a request. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -48,7 +49,8 @@ app.use((req, res, next) => { }) ``` -此示例显示安装在 `/user/:id` 路径中的中间件函数。在 `/user/:id` 路径中为任何类型的 HTTP 请求执行此函数。 +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. ```js app.use('/user/:id', (req, res, next) => { @@ -57,7 +59,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -此示例显示一个路由及其处理程序函数(中间件系统)。此函数处理针对 `/user/:id` 路径的 GET 请求。 +This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. ```js app.get('/user/:id', (req, res, next) => { @@ -65,8 +67,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('/user/:id', (req, res, next) => { @@ -78,7 +80,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -路由处理程序使您可以为一个路径定义多个路由。以下示例为针对 `/user/:id` 路径的 GET 请求定义两个路由。第二个路由不会导致任何问题,但是永远都不会被调用,因为第一个路由结束了请求/响应循环。 +Route handlers enable you to define multiple routes for a path. 路由处理程序使您可以为一个路径定义多个路由。以下示例为针对 `/user/:id` 路径的 GET 请求定义两个路由。第二个路由不会导致任何问题,但是永远都不会被调用,因为第一个路由结束了请求/响应循环。 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 请求。 @@ -92,13 +94,21 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` 要跳过路由器中间件堆栈中剩余的中间件函数,请调用 `next('route')` 将控制权传递给下一个路由。 **注**:`next('route')` 仅在使用 `app.METHOD()` 或 `router.METHOD()` 函数装入的中间件函数中有效。 +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} + 此示例显示一个中间件子堆栈,用于处理针对 `/user/:id` 路径的 GET 请求。 ```js @@ -106,15 +116,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +此示例显示安装在 `/user/:id` 路径中的中间件函数。在 `/user/:id` 路径中为任何类型的 HTTP 请求执行此函数。 + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -125,10 +156,15 @@ app.get('/user/:id', (req, res, next) => { ```js const router = express.Router() ``` + +以下是在安装点使用安装路径装入一系列中间件函数的示例。 +它演示一个中间件子堆栈,用于显示针对 `/user/:id` 路径的任何类型 HTTP 请求的信息。 + 使用 `router.use()` 和 `router.METHOD()` 函数装入路由器层中间件。 以下示例代码使用路由器层中间件复制以上为应用层中间件显示的中间件系统: ```js +const express = require('express') const app = express() const router = express.Router() @@ -152,7 +188,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -167,10 +203,37 @@ router.get('/user/:id', (req, res, next) => { // 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. + +此示例显示一个中间件子堆栈,用于处理针对 `/user/:id` 路径的 GET 请求。 + +```js +const express = require('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) +}) +``` +

    错误处理中间件

    -错误处理中间件始终采用*四个*自变量。必须提供四个自变量,以将函数标识为错误处理中间件函数。即使无需使用 `next` 对象,也必须指定该对象以保持特征符的有效性。否则,`next` 对象将被解释为常规中间件,从而无法处理错误。 +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.
    错误处理中间件函数的定义方式与其他中间件函数基本相同,差别在于错误处理函数有四个自变量而不是三个,专门具有特征符 `(err, req, res, next)`: @@ -186,54 +249,13 @@ app.use((err, req, res, next) => {

    内置中间件

    -自 V4.x 起,Express 不再依赖于 [Connect](https://github.com/senchalabs/connect)。除 `express.static` 外,先前 Express 随附的所有中间件函数现在以单独模块的形式提供。请查看[中间件函数的列表](https://github.com/senchalabs/connect#middleware)。 - -

    express.static(root, [options])

    - -Express 中唯一内置的中间件函数是 `express.static`。此函数基于 [serve-static](https://github.com/expressjs/serve-static),负责提供 Express 应用程序的静态资源。 - -`root` 自变量指定从其中提供静态资源的根目录。 - -可选的 `options` 对象可以具有以下属性: - -| 属性 | 描述 | 类型 | 缺省值 | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | 是否对外输出文件名以点(.)开头的文件。有效值包括“allow”、“deny”和“ignore” | 字符串 | “ignore” | -| `etag` | 启用或禁用 etag 生成 | 布尔 | `true` | -| `extensions` | 用于设置后备文件扩展名。 | 数组 | `[]` | -| `index` | 发送目录索引文件。设置为 `false` 可禁用建立目录索引。 | 混合 | “index.html” | - `lastModified` | 将 `Last-Modified` 的头设置为操作系统上该文件的上次修改日期。有效值包括 `true` 或 `false`。 | 布尔 | `true` | -| `maxAge` | 设置 Cache-Control 头的 max-age 属性(以毫秒或者 [ms 格式](https://www.npmjs.org/package/ms)中的字符串为单位) | 数字 | 0 | -| `redirect` | 当路径名是目录时重定向到结尾的“/”。 | 布尔 | `true` | -| `setHeaders` | 用于设置随文件一起提供的 HTTP 头的函数。 | 函数 | | - -以下示例将使用了 `express.static` 中间件,并且提供了一个详细的'options'对象(作为示例): +Starting with version 4.x, Express no longer depends on [Connect](https://github.com/senchalabs/connect). 自 V4.x 起,Express 不再依赖于 [Connect](https://github.com/senchalabs/connect)。除 `express.static` 外,先前 Express 随附的所有中间件函数现在以单独模块的形式提供。请查看[中间件函数的列表](https://github.com/senchalabs/connect#middleware)。 -```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` - -对于每个应用程序,可以有多个静态目录: - -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` +Express has the following built-in middleware functions: -有关 `serve-static` 函数及其选项的更多详细信息,请参阅:[serve-static](https://github.com/expressjs/serve-static) 文档。 +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+**

    第三方中间件

    diff --git a/zh-cn/guide/using-template-engines.md b/zh-cn/guide/using-template-engines.md old mode 100755 new mode 100644 index 15caf8a96c..3615c6552f --- a/zh-cn/guide/using-template-engines.md +++ b/zh-cn/guide/using-template-engines.md @@ -1,18 +1,25 @@ --- layout: page title: 将模板引擎用于 Express +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide -lang: zh-cn -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +lang: en +redirect_from: " " --- # 将模板引擎用于 Express -在 Express 可以呈现模板文件之前,必须设置以下应用程序设置: +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. -* `views`:模板文件所在目录。例如:`app.set('views', './views')` -* `view engine`:要使用的模板引擎。例如:`app.set('view engine', 'pug')` +The [Express application generator](/{{ page.lang }}/starter/generator.html) 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](/{{ page.lang }}/4x/api.html#app.set), in the default `app.js` created by the generator: + +- `views`, the directory where the template files are located. `views`:模板文件所在目录。例如:`app.set('views', './views')` + This defaults to the `views` directory in the application root directory. +- `view engine`, the template engine to use. `view engine`:要使用的模板引擎。例如:`app.set('view engine', 'pug')` 然后安装对应的模板引擎 npm 包: @@ -23,6 +30,11 @@ $ npm install pug --save
    与 Express 兼容的模板引擎(例如 Pug)导出名为 `__express(filePath, options, callback)` 的函数,该函数由 `res.render()` 函数调用以呈现模板代码。 某些模板引擎并不遵循此约定。[Consolidate.js](https://www.npmjs.org/package/consolidate) 库通过映射所有流行的 Node.js 模板引擎来遵循此约定,因此可以在 Express 内无缝工作。 + + +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. +
    在设置视图引擎之后,不必指定该引擎或者在应用程序中装入模板引擎模块;Express 在内部装入此模块,如下所示(针对以上示例)。 @@ -41,7 +53,8 @@ html h1= message ``` -随后创建路由以呈现 `index.pug` 文件。如果未设置 `view engine` 属性,必须指定 `view` 文件的扩展名。否则,可以将其忽略。 +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. ```js app.get('/', (req, res) => { @@ -51,5 +64,4 @@ app.get('/', (req, res) => { 向主页发出请求时,`index.pug` 文件将呈现为 HTML。 - -要了解有关模板引擎在 Express 中如何工作的更多信息,请参阅:[“为 Express 开发模板引擎”](/{{ page.lang }}/advanced/developing-template-engines.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/zh-cn/guide/writing-middleware.md b/zh-cn/guide/writing-middleware.md old mode 100755 new mode 100644 index 635cc1052e..a83a812810 --- a/zh-cn/guide/writing-middleware.md +++ b/zh-cn/guide/writing-middleware.md @@ -1,35 +1,35 @@ --- layout: page title: 编写中间件以用于 Express 应用程序 +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide -lang: zh-cn -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +lang: en +redirect_from: " " --- # 编写中间件以用于 Express 应用程序

    概述

    -*中间件*函数能够访问[请求对象](/{{ page.lang }}/4x/api.html#req) (`req`)、[响应对象](/{{ page.lang }}/4x/api.html#res) (`res`) 以及应用程序的请求/响应循环中的下一个中间件函数。下一个中间件函数通常由名为 `next` 的变量来表示。 +_中间件_函数能够访问[请求对象](/{{ page.lang }}/4x/api.html#req) (`req`)、[响应对象](/{{ page.lang }}/4x/api.html#res) (`res`) 以及应用程序的请求/响应循环中的下一个中间件函数。下一个中间件函数通常由名为 `next` 的变量来表示。 The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. 中间件函数可以执行以下任务: -* 执行任何代码。 -* 对请求和响应对象进行更改。 -* 结束请求/响应循环。 -* 调用堆栈中的下一个中间件。 +- 执行任何代码。 +- 对请求和响应对象进行更改。 +- 结束请求/响应循环。 +- 调用堆栈中的下一个中间件。 -如果当前中间件函数没有结束请求/响应循环,那么它必须调用 `next()`,以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。 +如果当前中间件函数没有结束请求/响应循环,那么它必须调用 `next()`,以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。 Otherwise, the request will be left hanging. 以下示例显示中间件函数调用的元素: - -
    + +
    中间件函数适用的路径(路由)。
    @@ -43,7 +43,14 @@ description: Learn how to write custom middleware functions for Express.js appli
    Elements of a middleware function call -
    中间件函数适用的 HTTP 方法。
    +
    中间件函数适用的 HTTP 方法。
    +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. + +

    示例

    + 以下是“Hello World”Express 应用程序的简单示例,将为其定义两个中间件函数: +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 const express = require('express') @@ -56,9 +63,8 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    开发

    - -以下是称为“myLogger”的中间件函数的简单示例。此函数仅在应用程序的请求通过它时显示“LOGGED”。中间件函数会分配给名为 `myLogger` 的变量。 +

    Middleware function 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` 的变量。 ```js const myLogger = function (req, res, next) { @@ -68,12 +74,16 @@ const myLogger = function (req, res, next) { ```
    +Notice the call above to `next()`. Calling this function invokes the next middleware function in the app. + 请注意以上对 `next()` 的调用。调用此函数时,将调用应用程序中的下一个中间件函数。 `next()` 函数不是 Node.js 或 Express API 的一部分,而是传递给中间件函数的第三自变量。`next()` 函数可以命名为任何名称,但是按约定,始终命名为“next”。为了避免混淆,请始终使用此约定。 + 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` 中间件函数。 +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 const express = require('express') @@ -101,6 +111,8 @@ app.listen(3000) 中间件函数 `myLogger` 只是显示消息,然后通过调用 `next()` 函数将请求传递到堆栈中的下一个中间件函数。 +

    Middleware function requestTime

    + 下一个示例将名为 `requestTime` 的属性添加到请求对象。我们将此中间件函数命名为“requestTime”。 ```js @@ -110,7 +122,7 @@ const requestTime = function (req, res, next) { } ``` -现在,该应用程序使用 `requestTime` 中间件函数。此外,根路径路由的回调函数使用由中间件函数添加到 `req`(请求对象)的属性。 +The app now uses the `requestTime` middleware function. 现在,该应用程序使用 `requestTime` 中间件函数。此外,根路径路由的回调函数使用由中间件函数添加到 `req`(请求对象)的属性。 ```js const express = require('express') @@ -131,8 +143,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` + 您向应用程序根发出请求时,此应用程序当前在浏览器中显示请求的时间戳记。 +

    Middleware function validateCookies

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + 因为您拥有请求对象、响应对象、堆栈中的下一个中间件函数以及整个 Node.js API 的访问权,所以中间件函数的可能性是无穷的。 有关 Express 中间件的更多信息,请参阅:[使用 Express 中间件](/{{ page.lang }}/guide/using-middleware.html)。 + +

    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 +module.exports = 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') + +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. diff --git a/zh-cn/resources/community.md b/zh-cn/resources/community.md old mode 100755 new mode 100644 index eb8900524b..ca42422f76 --- a/zh-cn/resources/community.md +++ b/zh-cn/resources/community.md @@ -1,23 +1,89 @@ --- layout: page title: Express 社区 +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources -lang: zh-cn -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +lang: en +redirect_from: " " --- # 社区 -## 示例 +## Technical committee -查看存储库中数十个 Express 应用程序[示例](https://github.com/expressjs/express/tree/master/examples),这些示例涵盖从 API 设计和认证到模板引擎集成的一切内容。 +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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +我们充满活力的社区已创建了大量各种各样的扩展、[中间件模块](/{{ page.lang }}/resources/middleware.html)和更高层次的框架。请在 [wiki](https://github.com/expressjs/express/wiki) 中了解详细信息。 + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## 问题 如果您发现程序中存在错误,或者只是希望提出功能请求,请在[问题队列](https://github.com/expressjs/express/issues)中开具凭证。 -## 第三方 +## 示例 -我们充满活力的社区已创建了大量各种各样的扩展、[中间件模块](/{{ page.lang }}/resources/middleware.html)和更高层次的框架。请在 [wiki](https://github.com/expressjs/express/wiki) 中了解详细信息。 +查看存储库中数十个 Express 应用程序[示例](https://github.com/expressjs/express/tree/master/examples),这些示例涵盖从 API 设计和认证到模板引擎集成的一切内容。 + +## 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. + +# Branding of Express.js + +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/zh-cn/resources/contributing.md b/zh-cn/resources/contributing.md new file mode 100644 index 0000000000..3d58ea86b3 --- /dev/null +++ b/zh-cn/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: en +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/zh-cn/resources/glossary.md b/zh-cn/resources/glossary.md old mode 100755 new mode 100644 index e5e0a76856..b0a8e2b7bb --- a/zh-cn/resources/glossary.md +++ b/zh-cn/resources/glossary.md @@ -1,58 +1,66 @@ --- layout: page title: Express 词汇表 +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. menu: resources -lang: zh-cn -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. +lang: en +redirect_from: " " --- # 词汇表 -### 开放源码 (open-source, open source) +### 应用程序 (application) -英文中用作形容词时,以连字符连接;例如:“This is open-source software”。请参阅 [Wikipedia 上的开源软件](http://en.wikipedia.org/wiki/Open-source_software)。注:虽然不对此术语添加连字符也很常见,但是我们使用标准英语规则对复合形容词添加连字符。 +In general, one or more programs that are designed to carry out operations for a specific purpose. 一般而言,表示设计为针对特定目的执行操作的一个或多个程序。在 Express 的上下文中,表示使用 Node.js 平台上运行的 Express API 的一个程序。可能还指[应用程序对象](/{{ page.lang }}/api.html#express)。 Might also refer to an [app object](/{{ page.lang }}/api.html#express). -### 路由 (route) +### API -标识资源的部分 URL。例如,在 `http://foo.com/products/id` 中,“/products/id”是路由。 +应用程序编程接口。在首次使用时包含此缩写。 Spell out the abbreviation when it is first used. -### 路由器 (router) +### Express -请参阅“API 参考”中的[路由器](/{{ page.lang }}/4x/api.html#router)。 +Node.js 应用程序的一种高度包容、快速而极简的 Web 框架。一般而言,“Express”优先于“Express.js”,但是后者也可接受。 In general, "Express" is preferred to "Express.js," though the latter is acceptable. -### 请求 (request) +### libuv -HTTP 请求。客户机向服务器提交 HTTP 请求消息,然后服务器返回响应。该请求必须使用若干[请求方法](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods)之一,例如 GET、POST 等。 +一种多平台支持库,关注异步 I/O,主要供 Node.js 使用。 -### 响应 (response) +### middleware -HTTP 响应。服务器将 HTTP 响应消息返回给客户机。此响应包含关于请求的完整状态信息,可能还在消息体中包含请求的内容。 +在最终请求处理程序之前由 Express 路由层调用的函数,因此位于原始请求与最终期望的路由之间的中间位置。有关中间件的术语有几点说明: A few fine points of terminology around middleware: -### 应用程序 (application) +- 调用 `var foo = require('middleware')`:_需要_或_使用_ Node.js 模块。随后 `var mw = foo()` 语句通常返回中间件。 Then the statement `var mw = foo()` typically returns the middleware. +- 调用 `app.use(mw)`:_将中间件添加到全局处理堆栈_。 +- 调用 `app.get('/foo', mw, function (req, res) { ... })`:_将中间件添加到“GET /foo”处理堆栈_。 + +### Node.js -一般而言,表示设计为针对特定目的执行操作的一个或多个程序。在 Express 的上下文中,表示使用 Node.js 平台上运行的 Express API 的一个程序。可能还指[应用程序对象](/{{ page.lang }}/api.html#express)。 +A software platform that is used to build scalable network applications. 用于构建可扩展网络应用程序的一种软件平台。Node.js 将 JavaScript 用作其脚本编制语言,并通过非阻塞 I/O 和单线程事件循环实现大吞吐量。请参阅 [nodejs.org](http://nodejs.org/)。**使用说明**:最初为“Node.js”,后来成为“Node”。 See [nodejs.org](https://nodejs.org/en/). **Usage note**: Initially, "Node.js," thereafter "Node". -### 中间件 (middleware) +### 开放源码 (open-source, open source) -在最终请求处理程序之前由 Express 路由层调用的函数,因此位于原始请求与最终期望的路由之间的中间位置。有关中间件的术语有几点说明: +英文中用作形容词时,以连字符连接;例如:“This is open-source software”。请参阅 [Wikipedia 上的开源软件](http://en.wikipedia.org/wiki/Open-source_software)。注:虽然不对此术语添加连字符也很常见,但是我们使用标准英语规则对复合形容词添加连字符。 See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). - * 调用 `var foo = require('middleware')`:*需要*或*使用* Node.js 模块。随后 `var mw = foo()` 语句通常返回中间件。 - * 调用 `app.use(mw)`:*将中间件添加到全局处理堆栈*。 - * 调用 `app.get('/foo', mw, function (req, res) { ... })`:*将中间件添加到“GET /foo”处理堆栈*。 +{% capture english-rules %} -### API +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. -应用程序编程接口。在首次使用时包含此缩写。 +{% endcapture %} -### Express +{% include admonitions/note.html content=english-rules %} -Node.js 应用程序的一种高度包容、快速而极简的 Web 框架。一般而言,“Express”优先于“Express.js”,但是后者也可接受。 +### 请求 (request) -### libuv +An HTTP request. HTTP 响应。服务器将 HTTP 响应消息返回给客户机。此响应包含关于请求的完整状态信息,可能还在消息体中包含请求的内容。 HTTP 请求。客户机向服务器提交 HTTP 请求消息,然后服务器返回响应。该请求必须使用若干[请求方法](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods)之一,例如 GET、POST 等。 -一种多平台支持库,关注异步 I/O,主要供 Node.js 使用。 +### 响应 (response) -### Node.js +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. + +### 路由 (route) + +Part of a URL that identifies a resource. 标识资源的部分 URL。例如,在 `http://foo.com/products/id` 中,“/products/id”是路由。 -用于构建可扩展网络应用程序的一种软件平台。Node.js 将 JavaScript 用作其脚本编制语言,并通过非阻塞 I/O 和单线程事件循环实现大吞吐量。请参阅 [nodejs.org](http://nodejs.org/)。**使用说明**:最初为“Node.js”,后来成为“Node”。 +### 路由器 (router) + +请参阅“API 参考”中的[路由器](/{{ page.lang }}/4x/api.html#router)。 diff --git a/zh-cn/resources/middleware.md b/zh-cn/resources/middleware.md old mode 100755 new mode 100644 index 02949de4bb..07fdeb4ac3 --- a/zh-cn/resources/middleware.md +++ b/zh-cn/resources/middleware.md @@ -1,64 +1,45 @@ --- -layout: page +layout: middleware title: Express 中间件 +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. menu: resources -lang: zh-cn -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. +lang: en +redirect_from: " " +module: mw-home --- -# 第三方中间件 +## Express 中间件 -以下是一些 Express 中间件模块: +The Express middleware modules listed here are maintained by the +[Expressjs team](https://github.com/orgs/expressjs/people). - - [body-parser](https://github.com/expressjs/body-parser):先前为 `express.bodyParser`、`json` 和 `urlencoded`。另请参阅: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression):先前为 `express.compress`。 - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus):用于提供最优映像的 Connect/Express 中间件模块。如有可能,可将映像切换为 `.webp` 或 `.jxr`。 - - [connect-timeout](https://github.com/expressjs/timeout):先前为 `express.timeout`。 - - [cookie-parser](https://github.com/expressjs/cookie-parser):先前为 `express.cookieParser`。 - - [cookie-session](https://github.com/expressjs/cookie-session):先前为 `express.cookieSession`。 - - [errorhandler](https://github.com/expressjs/errorhandler):先前为 `express.errorHandler`。 - - [express-debug](https://github.com/devoidfury/express-debug):不引人注目的开发工具,用于向应用程序添加一个选项卡,其中包含有关模板变量(本地)、当前会话、有用请求数据等方面的信息。 - - [express-partial-response](https://github.com/nemtsov/express-partial-response):Express 中间件模块,使用 Google API 的 Partial Response,根据 `fields` 查询字符串过滤掉 JSON 响应的各个部分。 - - [express-session](https://github.com/expressjs/session):先前为 `express.session`。 - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn):Express 中间件模块,将 CDN 用于静态资产,具有多主机支持(例如:cdn1.host.com、cdn2.host.com)。 - - [express-slash](https://github.com/ericf/express-slash):Express 中间件模块,适用于对末尾斜杠有很严格要求的人员。 - - [express-stormpath](https://github.com/stormpath/stormpath-express):实现用户存储、认证、授权、SSO 和数据安全性的 Express 中间件模块。 - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize):中间件模块,用于将包含大写字母的 HTTP 请求转换为标准的小写形式。 - - [helmet](https://github.com/helmetjs/helmet):一个模块,用于通过设置各种 HTTP 头来帮助保护应用程序。 - - [join-io](https://github.com/coderaiser/join-io "join-io"):一个模块,用于实时联接文件以减少请求数目。 - - [method-override](https://github.com/expressjs/method-override):先前为 `express.methodOverride`。 - - [morgan](https://github.com/expressjs/morgan):先前为 `logger`。 - - [passport](https://github.com/jaredhanson/passport):用于认证的 Express 中间件模块。 - - [response-time](https://github.com/expressjs/response-time):先前为 `express.responseTime`。 - - [serve-favicon](https://github.com/expressjs/serve-favicon):先前为 `express.favicon`。 - - [serve-index](https://github.com/expressjs/serve-index):先前为 `express.directory`。 - - [serve-static](https://github.com/expressjs/serve-static):用于提供静态内容的模块。 - - [static-expiry](https://github.com/paulwalker/connect-static-expiry):静态资产的指纹式 URL 或高速缓存头,包含对一个或多个外部域的支持。 - - [vhost](https://github.com/expressjs/vhost):先前为 `express.vhost`。 - - [view-helpers](https://github.com/madhums/node-view-helpers):Express 中间件模块,用于向视图提供常见助手方法。 - - [sriracha-admin](https://github.com/hdngr/siracha):Express 中间件模块,为 Mongoose 动态生成管理站点。 +| Middleware module | 描述 | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Connect 先前随附的一些中间件模块不再受到 Connect/Express 团队的支持。这些模块由替代模块所取代,或者应该被更好的模块取代。请使用以下替代模块之一: +## Additional middleware modules - - express.cookieParser - - [cookies](https://github.com/jed/cookies) 和 [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -有关更多中间件模块,请参阅: +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| Middleware module | 描述 | +| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet):一个模块,用于通过设置各种 HTTP 头来帮助保护应用程序。 | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport):用于认证的 Express 中间件模块。 | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/zh-cn/resources/middleware/body-parser.md b/zh-cn/resources/middleware/body-parser.md new file mode 100644 index 0000000000..d188f90ee8 --- /dev/null +++ b/zh-cn/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: en +redirect_from: " " +module: body-parser +--- diff --git a/zh-cn/resources/middleware/compression.md b/zh-cn/resources/middleware/compression.md new file mode 100644 index 0000000000..05f540b0d0 --- /dev/null +++ b/zh-cn/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: en +redirect_from: " " +module: compression +--- diff --git a/zh-cn/resources/middleware/connect-rid.md b/zh-cn/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..64bc400309 --- /dev/null +++ b/zh-cn/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: en +redirect_from: " " +module: connect-rid +--- diff --git a/zh-cn/resources/middleware/cookie-parser.md b/zh-cn/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..a75855fc91 --- /dev/null +++ b/zh-cn/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: en +redirect_from: " " +module: cookie-parser +--- diff --git a/zh-cn/resources/middleware/cookie-session.md b/zh-cn/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..8b68fa1911 --- /dev/null +++ b/zh-cn/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: en +redirect_from: " " +module: cookie-session +--- diff --git a/zh-cn/resources/middleware/cors.md b/zh-cn/resources/middleware/cors.md new file mode 100644 index 0000000000..be266ac8d4 --- /dev/null +++ b/zh-cn/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: en +redirect_from: " " +module: cors +--- diff --git a/zh-cn/resources/middleware/errorhandler.md b/zh-cn/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..b7da1e5f68 --- /dev/null +++ b/zh-cn/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: en +redirect_from: " " +module: errorhandler +--- diff --git a/zh-cn/resources/middleware/method-override.md b/zh-cn/resources/middleware/method-override.md new file mode 100644 index 0000000000..5938f1de7f --- /dev/null +++ b/zh-cn/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: en +redirect_from: " " +module: method-override +--- diff --git a/zh-cn/resources/middleware/morgan.md b/zh-cn/resources/middleware/morgan.md new file mode 100644 index 0000000000..7d09c8ba37 --- /dev/null +++ b/zh-cn/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: en +redirect_from: " " +module: morgan +--- diff --git a/zh-cn/resources/middleware/multer.md b/zh-cn/resources/middleware/multer.md new file mode 100644 index 0000000000..f837cafdb8 --- /dev/null +++ b/zh-cn/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: en +redirect_from: " " +module: multer +--- diff --git a/zh-cn/resources/middleware/response-time.md b/zh-cn/resources/middleware/response-time.md new file mode 100644 index 0000000000..ae48e3f005 --- /dev/null +++ b/zh-cn/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: en +redirect_from: " " +module: response-time +--- diff --git a/zh-cn/resources/middleware/serve-favicon.md b/zh-cn/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..57f5a450aa --- /dev/null +++ b/zh-cn/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: en +redirect_from: " " +module: serve-favicon +--- diff --git a/zh-cn/resources/middleware/serve-index.md b/zh-cn/resources/middleware/serve-index.md new file mode 100644 index 0000000000..a92b46dc95 --- /dev/null +++ b/zh-cn/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: en +redirect_from: " " +module: serve-index +--- diff --git a/zh-cn/resources/middleware/serve-static.md b/zh-cn/resources/middleware/serve-static.md new file mode 100644 index 0000000000..b17737af5f --- /dev/null +++ b/zh-cn/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: en +redirect_from: " " +module: serve-static +--- diff --git a/zh-cn/resources/middleware/session.md b/zh-cn/resources/middleware/session.md new file mode 100644 index 0000000000..05ec6133ac --- /dev/null +++ b/zh-cn/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: en +redirect_from: " " +module: session +--- diff --git a/zh-cn/resources/middleware/timeout.md b/zh-cn/resources/middleware/timeout.md new file mode 100644 index 0000000000..0aa926a7f3 --- /dev/null +++ b/zh-cn/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: en +redirect_from: " " +module: timeout +--- diff --git a/zh-cn/resources/middleware/vhost.md b/zh-cn/resources/middleware/vhost.md new file mode 100644 index 0000000000..08860472ec --- /dev/null +++ b/zh-cn/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: en +redirect_from: " " +module: vhost +--- diff --git a/zh-cn/resources/utils.md b/zh-cn/resources/utils.md new file mode 100644 index 0000000000..e5a7d7cb62 --- /dev/null +++ b/zh-cn/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: en +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| Utility modules | 描述 | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/zh-cn/starter/basic-routing.md b/zh-cn/starter/basic-routing.md old mode 100755 new mode 100644 index e098d03caf..3934fcbf89 --- a/zh-cn/starter/basic-routing.md +++ b/zh-cn/starter/basic-routing.md @@ -1,25 +1,25 @@ --- layout: page title: Express 基本路由 +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. menu: starter -lang: zh-cn -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. +lang: en +redirect_from: " " --- # 基本路由 -*路由*用于确定应用程序如何响应对特定端点的客户机请求,包含一个 URI(或路径)和一个特定的 HTTP 请求方法(GET、POST 等)。 +_路由_用于确定应用程序如何响应对特定端点的客户机请求,包含一个 URI(或路径)和一个特定的 HTTP 请求方法(GET、POST 等)。 每个路由可以具有一个或多个处理程序函数,这些函数在路由匹配时执行。 路由定义采用以下结构: + ```js app.METHOD(PATH, HANDLER) ``` -其中: +Where: - `app` 是 `express` 的实例。 - `METHOD` 是 [HTTP 请求方法](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)。 @@ -27,7 +27,9 @@ app.METHOD(PATH, HANDLER) - `HANDLER` 是在路由匹配时执行的函数。
    +This tutorial assumes that an instance of `express` named `app` is created and the server is running. 本教程假定创建了名为 `app` 的 `express` 实例且服务器正在运行。如果您对创建和启动应用程序并不熟悉,请参阅 [Hello world 示例](/{{ page.lang }}/starter/hello-world.html)。 +
    以下示例演示了如何定义简单路由。 @@ -65,3 +67,5 @@ app.delete('/user', (req, res) => { ``` 有关路由的更多详细信息,请参阅[路由指南](/{{ page.lang }}/guide/routing.html)。 + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/zh-cn/starter/examples.md b/zh-cn/starter/examples.md new file mode 100644 index 0000000000..0df4f7d85a --- /dev/null +++ b/zh-cn/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: en +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/zh-cn/starter/faq.md b/zh-cn/starter/faq.md old mode 100755 new mode 100644 index d70830722e..f573a203a8 --- a/zh-cn/starter/faq.md +++ b/zh-cn/starter/faq.md @@ -1,56 +1,73 @@ --- layout: page title: Express 常见问题及解答 +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter -lang: zh-cn -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +lang: en +redirect_from: " " --- # 常见问题及解答 ## 如何构造自己的应用程序? -这个问题没有固定答案。具体取决于您的应用程序以及参与团队的规模。为了实现尽可能的灵活性,Express 在结构方面不作任何假设。 +There is no definitive answer to this question. 这个问题没有固定答案。具体取决于您的应用程序以及参与团队的规模。为了实现尽可能的灵活性,Express 在结构方面不作任何假设。 To be as +flexible as possible, Express makes no assumptions in terms of structure. -路由和其他特定于应用程序的逻辑可以存在于您首选的任何目录结构的任意数量的文件中。请查看以下示例以获取灵感: +路由和其他特定于应用程序的逻辑可以存在于您首选的任何目录结构的任意数量的文件中。请查看以下示例以获取灵感: View the following +examples for inspiration: -* [路由列表](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [路由图](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [MVC 样式控制器](https://github.com/expressjs/express/tree/master/examples/mvc) +- [路由列表](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [路由图](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [MVC 样式控制器](https://github.com/expressjs/express/tree/master/examples/mvc) 另外还有针对 Express 的第三方扩展,这有助于简化某些模式: -* [资源丰富的路由](https://github.com/expressjs/express-resource) +- [资源丰富的路由](https://github.com/expressjs/express-resource) ## 如何定义模型? -Express 没有数据库概念。此概念留给第三方 Node 模块实现,因此可以接入几乎任何数据库。 +Express 没有数据库概念。此概念留给第三方 Node 模块实现,因此可以接入几乎任何数据库。 This concept is +left up to third-party Node modules, allowing you to +interface with nearly any database. 请参阅 [LoopBack](http://loopback.io) 以了解处于模型中心的基于 Express 的框架。 ## 如何对用户进行认证? +Authentication is another opinionated area that Express does not +venture into. You may use any authentication scheme you wish. 认证是 Express 没有涉足的另一严格领域。您可使用所希望的任何认证方案。 要了解简单的“用户名/密码”方案,请参阅[此示例](https://github.com/expressjs/express/tree/master/examples/auth)。 - ## Express 支持哪些模板引擎? Express 支持符合 `(path, locals, callback)` 特征符的任何模板引擎。 为了使模板引擎接口和高速缓存实现标准化,请参阅 [consolidate.js](https://github.com/visionmedia/consolidate.js) 项目以获得支持。未列出的模板引擎可能也支持 Express 特征符。 +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. + +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). ## 如何处理 404 响应? -在 Express 中,404 响应不是错误的结果,所以错误处理程序中间件不会将其捕获。此行为是因为 404 响应只是表明缺少要执行的其他工作;换言之,Express 执行了所有中间件函数和路由,且发现它们都没有响应。您需要做的只是在堆栈的最底部(在其他所有函数之下)添加一个中间件函数来处理 404 响应: +在 Express 中,404 响应不是错误的结果,所以错误处理程序中间件不会将其捕获。此行为是因为 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, +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: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## 如何设置错误处理程序? 错误处理中间件的定义方式与其他中间件基本相同,差别在于错误处理中间件有四个自变量而不是三个,专门具有特征符 `(err, req, res, next)`: @@ -66,6 +83,16 @@ app.use((err, req, res, next) => { ## 如何呈现纯 HTML? -您不必这么做!无需使用 `res.render()` 函数来“呈现”HTML。 +You don't! 您不必这么做!无需使用 `res.render()` 函数来“呈现”HTML。 如果您具有特定文件,请使用 `res.sendFile()` 函数。 如果您希望从目录提供许多资产,请使用 `express.static()` 中间件函数。 +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. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/zh-cn/starter/generator.md b/zh-cn/starter/generator.md old mode 100755 new mode 100644 index 45209ea3e0..b3b7e62653 --- a/zh-cn/starter/generator.md +++ b/zh-cn/starter/generator.md @@ -1,10 +1,10 @@ --- layout: page title: Express 应用程序生成器 +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter -lang: zh-cn -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +lang: en +redirect_from: " " --- # Express 应用程序生成器 @@ -29,7 +29,7 @@ $ express ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -40,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -例如,以下语句在当前工作目录中创建名为 _myapp_ 的 Express 应用程序并将视图引擎将设置为 [Pug](https://pugjs.org/) : +For example, the following creates an Express app named _myapp_. 例如,以下语句在当前工作目录中创建名为 _myapp_ 的 Express 应用程序并将视图引擎将设置为 [Pug](https://pugjs.org/) : ```bash $ express --view=pug myapp @@ -122,5 +122,9 @@ PS> $env:DEBUG='myapp:*'; npm start ```
    + 生成器创建的应用程序结构只是构造 Express 应用程序的众多方法之一。请随意使用此结构或者对其进行修改以最大程度满足自己的需求。 + Feel free to use this structure or modify it to best suit your needs.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/zh-cn/starter/hello-world.md b/zh-cn/starter/hello-world.md old mode 100755 new mode 100644 index 5f6989eaf1..f486a4e41b --- a/zh-cn/starter/hello-world.md +++ b/zh-cn/starter/hello-world.md @@ -1,22 +1,18 @@ --- layout: page title: Express“Hello World”示例 +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter -lang: zh-cn -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +lang: en +redirect_from: " " --- # Hello world 示例
    -这基本上是您可以创建的最简单的 Express 应用程序。这是单个文件应用程序 — 根本*不*需要动用 [Express 生成器](/{{ page.lang }}/starter/generator.html)。Express 生成器的作用就像是为完整的应用程序建立一个“脚手架”,包含各种用途的 JavaScript 文件、Jade 模板和子目录。 +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](/{{ page.lang }}/starter/generator.html), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.
    -首先创建名为 `myapp` 的目录,切换到此目录,然后运行 `npm init`。根据[安装指南](/{{ page.lang }}/starter/installing.html)将 `express` 安装为依赖项。 - -在 `myapp` 目录中,创建名为 `app.js` 的文件,然后添加以下代码: - ```js const express = require('express') const app = express() @@ -31,7 +27,13 @@ app.listen(port, () => { }) ``` -应用程序会启动服务器,并在端口 3000 上侦听连接。此应用程序以“Hello World!”响应针对根 URL (`/`) 或*路由*的请求。对于其他所有路径,它将以 **404 Not Found** 进行响应。 +This app starts a server and listens on port 3000 for connections. 应用程序会启动服务器,并在端口 3000 上侦听连接。此应用程序以“Hello World!”响应针对根 URL (`/`) 或_路由_的请求。对于其他所有路径,它将以 **404 Not Found** 进行响应。 For every other path, it will respond with a **404 Not Found**. + +### Running Locally + +首先创建名为 `myapp` 的目录,切换到此目录,然后运行 `npm init`。根据[安装指南](/{{ page.lang }}/starter/installing.html)将 `express` 安装为依赖项。 Then, install `express` as a dependency, as per the [installation guide](/{{ page.lang }}/starter/installing.html). + +在 `myapp` 目录中,创建名为 `app.js` 的文件,然后添加以下代码:
    `req`(请求)和 `res`(响应)与 Node 提供的对象完全相同,所以您可以在不涉及 Express 的情况下调用 `req.pipe()`、`req.on('data', callback)` 和要执行的其他任何函数。 @@ -45,3 +47,4 @@ $ node app.js 然后,在浏览器中输入 [http://localhost:3000/](http://localhost:3000/) 以查看输出。 +### 这基本上是您可以创建的最简单的 Express 应用程序。这是单个文件应用程序 — 根本_不_需要动用 [Express 生成器](/{{ page.lang }}/starter/generator.html)。Express 生成器的作用就像是为完整的应用程序建立一个“脚手架”,包含各种用途的 JavaScript 文件、Jade 模板和子目录。 diff --git a/zh-cn/starter/installing.md b/zh-cn/starter/installing.md old mode 100755 new mode 100644 index c295216698..c8a5b9509f --- a/zh-cn/starter/installing.md +++ b/zh-cn/starter/installing.md @@ -1,16 +1,19 @@ --- layout: page title: 安装 Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter -lang: zh-cn -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +lang: en +redirect_from: " " --- # 安装 假设您已经安装了 [Node.js](https://nodejs.org/),创建目录以保存应用程序,并将其设置为工作目录。 +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp @@ -18,21 +21,22 @@ $ cd myapp 使用 `npm init` 命令为应用程序创建 `package.json` 文件。 有关 `package.json` 工作方式的更多信息,请参阅 [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json)。 +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: -```bash +``` entry point: (index.js) ``` -输入 `app.js`,或者您希望使用的任何主文件名称。如果希望文件名为 `index.js`,请按回车键以接受建议的缺省文件名。 +输入 `app.js`,或者您希望使用的任何主文件名称。如果希望文件名为 `index.js`,请按回车键以接受建议的缺省文件名。 If you want it to be `index.js`, hit RETURN to accept the suggested default file name. -在 `myapp` 目录中安装 Express,然后将其保存在依赖项列表中。例如: +在 `myapp` 目录中安装 Express,然后将其保存在依赖项列表中。例如: For example: ```bash $ npm install express @@ -45,6 +49,10 @@ $ npm install express --no-save ```
    + 默认情况下,版本为 npm 5.0+ 的 npm install 将模块添加到 `package.json` 文件中的 `dependencies` 列表;对于较早版本的 npm,必须显式指定 `--save` 选项。 今后运行 `app` 目录中的 `npm install` 将自动安装依赖项列表中的模块。 + Then, afterwards, running `npm install` in the app directory will automatically install modules in the dependencies list.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/zh-cn/starter/static-files.md b/zh-cn/starter/static-files.md old mode 100755 new mode 100644 index a28bd91f1f..39a6d676f7 --- a/zh-cn/starter/static-files.md +++ b/zh-cn/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: 在 Express 中提供静态文件 +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter -lang: zh-cn -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +lang: en +redirect_from: " " --- # 在 Express 中提供静态文件 为了提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件,请使用 Express 中的 `express.static` 内置中间件函数。 -将包含静态资源的目录的名称传递给 `express.static` 中间件函数,以便开始直接提供这些文件。例如,使用以下代码在名为 `public` 的目录中提供图像、CSS 文件和 JavaScript 文件: +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](/{{page.lang}}/4x/api.html#express.static). + +For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`: ```js app.use(express.static('public')) @@ -40,6 +49,11 @@ app.use(express.static('files')) Express 以您使用 `express.static` 中间件函数设置静态目录的顺序来查找文件。 +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} + 要为 `express.static` 函数提供的文件创建虚拟路径前缀(路径并不实际存在于文件系统中),请为静态目录[指定安装路径](/{{ page.lang }}/4x/api.html#app.use),如下所示: ```js @@ -56,9 +70,13 @@ http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html ``` -然而,向 `express.static` 函数提供的路径相对于您在其中启动 `node` 进程的目录。如果从另一个目录运行 Express 应用程序,那么对于提供资源的目录使用绝对路径会更安全: +然而,向 `express.static` 函数提供的路径相对于您在其中启动 `node` 进程的目录。如果从另一个目录运行 Express 应用程序,那么对于提供资源的目录使用绝对路径会更安全: 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 const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/zh-cn/support/index.md b/zh-cn/support/index.md index f587c8b5ba..018767928f 100644 --- a/zh-cn/support/index.md +++ b/zh-cn/support/index.md @@ -1,8 +1,9 @@ --- layout: page 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. menu: support -lang: zh-cn +lang: en --- # Version Support @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [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/zh-tw/3x/api.md b/zh-tw/3x/api.md old mode 100755 new mode 100644 index 0afc09f3d6..88149e58e5 --- a/zh-tw/3x/api.md +++ b/zh-tw/3x/api.md @@ -2,34 +2,25 @@ layout: api version: 3x title: Express 3.x - API 參照 +description: Access the API reference for Express.js version 3.x, noting that this version is end-of-life and no longer maintained - includes details on modules and methods. lang: zh-tw -description: Access the API reference for Express.js version 3.x, noting that this - version is end-of-life and no longer maintained - includes details on modules and - methods. +redirect_from: " " --- +
    **Express 3.x 已不再維護** - 從前次更新(2015 年 8 月 1 日)起,不再處理 3.x 中的已知和不明的安全與效能問題。強烈建議您使用 Express 最新版本。 -
    - -

    3.x API

    +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. - - {% include api/en/3x/express.md %} +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). - - {% include api/en/3x/app.md %} - - - {% include api/en/3x/req.md %} +
    - - {% include api/en/3x/res.md %} +

    3.x API

    - - {% include api/en/3x/middleware.md %} + +{% include api/en/3x/app.md %}
    diff --git a/zh-tw/4x/api.md b/zh-tw/4x/api.md old mode 100755 new mode 100644 index 35a71716cb..40cbb4947e --- a/zh-tw/4x/api.md +++ b/zh-tw/4x/api.md @@ -2,27 +2,26 @@ layout: api version: 4x title: Express 4.x - API 參照 +description: Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version. lang: zh-tw -description: Access the API reference for Express.js 4.x, detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- +

    4.x API

    - - {% include api/en/4x/express.md %} +{% capture node-version %} - - {% include api/en/4x/app.md %} +``` +Express 4.0 requires Node.js 0.10 or higher. +``` - - {% include api/en/4x/req.md %} +{% endcapture %} - - {% include api/en/4x/res.md %} +{% include admonitions/note.html content=node-version %} - - {% include api/en/4x/router.md %} + +{% include api/en/4x/app.md %}
    diff --git a/zh-tw/5x/api.md b/zh-tw/5x/api.md index 977a931873..abd67c9dd4 100644 --- a/zh-tw/5x/api.md +++ b/zh-tw/5x/api.md @@ -2,18 +2,24 @@ layout: api version: 5x title: Express 5.x - API 參照 +description: Access the API reference for Express.js 5.x, detailing all modules, methods, and properties for building web applications with this latest version. lang: zh-tw -description: Access the API reference for Express.js 5.x, detailing all modules, methods, - and properties for building web applications with this latest version. +redirect_from: " " ---
    -

    5.x API

    +

    5.x API

    -{% include admonitions/caution.html content="This is early beta documentation that may be incomplete and is still under development." %} +{% capture node-version %} -{% include admonitions/note.html content="Express 5.0 requires Node.js 18 or higher." %} +``` +Express 5.0 requires Node.js 18 or higher. +``` + +{% endcapture %} + +{% include admonitions/note.html content=node-version %} {% include api/en/5x/express.md %} {% include api/en/5x/app.md %} diff --git a/zh-tw/advanced/best-practice-performance.md b/zh-tw/advanced/best-practice-performance.md old mode 100755 new mode 100644 index 67e5180fe6..d499fece87 --- a/zh-tw/advanced/best-practice-performance.md +++ b/zh-tw/advanced/best-practice-performance.md @@ -1,112 +1,95 @@ --- layout: page title: 在正式作業中使用 Express 的效能最佳作法 +description: Discover performance and reliability best practices for Express apps in production, covering code optimizations and environment setups for optimal performance. menu: advanced lang: zh-tw -description: Discover performance and reliability best practices for Express apps - in production, covering code optimizations and environment setups for optimal performance. +redirect_from: " " --- # 正式作業最佳作法:效能和可靠性 -## 概觀 - 本文討論部署至正式作業之 Express 應用程式的效能與可靠性最佳作法。 -顯然地,這個主題屬於 "devops" 領域,涵蓋了傳統開發和作業兩者。因此,資訊分為兩大部分: - -* [在程式碼中的作法](#code)(開發部分)。 -* [在環境 / 設定中的作法](#env)(作業部分)。 +This topic clearly falls into the "devops" world, spanning both traditional development and operations. Accordingly, the information is divided into two parts: - +- Things to do in your code (the dev part): + - 採用 gzip 壓縮 + - [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): + - 將 NODE_ENV 設為 "production" + - 確定您的應用程式自動重新啟動 + - [Run your app in a cluster](#run-your-app-in-a-cluster) + - [Cache request results](#cache-request-results) + - 負載平衡器通常是一個反向 Proxy,負責協調與多個應用程式實例和伺服器之間的資料流量。利用 [Nginx](http://nginx.org/en/docs/http/load_balancing.html) 或 [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts),就能輕鬆設定您應用程式的負載平衡器。 + - 反向 Proxy 位於 Web 應用程式前面,除了將要求引導至應用程式,也會對要求執行支援的作業。除此之外,它還可以處理錯誤頁面、壓縮、快取、提供的檔案,以及負載平衡。 -## 在程式碼中的作法 +## Things to do in your code {#in-code} 以下是您可以在程式碼中執行的一些作法,藉以改良您應用程式的效能: -* 採用 gzip 壓縮 -* 不使用同步函數 -* 使用中介軟體來提供靜態檔案 -* 正確執行記載 -* 適當處理異常狀況 +- 採用 gzip 壓縮 +- [Don't use synchronous functions](#dont-use-synchronous-functions) +- [Do logging correctly](#do-logging-correctly) +- [Handle exceptions properly](#handle-exceptions-properly) ### 採用 gzip 壓縮 -Gzip 壓縮可以大幅減少回應內文的大小,從而提高 Web 應用程式的速度。請使用 [compression](https://www.npmjs.com/package/compression) 中介軟體,在您的 Express 應用程式中進行 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: ```js const compression = require('compression') const express = require('express') const app = express() + app.use(compression()) ``` -在正式作業中,如果網站的資料流量極高,落實執行壓縮最好的作法是在反向 Proxy 層次實作它(請參閱[使用反向 Proxy](#proxy))。在該情況下,就不需使用壓縮中介軟體。如需在 Nginx 中啟用 gzip 壓縮的詳細資料,請參閱 Nginx 說明文件中的 [ngx_http_gzip_module 模組](http://nginx.org/en/docs/http/ngx_http_gzip_module.html)。 +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. 在正式作業中,如果網站的資料流量極高,落實執行壓縮最好的作法是在反向 Proxy 層次實作它(請參閱[使用反向 Proxy](#proxy))。在該情況下,就不需使用壓縮中介軟體。如需在 Nginx 中啟用 gzip 壓縮的詳細資料,請參閱 Nginx 說明文件中的 [ngx_http_gzip_module 模組](http://nginx.org/en/docs/http/ngx_http_gzip_module.html)。 ### 不使用同步函數 -同步函數和方法直到傳回前,會阻礙執行程序的進行。單次呼叫同步函數,可能在數微秒或毫秒傳回,不過,在高資料流量的網站中,這些呼叫往往會累加,並降低應用程式效能。請避免在正式作業中使用它們。 - -雖然 Node 和許多模組會提供其函數的同步與非同步版本,在正式作業中,請一律使用非同步版本。唯一有理由使用同步函數的時機是在最初啟動之時。 - -如果您使用 Node.js 4.0+ 或 io.js 2.1.0+,每當您的應用程式使用同步 API 時,您可以使用 `--trace-sync-io` 指令行旗標,來列印警告和堆疊追蹤。當然,在正式作業中您其實不會想使用此旗標,但這可確保您的程式碼可準備用於正式作業中。如需相關資訊,請參閱 [io.js 2.1.0 每週更新](https://nodejs.org/en/blog/weekly-updates/weekly-update.2015-05-22/#2-1-0)。 +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 和許多模組會提供其函數的同步與非同步版本,在正式作業中,請一律使用非同步版本。唯一有理由使用同步函數的時機是在最初啟動之時。 The only time when a synchronous function can be justified is upon initial startup. -在開發中,您可以使用 [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) 來提供靜態檔案。但是在正式作業中卻不能這樣做,因為此函數得讀取檔案系統,才能取得每一個檔案要求,如此會遇到明顯的延遲,並影響應用程式的整體效能。請注意,`res.sendFile()` *並非*透過更具效率的 [sendfile](http://linux.die.net/man/2/sendfile) 系統呼叫來實作。 +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#cli_trace_sync_io) for more information. -請改用 [serve-static](https://www.npmjs.com/package/serve-static) 中介軟體(或同等項目),此中介軟體能有效提供 Express 應用程式的檔案。 +### Do logging correctly -甚至更好的作法是使用反向 Proxy 來提供靜態檔案;如需相關資訊,請參閱[使用反向 Proxy](#proxy)。 +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()` 或 `console.err()` 將日誌訊息列印至終端機,在開發中是常見作法。但是當目的地是終端機或檔案時,[這些函數是同步的](https://nodejs.org/api/console.html#console_console_1),除非您將輸出引導至另一個程式,這些函數並不適用於正式作業。 - -#### 為了除錯 - -如果您為了除錯而記載,則不要使用 `console.log()`,請改用 [debug](https://www.npmjs.com/package/debug) 之類的特殊除錯模組。這個模組可讓您使用 DEBUG 環境變數,來控制哪些除錯訊息(若有的話)要送往 `console.err()`。為了讓應用程式完全維持非同步,您仍得將 `console.err()` 引導至另一個程式。但之後在正式作業中,實際上您並不會進行除錯,不是嗎? +如果您為了除錯而記載,則不要使用 `console.log()`,請改用 [debug](https://www.npmjs.com/package/debug) 之類的特殊除錯模組。這個模組可讓您使用 DEBUG 環境變數,來控制哪些除錯訊息(若有的話)要送往 `console.err()`。為了讓應用程式完全維持非同步,您仍得將 `console.err()` 引導至另一個程式。但之後在正式作業中,實際上您並不會進行除錯,不是嗎? 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? #### 為了應用程式活動 -如果您要記載應用程式活動(例如,追蹤資料流量或 API 呼叫),則不要使用 `console.log()`,請改用 [Winston](https://www.npmjs.com/package/winston) 或 -[Bunyan](https://www.npmjs.com/package/bunyan) 之類的記載程式庫。如需這兩種程式庫的詳細比較,請參閱 StrongLoop 部落格文章 [Comparing Winston and Bunyan Node.js Logging](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/)。 - - +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 -Node 應用程式一旦遇到未捕捉到的異常狀況,就會當機。如果不處理異常狀況,並採取適當的動作,您的 Express 應用程式會當機並且離線。如果您遵循下方[確定您的應用程式自動重新啟動](#restart)中的建議,應用程式就能從當機回復。幸好 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. 為了確保您能處理所有的異常狀況,請使用下列技術: -* [使用 try-catch](#try-catch) -* [使用 promise](#promises) +- [使用 try-catch](#try-catch) +- [使用 promise](#promises) -在分別討論這兩個主題之前,您對 Node/Express 錯誤處理方式應有基本的瞭解:使用「錯誤優先回呼」,並將錯誤傳播至中介軟體。Node 從非同步函數傳回錯誤時,會採用「錯誤優先回呼」慣例,其中,回呼函數的第一個參數是錯誤物件,接著是後續參數中的結果資料。如果要指出無錯誤,會傳遞 null 作為第一個參數。回呼函數必須同樣遵循「錯誤優先回呼」慣例,才能實際處理錯誤。在 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. 如需進一步瞭解錯誤處理的基本概念,請參閱: -* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) -* [Building Robust Node Applications: Error Handling](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/robust-node-applications-error-handling/) (StrongLoop blog) - -#### 禁止事項 - -有一件事*不能*做,就是接聽 `uncaughtException` 事件,此事件是在回歸事件迴圈期間不斷引發異常狀況時產生的。新增 `uncaughtException` 的事件接聽器,會使遇到異常狀況的程序變更其預設行為;儘管發生異常狀況,該程序會繼續執行。阻止應用程式當機,似乎是個好辦法,但是在未捕捉到異常狀況之後,又繼續執行應用程式,卻是危險作法而不建議這麼做,因為程序的狀態會變得不可靠且無法預測。 - -此外,使用 `uncaughtException` 被公認為[拙劣作法](https://nodejs.org/api/process.html#process_event_uncaughtexception),這裡有一份[提案](https://github.com/nodejs/node-v0.x-archive/issues/2582),指出如何將它從核心移除。因此,接聽 `uncaughtException` 並不可取。這是我們建議採取多重程序和監督程式等事項的原因:當機再重新啟動,通常是從錯誤回復最可靠的作法。 - -我們也不建議使用 [domains](https://nodejs.org/api/domain.html)。它通常不能解決問題,並且是個已淘汰的模組。 - - +- [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors) #### 使用 try-catch -try-catch 是一種 JavaScript 語言建構,可用來捕捉同步程式碼中的異常狀況。例如,如以下所示,利用 try-catch 來處理 JSON 剖析錯誤。 +try-catch 是一種 JavaScript 語言建構,可用來捕捉同步程式碼中的異常狀況。例如,如以下所示,利用 try-catch 來處理 JSON 剖析錯誤。 Use try-catch, for example, to handle JSON parsing errors as shown below. -使用 [JSHint](http://jshint.com/) 或 [JSLint](http://www.jslint.com/) 之類的工具,有助您尋找隱含的異常狀況,例如[參照未定義變數中的錯誤](http://www.jshint.com/docs/options/#undef)。 - -下列範例顯示如何使用 try-catch 來處理潛在的程序當機異常狀況。此中介軟體函數接受名稱是 "params" 的查詢欄位參數,它是一個 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) => { @@ -123,166 +106,126 @@ app.get('/search', (req, res) => { }) ``` -不過,try-catch 只適用於同步程式碼。由於 Node 平台主要是非同步(尤其是在正式作業環境),try-catch 不會捕捉大量的異常狀況。 - - +However, try-catch works only for synchronous code. 不過,try-catch 只適用於同步程式碼。由於 Node 平台主要是非同步(尤其是在正式作業環境),try-catch 不會捕捉大量的異常狀況。 #### 使用 promise -只要非同步程式碼區塊使用 `then()`,promise 就會處理其中的任何異常狀況(包括明確和隱含)。只需在 promise 鏈尾端新增 `.catch(next)` 即可。例如: +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('/', (req, res, next) => { - // do some sync stuff - queryDb() - .then((data) => makeCsv(data)) // handle data - .then((csv) => { /* handle csv */ }) - .catch(next) +app.get('/', async (req, res, next) => { + const data = await userData() // If this promise fails, it will automatically call `next(err)` to handle the error. + + res.send(data) }) app.use((err, req, res, next) => { - // handle error + res.status(err.status ?? 500).send({ error: err.message }) }) ``` -現在,所有非同步與同步錯誤都會傳播到錯誤中介軟體。 - -不過,請注意下列兩項警告: - -1. 您所有的非同步程式碼都必須傳回 promise(不包括發射程式)。如果特定程式庫沒有傳回 promise,請使用 [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html) 等之類的 helper 函數來轉換基本物件。 -2. 事件發射程式(例如:串流)仍可能造成未捕捉到的異常狀況。因此,請確定錯誤事件的處理適當;例如: +Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js -const wrap = fn => (...args) => fn(...args).catch(args[2]) +app.use(async (req, res, next) => { + req.locals.user = await getUser(req) -app.get('/', wrap(async (req, res, next) => { - const company = await getCompanyById(req.query.id) - const stream = getLogoStreamById(company.id) - stream.on('error', next).pipe(res) -})) + next() // This will be called if the promise does not throw an error. +}) ``` -如需使用 promise 來處理錯誤的相關資訊,請參閱: - -* [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/) -* [Promises in Node.js with Q – An Alternative to Callbacks](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/) +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` 被公認為[拙劣作法](https://nodejs.org/api/process.html#process_event_uncaughtexception),這裡有一份[提案](https://github.com/nodejs/node-v0.x-archive/issues/2582),指出如何將它從核心移除。因此,接聽 `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. -* 將 NODE_ENV 設為 "production" -* 確定您的應用程式自動重新啟動 -* 在叢集中執行應用程式 -* 快取要求結果 -* 使用負載平衡器 -* 使用反向 Proxy +我們也不建議使用 [domains](https://nodejs.org/api/domain.html)。它通常不能解決問題,並且是個已淘汰的模組。 It generally doesn't solve the problem and is a deprecated module. -### 將 NODE_ENV 設為 "production" +## Things to do in your environment / setup -NODE_ENV 環境變數用來指定應用程式的執行環境(通常是開發或正式作業)。若要改良效能,其中一個最簡單的作法是將 NODE_ENV 設為 "production"。 +{#in-environment} -將 NODE_ENV 設為 "production",可讓 Express: - -* 快取視圖範本。 -* 快取從 CSS 延伸項目產生的 CSS 檔案。 -* 產生簡略的錯誤訊息。 +以下是您可以在系統環境中執行的一些作法,藉以改良您應用程式的效能: -[測試指出](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/)單單這樣做,就能提高 3 倍的應用程式效能! +- 將 NODE_ENV 設為 "production" +- 確定您的應用程式自動重新啟動 +- [Run your app in a cluster](#run-your-app-in-a-cluster) +- [Cache request results](#cache-request-results) +- 負載平衡器通常是一個反向 Proxy,負責協調與多個應用程式實例和伺服器之間的資料流量。利用 [Nginx](http://nginx.org/en/docs/http/load_balancing.html) 或 [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts),就能輕鬆設定您應用程式的負載平衡器。 +- 反向 Proxy 位於 Web 應用程式前面,除了將要求引導至應用程式,也會對要求執行支援的作業。除此之外,它還可以處理錯誤頁面、壓縮、快取、提供的檔案,以及負載平衡。 -如果您需要撰寫環境特定的程式碼,您可以使用 `process.env.NODE_ENV` 來檢查 NODE_ENV 的值。請注意,檢查任何環境變數的值都會影響效能,因此請慎行。 +### 將 NODE_ENV 設為 "production" -在開發中,您通常是在互動式 Shell 中設定環境變數,例如,使用 `export` 或您的 `.bash_profile` 檔。但是在正式作業伺服器中,通常您應該不會這樣做;反而是使用您作業系統的 init 系統(systemd 或 Upstart)。下一節詳述一般性的 init 系統用法,但由於設定 NODE_ENV 對於效能來說很重要(而且輕而易舉),這裡仍特別強調。 +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`. -採用 Upstart 時,請在您的工作檔中使用 `env` 關鍵字。例如: +將 NODE_ENV 設為 "production",可讓 Express: +- Cache view templates. +- 快取從 CSS 延伸項目產生的 CSS 檔案。 +- Generate less verbose error messages. -```sh -# /etc/init/env.conf - env NODE_ENV=production -``` +[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! -如需相關資訊,請參閱 [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables)。 +如果您需要撰寫環境特定的程式碼,您可以使用 `process.env.NODE_ENV` 來檢查 NODE_ENV 的值。請注意,檢查任何環境變數的值都會影響效能,因此請慎行。 Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. -採用 systemd 時,請在單位檔案中使用 `Environment` 指引。例如: +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` 指引。例如: For example: ```sh # /etc/systemd/system/myservice.service Environment=NODE_ENV=production ``` -如需相關資訊,請參閱 [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html)。 - -如果您使用 StrongLoop Process Manager,您也可以[在將 StrongLoop PM 安裝成服務時,設定環境變數](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-Setenvironmentvariables)。 - - +For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### 確定您的應用程式自動重新啟動 -在正式作業中,您始終不希望您的應用程式離線。也就是說,不論是應用程式當機,或是伺服器本身當機,您都需要確保它會重新啟動。儘管最好這些事件都不要發生,您仍必須務實看待這兩種可能的情況,其作法如下: +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: -* 當應用程式(和 Node)當機時,使用程序管理程式重新啟動它。 -* 當作業系統當機時,使用您作業系統提供的 init 系統,來重新啟動程序管理程式。也有可能可以使用 init 系統,而不使用程序管理程式。 +- 當應用程式(和 Node)當機時,使用程序管理程式重新啟動它。 +- 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 應用程式一旦遇到未捕捉到的異常狀況,就會當機。首要之務是確定您的應用程式已妥善測試,且已處理所有的異常狀況(請參閱[適當處理異常狀況](#exceptions),以取得詳細資料)。但是萬全的作法是落實執行機制,以確保萬一您的應用程式當機,它會自動重新啟動。 +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 server.js` 或類似指令,就會啟動應用程式。但在正式作業中這樣做,卻會成為禍因。如果應用程式當機,就會離線直到您重新啟動它為止。為了確保應用程式會在當機時重新啟動,請使用程序管理程式。程序管理程式是一個應用程式的「儲存器」,有助於部署、提供高可用性,並可讓您在執行時期管理應用程式。 +在開發中,只需從指令行使用 `node server.js` 或類似指令,就會啟動應用程式。但在正式作業中這樣做,卻會成為禍因。如果應用程式當機,就會離線直到您重新啟動它為止。為了確保應用程式會在當機時重新啟動,請使用程序管理程式。程序管理程式是一個應用程式的「儲存器」,有助於部署、提供高可用性,並可讓您在執行時期管理應用程式。 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. 除了在應用程式當機時重新啟動它,程序管理程式還可讓您: -* 洞察執行時期效能和資源的耗用情況。 -* 動態修改設定,以改良效能。 -* 控制叢集作業(StrongLoop PM 和 pm2)。 - -最普及的 Node 程序管理程式如下: - -* [StrongLoop Process Manager](http://strong-pm.io/) -* [PM2](https://github.com/Unitech/pm2) -* [Forever](https://www.npmjs.com/package/forever) - -有關這三種程序管理程式的特性比較,請參閱 [http://strong-pm.io/compare/](http://strong-pm.io/compare/)。 - -即使您的應用程式不時發生當機,這些程序管理程式不論哪一個都足以讓您的應用程式維持作用中。 +- 洞察執行時期效能和資源的耗用情況。 +- 動態修改設定,以改良效能。 +- Control clustering (pm2). -不過,StrongLoop PM 有許多特性明確以正式作業部署為目標。您可以使用它和相關的 StrongLoop 工具來: - -* 在本端建置和包裝您的應用程式,然後安全地部署到正式作業系統。 -* 在應用程式當機時(不論任何原因),自動重新啟動。 -* 遠端管理叢集。 -* 檢視 CPU 設定檔和資料堆 Snapshot,使效能達到最佳,並診斷記憶體洩漏情況。 -* 檢視您應用程式的效能度量。 -* 藉由 Nginx 負載平衡器的整合控制,輕鬆調整至多部主機。 - -如同以下說明,當您使用 init 系統將 StrongLoop PM 安裝成作業系統服務時,它會自動隨系統一起重新啟動。因此,它會讓您的應用程式程序和叢集永遠維持作用中。 +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 系統 -接下來的可靠性層級是確保您的應用程式會隨伺服器一起重新啟動。系統仍可能因各種不同的原因而關閉。為了確保您的應用程式會在伺服器當機時重新啟動,請使用您作業系統內建的 init 系統。現今兩個通行的主要 init 系統是 [systemd](https://wiki.debian.org/systemd) 和 [Upstart](http://upstart.ubuntu.com/)。 +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). init 系統若要與 Express 應用程式搭配使用,其作法有二: -* 在程序管理程式中執行應用程式,並利用 init 系統將程序管理程式安裝成服務。當應用程式當機時,程序管理程式會重新啟動應用程式,且 init 系統會在作業系統重新啟動時,重新啟動程序管理程式。這是建議的作法。 -* 直接使用 init 系統來執行應用程式(和 Node)。這樣做比較簡單,但卻少了使用程序管理程式時的其他好處。 +- 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 是一個 Linux 系統和服務管理程式。大部分主要的 Linux 發行套件已採用 systemd 作為其預設 init 系統。 Most major Linux distributions have adopted systemd as their default init system. -systemd 服務配置檔稱為*單位檔案*,其副名結尾是 .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] -Description=Awesome Express App +Description= [Service] Type=simple -ExecStart=/usr/local/bin/node /projects/myapp/index.js -WorkingDirectory=/projects/myapp +ExecStart=/usr/local/bin/node +WorkingDirectory= User=nobody Group=nogroup @@ -304,144 +247,67 @@ Restart=always [Install] WantedBy=multi-user.target ``` -如需 systemd 的相關資訊,請參閱 [systemd 參照(線上指令說明)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)。 - -##### 將 StrongLoop PM 當成 systemd 服務 - -將 StrongLoop Process Manager 安裝成 systemd 服務很簡單。完成之後,當伺服器重新啟動時,就會自動重新啟動 StrongLoop PM,之後它就會重新啟動其所管理的所有應用程式。 -將 StrongLoop PM 安裝成 systemd 服務: - -```bash -$ sudo sl-pm-install --systemd -``` - -然後使用下列指令來啟動服務: - -```bash -$ sudo /usr/bin/systemctl start strong-pm -``` - -如需相關資訊,請參閱 [Setting up a production host(StrongLoop 說明文件)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10)。 - -##### Upstart - -Upstart 是一個可在許多 Linux 發行套件中使用的系統工具,它會在系統啟動期間啟動作業和服務、在關機期間停止它們,並且監督它們。您可以將 Express 應用程式或程序管理程式配置成服務,之後 Express 應用程式或程序管理程式一旦發生當機,Upstart 就會自動重新啟動它。 - -Upstart 服務定義在工作配置檔(亦稱為 "job")中,其副名結尾是 `.conf`。下列範例顯示如何為名稱是 "myapp" 的應用程式,建立一項名稱是 "myapp" 的工作,且其主要檔案位於 `/projects/myapp/index.js`。 - -在 `/etc/init/` 建立名稱是 `myapp.conf` 的檔案,且其內容如下(請以您系統和應用程式的值取代粗體字): - -```sh -# When to start the process -start on runlevel [2345] - -# When to stop the process -stop on runlevel [016] - -# Increase file descriptor limit to be able to handle more requests -limit nofile 50000 50000 - -# Use production mode -env NODE_ENV=production - -# Run as www-data -setuid www-data -setgid www-data - -# Run from inside the app dir -chdir /projects/myapp - -# The process to start -exec /usr/local/bin/node /projects/myapp/index.js - -# Restart the process if it is down -respawn +如需 systemd 的相關資訊,請參閱 [systemd 參照(線上指令說明)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html)。 -# Limit restart attempt to 10 times within 10 seconds -respawn limit 10 10 -``` +### Run your app in a cluster -附註:這個 Script 需要 Upstart 1.4 或更新版本,且 Ubuntu 12.04-14.10 支援該 Upstart 版本。 +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. -由於工作是配置成在系統啟動時執行,您的應用程式會隨作業系統一起啟動,並在應用程式當機或系統關閉時自動重新啟動。 +![Balancing between application instances using the cluster API](/images/clustering.png) -除了自動重新啟動應用程式,Upstart 可讓您使用下列指令: +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. -* `start myapp` – 啟動應用程式 -* `restart myapp` – 重新啟動應用程式 -* `stop myapp` – 停止應用程式。 +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(). -如需 Upstart 的相關資訊,請參閱 [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook)。 +#### 使用 Node 的叢集模組 -##### 將 StrongLoop PM 當成 Upstart 服務 +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. -將 StrongLoop Process Manager 安裝成 Upstart 服務很簡單。完成之後,當伺服器重新啟動時,就會自動重新啟動 StrongLoop PM,之後它就會重新啟動其所管理的所有應用程式。 +#### Using PM2 -將 StrongLoop PM 安裝成 Upstart 1.4 服務: +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). -```bash -$ sudo sl-pm-install -``` +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 -$ sudo /sbin/initctl start strong-pm +# Start 4 worker processes +$ pm2 start npm --name my-app -i 4 -- start +# Auto-detect number of available CPUs and start that many worker processes +$ pm2 start npm --name my-app -i max -- start ``` -附註:在不支援 Upstart 1.4 的系統上,指令略有不同。如需相關資訊,請參閱 [Setting up a production host(StrongLoop 說明文件)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10)。 - -### 在叢集中執行應用程式 - -在多核心系統中,您可以啟動程序叢集,多次提高 Node 應用程式的效能。叢集會執行該應用程式的多個實例,理論上,每一個 CPU 核心上各有一個實例,因此負載和作業會分散在這些實例之間。 - - - -重要事項:由於應用程式實例是以個別程序形式執行,因此不會共用相同的記憶體空間。也就是說,物件位於每一個應用程式實例本端。因此,您無法在應用程式碼中維護狀態。不過,您可以利用 [Redis](http://redis.io/) 等之類的記憶體內資料儲存庫,來儲存階段作業的相關資料和狀態。不論叢集是由多個程序或多部實體伺服器組成,這項警告其實適用於所有的水平調整形式。 +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. -在叢集化的應用程式中,工作者程序可個別當機,而不會影響其餘的程序。除了效能優點,執行應用程式程序叢集的另一個原因是,可將失效隔離。只要有工作者程序當機,一律要確定會記載事件,並利用 cluster.fork() 來衍生新程序。 - -#### 使用 Node 的叢集模組 - -利用 Node 的[叢集模組](https://nodejs.org/docs/latest/api/cluster.html),即可達成叢集作業。這可讓主要程序衍生工作者程序,並將送入的連線分散在這些工作者之間。不過,與其直接使用這個模組,更好的作法是使用其中提供的一個工具,自動為您執行叢集作業; -例如 [node-pm](https://www.npmjs.com/package/node-pm) 或 [cluster-service](https://www.npmjs.com/package/cluster-service)。 - -#### 使用 StrongLoop PM - -如果您將應用程式部署至 StrongLoop Process Manager (PM),您可以善用叢集作業,且*不需*修改應用程式碼。 - -當 StrongLoop Process Manager (PM) 執行應用程式時,它會自動在叢集中執行它,且該叢集中的工作者數目等於系統上的 CPU 核心數。您可以使用 slc 指令行工具,直接手動變更工作者程序數目,而不需停止應用程式。 - -舉例來說,假設您將應用程式部署至 prod.foo.com,且 StrongLoop PM 是在埠 8701(預設值)接聽,請使用 slc 將叢集大小設為 8: +Once running, the application can be scaled like so: ```bash -$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8 +# Add 3 more workers +$ pm2 scale my-app +3 +# Scale to a specific number of workers +$ pm2 scale my-app 2 ``` -如需利用 StrongLoop PM 執行叢集作業的相關資訊,請參閱 StrongLoop 說明文件中的[叢集作業](https://docs.strongloop.com/display/SLC/Clustering)。 +For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation. ### 快取要求結果 在正式作業中改良效能的另一項策略是快取要求的結果,這樣您的應用程式就不會重複執行作業而反覆處理相同的要求。 -使用 [Varnish](https://www.varnish-cache.org/) 或 [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/)(另請參閱 [Nginx 快取](https://serversforhackers.com/nginx-caching/))等之類的快取伺服器,可大幅改良您應用程式的速度與效能。 +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. ### 使用負載平衡器 -不論如何將應用程式最佳化,單一實例所能處理的負載量與資料流量有限。調整應用程式的其中一個作法是執行其多個實例,並透過負載平衡器來分散資料流量。設定負載平衡器可改良您應用程式的效能和速度,且透過其單一實例,使該應用程式得以多次調整。 - -負載平衡器通常是一個反向 Proxy,負責協調與多個應用程式實例和伺服器之間的資料流量。利用 [Nginx](http://nginx.org/en/docs/http/load_balancing.html) 或 [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts),就能輕鬆設定您應用程式的負載平衡器。 - -如果進行負載平衡,您可能得確定與特定階段作業 ID 相關聯的要求,會連接至發出該要求的程序。這就是所謂的*階段作業親緣性*或*組合階段作業*,如果要解決此情況,可按照上述建議,使用 Redis 等之類的資料儲存庫來儲存階段作業資料(視您的應用程式而定)。相關討論請參閱[使用多個節點](https://socket.io/docs/v4/using-multiple-nodes/)。 +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. -#### StrongLoop PM 與 Nginx 負載平衡器搭配使用 +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). -[StrongLoop Process Manager](http://strong-pm.io/) 整合了 Nginx Controller,因此配置多主機正式作業環境配置更簡單。如需相關資訊,請參閱 [Scaling to multiple servers](https://docs.strongloop.com/display/SLC/Scaling+to+multiple+servers)(StrongLoop 說明文件)。 - +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/). ### 使用反向 Proxy -反向 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. -將不需要瞭解應用程式狀態的作業移交給反向 Proxy,使 Express 更有餘裕執行特殊的應用程式作業。基於此因,在正式作業中,建議讓 Express 在 [Nginx](https://www.nginx.com/) 或 [HAProxy](http://www.haproxy.org/) 等之類的反向 Proxy 背後執行。 +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. diff --git a/zh-tw/advanced/best-practice-security.md b/zh-tw/advanced/best-practice-security.md old mode 100755 new mode 100644 index 8272257aea..4cf9a06d96 --- a/zh-tw/advanced/best-practice-security.md +++ b/zh-tw/advanced/best-practice-security.md @@ -1,79 +1,174 @@ --- layout: page title: 正式作業中的 Express 安全最佳作法 +description: Discover crucial security best practices for Express apps in production, including using TLS, input validation, secure cookies, and preventing vulnerabilities. menu: advanced lang: zh-tw -description: Discover crucial security best practices for Express apps in production, - including using TLS, input validation, secure cookies, and preventing vulnerabilities. +redirect_from: " " --- # 正式作業最佳作法:安全 ## 概觀 -「*正式作業*」術語是指軟體生命週期中,應用程式或 API 通用於其一般使用者或消費者的階段。相對地,在「*開發*」階段,您仍在積極撰寫和測試程式碼,且應用程式尚未開放給外部存取。對應的系統環境分別稱為*正式作業*環境和*開發*環境。 +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. -開發環境和正式作業環境的設定方式通常不同,且其需求差異頗大。適合用於開發中的,在正式作業中不見得合用。舉例來說,在開發環境中,您可能希望詳細記載錯誤以便除錯,而相同的行為在正式作業環境中卻可能成為安全隱憂。在開發中,您不必擔心可調整性、可靠性和效能,但在正式作業中這些顧慮相形重要。 +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. -本文討論部署至正式作業之 Express 應用程式的一些安全最佳作法。 +{% capture security-note %} + +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/en/resources/contributing.html#security-policies-and-procedures). + +{% endcapture %} + +{% include admonitions/note.html content=security-note %} + +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) + - 您可能熟悉 Secure Socket Layer (SSL) 加密。[TLS 就是 SSL 後繼的演進](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx)。換句話說,如果您之前使用 SSL,請考量升級至 TLS。一般而言,我們建議由 Nginx 來處理 TLS。如需有關在 Nginx(和其他伺服器)上配置 TLS 的適當參考資料,請參閱 [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations)。 + - [Do not trust user input](#do-not-trust-user-input) + - [Prevent open redirects](#prevent-open-redirects) + - [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) 會移除 `X-Powered-By` 標頭。 + - [Reduce fingerprinting](#reduce-fingerprinting) + - `domain` - 指出 Cookie 的網域;用來與發出 URL 要求之伺服器的網域相互比較。如果相符,接著會檢查路徑屬性。 + - 相對地,[cookie-session](https://www.npmjs.com/package/cookie-session) 中介軟體會實作以 Cookie 為基礎的儲存體:它會將整個階段作業序列化為 Cookie,而非只是一個階段作業金鑰。只有在階段作業資料相對較小,且易於編碼成基本值(而非物件)時,才使用此項。雖然瀏覽器對於每個 Cookie 理應可以支援至少 + 4096 個位元組,為了確保您不會超出限制,對於每一個網域,請勿超過 4093 個位元組大小。此外要留意的是,用戶端可以看見 Cookie 資料,因此,若有任何原因需要保護該資料的安全或加以遮蔽,最好選擇 express-session。 + - 使用預設階段作業 Cookie 名稱可能開放您的應用程式遭受攻擊。引發的安全問題類似於 `X-Powered-By`:潛在的攻擊者可能用它來對伺服器進行指紋辨識,從而發動目標攻擊。 + - [Prevent brute-force attacks against authorization](#prevent-brute-force-attacks-against-authorization) + - [Ensure your dependencies are secure](#ensure-your-dependencies-are-secure) + - 最後,如同其他任何的 Web 應用程式,Express 應用程式仍可能遭到各種 Web 型攻擊。請多加熟悉已知的 [Web 漏洞](https://www.owasp.org/www-project-top-ten/),並採取預防措施,來避免這些攻擊。 + - [Additional considerations](#additional-considerations) ## 請勿使用已淘汰或有漏洞的 Express 版本 -Express 2.x 和 3.x 不再維護。不會修正這些版本中的安全與效能問題。請勿使用它們!如果您尚未移至第 4 版,請遵循[移轉手冊](/{{ page.lang }}/guide/migrating-4.html)。 +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](/{{ page.lang }}/guide/migrating-4.html) or consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). -另請確定您沒有使用[「安全更新」頁面](/{{ page.lang }}/advanced/security-updates.html)中列出的任何有漏洞的 Express 版本。若有使用,請更新為其中一個穩定版本,最好是最新版本。 +另請確定您沒有使用[「安全更新」頁面](/{{ page.lang }}/advanced/security-updates.html)中列出的任何有漏洞的 Express 版本。若有使用,請更新為其中一個穩定版本,最好是最新版本。 If you are, update to one of the stable releases, preferably the latest. ## 使用 TLS -如果您的應用程式會處理或傳輸機密資料,請使用[傳輸層安全](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)。 +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). -您可能熟悉 Secure Socket Layer (SSL) 加密。[TLS 就是 SSL 後繼的演進](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515(v=vs.85).aspx)。換句話說,如果您之前使用 SSL,請考量升級至 TLS。一般而言,我們建議由 Nginx 來處理 TLS。如需有關在 Nginx(和其他伺服器)上配置 TLS 的適當參考資料,請參閱 [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. [TLS is simply the next progression of SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515\(v=vs.85\).aspx). 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). 此外,可方便您取得免費 TLS 憑證的工具是 [Let's Encrypt](https://letsencrypt.org/about/),這是一個免費的自動化開放憑證管理中心 (CA),由 [Internet Security Research Group (ISRG)](https://letsencrypt.org/isrg/) 提供。 +## 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. + +### 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. + +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. + +Here is an example of checking URLs before using `res.redirect` or `res.location`: + +```js +app.use((req, res) => { + try { + if (new Url(req.query.url).host !== 'example.com') { + return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`) + } + } catch (e) { + return res.status(400).end(`Invalid url: ${req.query.url}`) + } + res.redirect(req.query.url) +}) +``` + ## 使用 Helmet [Helmet](https://www.npmjs.com/package/helmet) 會適當設定 HTTP 標頭,有助於防範您的應用程式出現已知的 Web 漏洞。 -Helmet 實際上只由 9 個小型中介軟體函數組成,這些函數會設定安全相關的 HTTP 標頭: +Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: -* [csp](https://github.com/helmetjs/csp) 會設定 `Content-Security-Policy` 標頭,以防範跨網站 Scripting 攻擊和其他跨網站注入。 -* [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) 會移除 `X-Powered-By` 標頭。 -* [hsts](https://github.com/helmetjs/hsts) 會設定 `Strict-Transport-Security` 標頭,以施行安全的 (HTTP over SSL/TLS) 伺服器連線。 -* [ieNoOpen](https://github.com/helmetjs/ienoopen) 會設定 `X-Download-Options`(適用於 IE8+)。 -* [noCache](https://github.com/helmetjs/nocache) 會設定 `Cache-Control` 和 Pragma 標頭,以停用用戶端快取。 -* [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) 會設定 `X-Content-Type-Options`,以阻止瀏覽器對脫離所宣告內容類型的回應進行 MIME 探查。 -* [frameguard](https://github.com/helmetjs/frameguard) 會設定 `X-Frame-Options` 標頭,以提供 [clickjacking](https://www.owasp.org/index.php/Clickjacking) 保護。 -* [xssFilter](https://github.com/helmetjs/x-xss-protection) 會設定 `X-XSS-Protection`,以便在最新的 Web 瀏覽器中啟用跨網站 Scripting (XSS) 過濾器。 +- `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 +- `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 +- `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 + +Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. 安裝 Helmet 等之類的其他任何模組: ```bash -$ npm install --save helmet +$ npm install helmet ``` 然後在您的程式碼中使用它: ```js -/// ... +// ... const helmet = require('helmet') app.use(helmet()) -/// ... +// ... ``` -### 至少停用 X-Powered-By 標頭 +## Reduce fingerprinting -如果您不想使用 Helmet,最起碼請停用 `X-Powered-By` 標頭。攻擊者可能使用這個標頭(依預設,會啟用),來偵測執行 Express 的應用程式,然後啟動特定目標的攻擊。 +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. -因此最佳作法是使用 `app.disable()` 方法來關閉標頭: +By default, Express sends the `X-Powered-By` response header that you can +disable using the `app.disable()` method: ```js app.disable('x-powered-by') ``` -如果您使用 `helmet.js`,自會為您處理此事。 +{% capture powered-advisory %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=powered-advisory %} + +Express also sends its own formatted "404 Not Found" messages and formatter error +response messages. These can be changed by +[adding your own not found handler](/en/starter/faq.html#how-do-i-handle-404-responses) +and +[writing your own error handler](/en/guide/error-handling.html#writing-error-handlers): + +```js +// last app.use calls right before app.listen(): + +// custom 404 +app.use((req, res, next) => { + res.status(404).send("Sorry can't find that!") +}) + +// custom error handler +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) +``` ## 安全地使用 Cookie @@ -81,19 +176,18 @@ app.disable('x-powered-by') 以下是兩個主要的中介軟體 Cookie 階段作業模組: -* [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` 中介軟體。 +- [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` 中介軟體。 這兩個模組之間的主要差異是它們儲存 Cookie 階段作業資料的方式。[express-session](https://www.npmjs.com/package/express-session) 中介軟體會將階段作業資料儲存在伺服器上; 它只將階段作業 ID(而非階段作業資料)儲存在 Cookie 本身中。依預設,它使用記憶體內儲存體,且並非設計成用於正式作業環境。在正式作業中,您需要設定可調式階段作業儲存庫; -請參閱[相容的階段作業儲存庫](https://github.com/expressjs/session#compatible-session-stores)清單。 +請參閱[相容的階段作業儲存庫](https://github.com/expressjs/session#compatible-session-stores)清單。 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-session](https://www.npmjs.com/package/cookie-session) 中介軟體會實作以 Cookie 為基礎的儲存體:它會將整個階段作業序列化為 Cookie,而非只是一個階段作業金鑰。只有在階段作業資料相對較小,且易於編碼成基本值(而非物件)時,才使用此項。雖然瀏覽器對於每個 Cookie 理應可以支援至少 -4096 個位元組,為了確保您不會超出限制,對於每一個網域,請勿超過 4093 個位元組大小。此外要留意的是,用戶端可以看見 Cookie 資料,因此,若有任何原因需要保護該資料的安全或加以遮蔽,最好選擇 express-session。 +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 名稱 -使用預設階段作業 Cookie 名稱可能開放您的應用程式遭受攻擊。引發的安全問題類似於 `X-Powered-By`:潛在的攻擊者可能用它來對伺服器進行指紋辨識,從而發動目標攻擊。 +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 名稱; 例如,使用 [express-session](https://www.npmjs.com/package/express-session) 中介軟體: @@ -104,19 +198,18 @@ app.set('trust proxy', 1) // trust first proxy app.use(session({ secret: 's3Cur3', name: 'sessionId' -}) -) +})) ``` ### 設定 Cookie 安全選項 設定下列 Cookie 選項來加強安全: -* `secure` - 確保瀏覽器只透過 HTTPS 傳送 Cookie。 -* `httpOnly` - 確保只透過 HTTP(S) 傳送 Cookie,而不透過用戶端 JavaScript 傳送,如此有助於防範跨網站 Scripting 攻擊。 -* `domain` - 指出 Cookie 的網域;用來與發出 URL 要求之伺服器的網域相互比較。如果相符,接著會檢查路徑屬性。 -* `path` - 指出 Cookie 的路徑;用來與要求路徑相互比較。如果此項與網域相符,則會傳送要求中的 Cookie。 -* `expires` - 用來設定持續性 Cookie 的到期日。 +- `secure` - 確保瀏覽器只透過 HTTPS 傳送 Cookie。 +- `httpOnly` - 確保只透過 HTTP(S) 傳送 Cookie,而不透過用戶端 JavaScript 傳送,如此有助於防範跨網站 Scripting 攻擊。 +- `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` - 指出 Cookie 的路徑;用來與要求路徑相互比較。如果此項與網域相符,則會傳送要求中的 Cookie。 If this and domain match, then send the cookie in the request. +- `expires` - 用來設定持續性 Cookie 的到期日。 下列範例使用 [cookie-session](https://www.npmjs.com/package/cookie-session) 中介軟體: @@ -136,23 +229,59 @@ app.use(session({ 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. + +[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) + +## 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. + +Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. + +```bash +$ npm audit +``` + +If you want to stay more secure, consider [Snyk](https://snyk.io/). -以下是優異的 [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) 所提供的進一步建議。如需這些建議的所有詳細資料,請參閱該部落格文章: +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: -* 實作速率限制,以防對鑑別發動強制入侵攻擊。其中一個作法是使用 [StrongLoop API Gateway](https://web.archive.org/web/20240000000000/https://strongloop.com/node-js/api-gateway/) 來施行速率限制原則。或者,您可以使用 [express-limiter](https://www.npmjs.com/package/express-limiter) 之類的中介軟體,但是如果這樣做,您需要稍微修改程式碼。 -* 一律對使用者輸入進行過濾和消毒,來防範跨網站 Scripting (XSS) 和指令注入攻擊。 -* 使用參數化查詢或備妥陳述式,來防禦 SQL 注入攻擊。 -* 使用開放程式碼 [sqlmap](http://sqlmap.org/) 工具,來偵測您應用程式中的 SQL 注入漏洞。 -* 使用 [nmap](https://nmap.org/) 和 [sslyze](https://github.com/nabla-c0d3/sslyze) 工具,來測試您 SSL 密碼、金鑰和重新協議的配置,以及測試您憑證的有效性。 -* 使用 [safe-regex](https://www.npmjs.com/package/safe-regex),確定您的正規表示式不易受到[正規表示式阻斷服務](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻擊。 +```bash +$ npm install -g snyk +$ cd your-app +``` + +Use this command to test your application for vulnerabilities: + +```bash +$ 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. 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. + +## 其他注意事項 -## 避免其他已知的漏洞 +以下是優異的 [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 Security Project](https://npmjs.com/advisories) 中有關可能影響您應用程式所用之 Express 或其他模組的公告。一般而言,Node Security Project 是一個絕佳的資源,它提供 Node 安全的相關知識和工具。 +- 一律對使用者輸入進行過濾和消毒,來防範跨網站 Scripting (XSS) 和指令注入攻擊。 +- 使用參數化查詢或備妥陳述式,來防禦 SQL 注入攻擊。 +- 使用開放程式碼 [sqlmap](http://sqlmap.org/) 工具,來偵測您應用程式中的 SQL 注入漏洞。 +- 使用 [nmap](https://nmap.org/) 和 [sslyze](https://github.com/nabla-c0d3/sslyze) 工具,來測試您 SSL 密碼、金鑰和重新協議的配置,以及測試您憑證的有效性。 +- 使用 [safe-regex](https://www.npmjs.com/package/safe-regex),確定您的正規表示式不易受到[正規表示式阻斷服務](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)攻擊。 -最後,如同其他任何的 Web 應用程式,Express 應用程式仍可能遭到各種 Web 型攻擊。請多加熟悉已知的 [Web 漏洞](https://www.owasp.org/www-project-top-ten/),並採取預防措施,來避免這些攻擊。 +[helmet]: <如果您使用 `helmet.js`,自會為您處理此事。> \ No newline at end of file diff --git a/zh-tw/advanced/developing-template-engines.md b/zh-tw/advanced/developing-template-engines.md old mode 100755 new mode 100644 index b32ae1d611..7fad8a44ca --- a/zh-tw/advanced/developing-template-engines.md +++ b/zh-tw/advanced/developing-template-engines.md @@ -1,15 +1,15 @@ --- layout: page title: 開發 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. menu: advanced lang: zh-tw -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. +redirect_from: " " --- # 開發 Express 範本引擎 -利用 `app.engine(ext, callback)` 方法,來建立您自己的範本引擎。`ext` 是指副檔名,`callback` 是範本引擎函數,它可接受下列項目作為參數:檔案的位置、options 物件,以及回呼函數。 +利用 `app.engine(ext, callback)` 方法,來建立您自己的範本引擎。`ext` 是指副檔名,`callback` 是範本引擎函數,它可接受下列項目作為參數:檔案的位置、options 物件,以及回呼函數。 `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. 下列程式碼範例說明如何實作一個相當簡單的範本引擎,以呈現 `.ntl` 檔。 @@ -17,9 +17,10 @@ description: Learn how to develop custom template engines for Express.js using a const fs = require('fs') // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { - if (err) return callback(new Error(err)) + if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', `${options.title}`) + const rendered = content.toString() + .replace('#title#', `${options.title}`) .replace('#message#', `

    ${options.message}

    `) return callback(null, rendered) }) @@ -28,17 +29,19 @@ app.set('views', './views') // specify the views directory app.set('view engine', 'ntl') // register the template engine ``` -現在,您的應用程式能夠呈現 `.ntl` 檔。請在 `views` 目錄中建立一個名稱是 `index.ntl` 的檔案,內含下列內容。 +Your app will now be able to render `.ntl` files. 現在,您的應用程式能夠呈現 `.ntl` 檔。請在 `views` 目錄中建立一個名稱是 `index.ntl` 的檔案,內含下列內容。 ```pug #title# #message# ``` -然後在應用程式中建立下列路由。 + +Then, create the following route in your app. ```js app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` -當您向首頁提出要求時,`index.ntl` 會呈現成 HTML。 + +當您向首頁提出要求時,`index.ntl` 會呈現成 HTML。 \ No newline at end of file diff --git a/zh-tw/advanced/healthcheck-graceful-shutdown.md b/zh-tw/advanced/healthcheck-graceful-shutdown.md new file mode 100644 index 0000000000..b5939f788b --- /dev/null +++ b/zh-tw/advanced/healthcheck-graceful-shutdown.md @@ -0,0 +1,34 @@ +--- +layout: page +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. +menu: advanced +lang: zh-tw +redirect_from: " " +--- + +# Health Checks and Graceful Shutdown + +## 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. + +### 範例 + +```js +const server = app.listen(port) + +process.on('SIGTERM', () => { + debug('SIGTERM signal received: closing HTTP server') + server.close(() => { + debug('HTTP server closed') + }) +}) +``` + +## 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/): + +- `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. \ No newline at end of file diff --git a/zh-tw/advanced/security-updates.md b/zh-tw/advanced/security-updates.md old mode 100755 new mode 100644 index b5b3742533..b88cecb8ea --- a/zh-tw/advanced/security-updates.md +++ b/zh-tw/advanced/security-updates.md @@ -1,47 +1,90 @@ --- layout: page title: Express 安全更新 +description: Review the latest security updates and patches for Express.js, including detailed vulnerability lists for different versions to help maintain a secure application. menu: advanced lang: zh-tw -description: Review the latest security updates and patches for Express.js, including - detailed vulnerability lists for different versions to help maintain a secure application. +redirect_from: " " --- # 安全更新
    + Node.js 的漏洞會直接影響 Express。因此,請[隨時監看 Node.js 漏洞](https://nodejs.org /en/blog/vulnerability/),並確保您所用的是最新的 Node.js 穩定版本。 + Therefore, [keep a watch on Node.js vulnerabilities](https://nodejs.org/en/blog/vulnerability/) and make sure you are using the latest stable version of Node.js.
    以下列舉已在指定的版本更新中修正的 Express 漏洞。 +{% capture security-policy %} +If you believe you have discovered a security vulnerability in Express, please see +[Security Policies and Procedures](/{{page.lang}}/resources/contributing.html#security-policies-and-procedures). +{% endcapture %} + +{% include admonitions/note.html content=security-policy %} + ## 4.x - * 4.11.1 - * 已修正 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路徑揭露漏洞 - * 4.10.7 - * 已修正 `express.static`([諮詢](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中的開放重新導向漏洞。 - * 4.8.8 - * 已修正 `express.static`([諮詢](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 可能洩漏 `fd`,而影響 `express.static` 和 `res.sendfile`。惡意的要求可能造成 `fd` 洩漏,最後導致 `EMFILE` 錯誤和伺服器無回應。 - * 4.8.0 - * 如果稀疏陣列在查詢字串中的索引過多,可能導致程序耗盡記憶體,而使伺服器當機。 - * 巢狀過深的查詢字串物件可能造成程序封鎖,使伺服器暫時沒有回應。 +- 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). +- 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`. +- 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. +- 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`. +- 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 `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. +- 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`. +- 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`. +- 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. +- 4.11.1 + - 已修正 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路徑揭露漏洞 +- 4.10.7 + - 已修正 `express.static`([諮詢](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中的開放重新導向漏洞。 +- 4.8.8 + - 已修正 `express.static`([諮詢](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 可能洩漏 `fd`,而影響 `express.static` 和 `res.sendfile`。惡意的要求可能造成 `fd` 洩漏,最後導致 `EMFILE` 錯誤和伺服器無回應。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 4.8.0 + - 如果稀疏陣列在查詢字串中的索引過多,可能導致程序耗盡記憶體,而使伺服器當機。 + - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily. ## 3.x - * 3.19.1 - * 已修正 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路徑揭露漏洞 - * 3.19.0 - * 已修正 `express.static`([諮詢](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中的開放重新導向漏洞。 - * 3.16.10 - * 已修正 `express.static` 中的目錄遍訪漏洞。 - * 3.16.6 - * 在某些情況下,Node.js 0.10 可能洩漏 `fd`,而影響 `express.static` 和 `res.sendfile`。惡意的要求可能造成 `fd` 洩漏,最後導致 `EMFILE` 錯誤和伺服器無回應。 - * 3.16.0 - * 如果稀疏陣列在查詢字串中的索引過多,可能導致程序耗盡記憶體,而使伺服器當機。 - * 巢狀過深的查詢字串物件可能造成程序封鎖,使伺服器暫時沒有回應。 - * 3.3.0 - * 404 回應(試圖進行不支援的方法置換)容易受到跨網站 Scripting 攻擊。 +
    + **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. + +If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/{{ page.lang }}/support#commercial-support-options). + +
    + +- 3.19.1 + - 已修正 `express.static`、`res.sendfile` 和 `res.sendFile` 中的根路徑揭露漏洞 +- 3.19.0 + - 已修正 `express.static`([諮詢](https://npmjs.com/advisories/35)、[CVE-2015-1164](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1164))中的開放重新導向漏洞。 +- 3.16.10 + - 已修正 `express.static` 中的目錄遍訪漏洞。 +- 3.16.6 + - 在某些情況下,Node.js 0.10 可能洩漏 `fd`,而影響 `express.static` 和 `res.sendfile`。惡意的要求可能造成 `fd` 洩漏,最後導致 `EMFILE` 錯誤和伺服器無回應。 Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. +- 3.16.0 + - 如果稀疏陣列在查詢字串中的索引過多,可能導致程序耗盡記憶體,而使伺服器當機。 + - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily. +- 3.3.0 + - 404 回應(試圖進行不支援的方法置換)容易受到跨網站 Scripting 攻擊。 \ No newline at end of file diff --git a/zh-tw/api.md b/zh-tw/api.md old mode 100755 new mode 100644 index c7ba9df0d5..8282f7f994 --- a/zh-tw/api.md +++ b/zh-tw/api.md @@ -1,28 +1,21 @@ --- layout: api -version: 4x -title: Express 4.x - API 參照 +version: 5x +title: Express 5.x - API 參照 +description: Access the API reference for Express.js detailing all modules, methods, and properties for building web applications with this version. lang: zh-tw -description: Access the API reference for Express.js detailing all modules, methods, - and properties for building web applications with this version. +redirect_from: " " --- -
    - -

    4.x API

    - - - {% include api/en/4x/express.md %} +
    +

    5.x API

    + {% include api/en/5x/express.md %} - {% include api/en/4x/app.md %} - + {% include api/en/5x/app.md %} - {% include api/en/4x/req.md %} - + {% include api/en/5x/req.md %} - {% include api/en/4x/res.md %} - + {% include api/en/5x/res.md %} - {% include api/en/4x/router.md %} - + {% include api/en/5x/router.md %}
    diff --git a/zh-tw/changelog/index.md b/zh-tw/changelog/index.md new file mode 100644 index 0000000000..c9fe997042 --- /dev/null +++ b/zh-tw/changelog/index.md @@ -0,0 +1,635 @@ +--- +layout: page +title: Express changelog +description: Stay updated with the release changelog for Express.js, detailing new features, bug fixes, and important changes across versions. +lang: zh-tw +sitemap: false +redirect_from: + - " " + - " " +--- + + + +
    + +# Release changelog + +All the latest updates, improvements, and fixes to Express + +## Express v5 + +{: id="5.x"} + +### 5.1.0 - Release date: 2025-03-31 + +{: id="5.0.1"} + +The 5.1.0 minor release includes some new features and improvements: + +- Support for sending responses as Uint8Array +- Added support for ETag option in `res.sendFile()` +- Added support for adding multiple links with the same rel with `res.links()` +- Performance: Use loop for acceptParams +- [body-parser@2.2.0](https://github.com/expressjs/body-parser/releases/tag/v2.2.0) + - Remove legacy node.js support checks for Brotli & `AsyncLocalStorage` + - Remove `unpipe` & `destroy` +- [router@2.2.0](https://github.com/pillarjs/router/releases/tag/v2.2.0) + - Restore `debug`. Now with the `router` scope instead of `express`. + - Remove legacy node.js support checks for `setImmediate` + - Deprecate non-native promise support + - Remove `after`, `safe-buffer`, `array-flatten`, `setprotoypeof`, `methods`, `utils-merge` +- [finalhandler@2.1.0](https://github.com/pillarjs/finalhandler/releases/tag/v2.1.0) + - Remove legacy node.js support checks for `headersSent`, `setImmediate`, & http2 support + - Remove `unpipe` +- Transitioned all remaining dependencies to use `^` ranges instead of locked versions +- Add package.json funding field to highlight our OpenCollective +- See [Changelog v5.1.0](https://github.com/expressjs/express/releases/tag/v5.1.0) + +### 5.0.1 - Release date: 2024-10-08 + +{: id="5.0.1"} + +The 5.0.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 5.0.0 - Release date: 2024-09-09 + +{: id="5.0.0"} + +Check the [migration guide](/{{page.lang}}/guide/migrating-5.html) with all the changes in this new version of Express. + +## Express v4 + +{: id="4.x"} + +### 4.21.2 - Release date: 2024-11-06 + +{: id="4.21.2"} + +The 4.21.2 patch release includes one security fix: + +- Update [pillajs/path-to-regexp](https://www.npmjs.com/package/path-to-regexp) to address a [vulnerability](https://github.com/advisories/GHSA-rhx6-c78j-4q9w). + +### 4.21.1 - Release date: 2024-10-08 + +{: id="4.21.1"} + +The 4.21.1 patch release includes one security fix: + +- Update [jshttps/cookie](https://www.npmjs.com/package/cookie) to address a [vulnerability](https://github.com/advisories/GHSA-pxg6-pf52-xh8x). + +### 4.21.0 - Release date: 2024-09-11 + +{: id="4.21.0"} + +The 4.21.0 minor release includes one new feature: + +- Deprecate `res.location("back")` and `res.redirect("back")` magic string + +### 4.20.0 - Release date: 2024-09-10 + +{: id="4.20.0"} + +The 4.20.0 minor release includes bug fixes and some new features, including: + +- The [`res.clearCookie()` method](/{{ page.lang }}/4x/api.html#res.clearCookie) deprecates `options.maxAge` and `options.expires` options. +- The [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) removes HTML link rendering. +- The [`express.urlencoded()` method](/{{ page.lang }}/4x/api.html#express.urlencoded) method now has a depth level of `32`, whereas it was previously `Infinity`. +- Adds support for named matching groups in the routes using a regex +- Removes encoding of `\`, `|`, and `^` to align better with URL spec + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4200--2024-09-10) + +### 4.19.2 - Release date: 2024-03-25 + +{: id="4.19.2"} + +- Improved fix for open redirect allow list bypass + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4192--2024-03-25) + +### 4.19.1 - Release date: 2024-03-20 + +{: id="4.19.1"} + +- Allow passing non-strings to res.location with new encoding handling checks + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4191--2024-03-20) + +### 4.19.0 - Release date: 2024-03-20 + +{: id="4.19.0"} + +- Prevent open redirect allow list bypass due to encodeurl +- deps: cookie@0.6.0 + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4190--2024-03-20) + +### 4.18.3 - Release date: 2024-02-29 + +{: id="4.18.3"} + +The 4.18.3 patch release includes the following bug fix: + +
      +
    • + Fix routing requests without method. ([commit](https://github.com/expressjs/express/commit/74beeac0718c928b4ba249aba3652c52fbe32ca8)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4183--2024-02-26) + +### 4.18.2 - Release date: 2022-10-08 + +{: id="4.18.2"} + +The 4.18.2 patch release includes the following bug fix: + +
      +
    • + Fix regression routing a large stack in a single route. ([commit](https://github.com/expressjs/express/commit/7ec5dd2b3c5e7379f68086dae72859f5573c8b9b)) +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4182--2022-10-08) + +### 4.18.1 - Release date: 2022-04-29 + +{: id="4.18.1"} + +The 4.18.1 patch release includes the following bug fix: + +
      +
    • + Fix the condition where if an Express application is created with a very large stack of routes, and all of those routes are sync (call `next()` synchronously), then the request processing may hang. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4181--2022-04-29). + +### 4.18.0 - Release date: 2022-04-25 + +{: id="4.18.0"} + +The 4.18.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The [`app.get()` method](/{{ page.lang }}/4x/api.html#app.get) and the [`app.set()` method](/{{ page.lang }}/4x/api.html#app.set) now ignores properties directly on `Object.prototype` when getting a setting value. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now accepts a "priority" option to set the Priority attribute on the Set-Cookie response header. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now rejects an Invalid Date object provided as the "expires" option. +
    • + +
    • + The [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) now works when `null` or `undefined` is explicitly provided as the "maxAge" argument. +
    • + +
    • + Starting with this version, Express supports Node.js 18.x. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts a "root" option to match [`res.sendFile()`](/{{ page.lang }}/4x/api.html#res.sendFile). +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) can be supplied with an `options` object without providing a `filename` argument, simplifying calls when the default `filename` is desired. +
    • + +
    • + The [`res.format()` method](/{{ page.lang }}/4x/api.html#res.format) now invokes the provided "default" handler with the same arguments as the type handlers (`req`, `res`, and `next`). +
    • + +
    • + The [`res.send()` method](/{{ page.lang }}/4x/api.html#res.send) will not attempt to send a response body when the response code is set to 205. +
    • + +
    • + The default error handler will now remove certain response headers that will break the error response rendering, if they were set previously. +
    • + +
    • + The status code 425 is now represented as the standard "Too Early" instead of "Unordered Collection". +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4180--2022-04-25). + +### 4.17.3 - Release date: 2022-02-16 + +{: id="4.17.3"} + +The 4.17.3 patch release includes one bug fix: + +
      +
    • + Update to [qs module](https://www.npmjs.com/package/qs) for a fix around parsing `__proto__` properties. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4173--2022-02-16). + +### 4.17.2 - Release date: 2021-12-16 + +{: id="4.17.2"} + +The 4.17.2 patch release includes the following bug fixes: + +
      +
    • + Fix handling of `undefined` in `res.jsonp` when a callback is provided. +
    • + +
    • + Fix handling of `undefined` in `res.json` and `res.jsonp` when `"json escape"` is enabled. +
    • + +
    • + Fix handling of invalid values to the `maxAge` option of `res.cookie()`. +
    • + +
    • + Update to [jshttp/proxy-addr module](https://www.npmjs.com/package/proxy-addr) to use `req.socket` over deprecated `req.connection`. +
    • + +
    • + Starting with this version, Express supports Node.js 14.x. +
    • + +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4172--2021-12-16). + +### 4.17.1 - Release date: 2019-05-25 + +{: id="4.17.1"} + +The 4.17.1 patch release includes one bug fix: + +
      +
    • + The change to the `res.status()` API has been reverted due to causing regressions in existing Express 4 applications. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4171--2019-05-25). + +### 4.17.0 - Release date: 2019-05-16 + +{: id="4.17.0"} + +The 4.17.0 minor release includes bug fixes and some new features, including: + +
      +
    • + The `express.raw()` and `express.text()` middleware have been added to provide request body parsing for more raw request payloads. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The `res.cookie()` API now supports the `"none"` value for the `sameSite` option. +
    • + +
    • + When the `"trust proxy"` setting is enabled, the `req.hostname` now supports multiple `X-Forwarded-For` headers in a request. +
    • + +
    • + Starting with this version, Express supports Node.js 10.x and 12.x. +
    • + +
    • + The `res.sendFile()` API now provides and more immediate and easier to understand error when a non-string is passed as the `path` argument. +
    • + +
    • + The `res.status()` API now provides and more immediate and easier to understand error when `null` or `undefined` is passed as the argument. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4170--2019-05-16). + +### 4.16.4 - Release date: 2018-10-10 + +{: id="4.16.4"} + +The 4.16.4 patch release includes various bug fixes: + +
      +
    • + Fix issue where `"Request aborted"` may be logged in `res.sendfile`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4164--2018-10-10). + +### 4.16.3 - Release date: 2018-03-12 + +{: id="4.16.3"} + +The 4.16.3 patch release includes various bug fixes: + +
      +
    • + Fix issue where a plain `%` at the end of the url in the `res.location` method or the `res.redirect` method would not get encoded as `%25`. +
    • + +
    • + Fix issue where a blank `req.url` value can result in a thrown error within the default 404 handling. +
    • + +
    • + Fix the generated HTML document for `express.static` redirect responses to properly include ``. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4163--2018-03-12). + +### 4.16.2 - Release date: 2017-10-09 + +{: id="4.16.2"} + +The 4.16.2 patch release includes a regression bug fix: + +
      +
    • + Fix a `TypeError` that can occur in the `res.send` method when a `Buffer` is passed to `res.send` and the `ETag` header is already set on the response. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4162--2017-10-09). + +### 4.16.1 - Release date: 2017-09-29 + +{: id="4.16.1"} + +The 4.16.1 patch release includes a regression bug fix: + +
      +
    • + Update to [pillarjs/send module](https://www.npmjs.com/package/send) to fix an edge case scenario regression that affected certain users of `express.static`. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4161--2017-09-29). + +### 4.16.0 - Release date: 2017-09-28 + +{: id="4.16.0"} + +The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including: + +
      +
    • + Update to [jshttp/forwarded module](https://www.npmjs.com/package/forwarded) 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`. +
    • + +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) to address a [vulnerability](https://npmjs.com/advisories/535) in the `mime` dependency. This may affect your application if untrusted string input is passed to the following APIs: `res.type()`. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has implemented a protection against the Node.js 8.5.0 [vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). Using any prior version of Express with Node.js 8.5.0 (that specific Node.js version) will make the following APIs vulnerable: `express.static`, `res.sendfile`, and `res.sendFile`. +
    • + +
    • + Starting with this version, Express supports Node.js 8.x. +
    • + +
    • + The new setting `"json escape"` can be enabled to escape characters in `res.json()`, `res.jsonp()` and `res.send()` responses that can trigger clients to sniff the response as HTML instead of honoring the `Content-Type`. This can help protect an Express app from a class of persistent XSS-based attacks. +
    • + +
    • + The [`res.download()` method](/{{ page.lang }}/4x/api.html#res.download) now accepts an optional `options` object. +
    • + +
    • + The `express.json()` and `express.urlencoded()` middleware have been added to provide request body parsing support out-of-the-box. This uses the [expressjs/body-parser module](https://www.npmjs.com/package/body-parser) module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support setting the `immutable` directive on the `Cache-Control` header. Setting this header with an appropriate `maxAge` will prevent supporting web browsers from sending any request to the server when the file is still in their cache. +
    • + +
    • + The [pillarjs/send module](https://www.npmjs.com/package/send) has an updated list of MIME types to better set the `Content-Type` of more files. There are 70 new types for file extensions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4160--2017-09-28). + +### 4.15.5 - Release date: 2017-09-24 + +{: id="4.15.5"} + +The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix: + +
      +
    • + Update to [debug module](https://www.npmjs.com/package/debug) to address a [vulnerability](https://snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) 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`. +
    • + +
    • + Update to [jshttp/fresh module](https://www.npmjs.com/package/fresh) fixes handling of modified headers with invalid dates and makes parsing conditional headers (like `If-None-Match`) faster. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4155--2017-09-24). + +### 4.15.4 - Release date: 2017-08-06 + +{: id="4.15.4"} + +The 4.15.4 patch release includes some minor bug fixes: + +
      +
    • + Fix array being set for `"trust proxy"` value being manipulated in certain conditions. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4154--2017-08-06). + +### 4.15.3 - Release date: 2017-05-16 + +{: id="4.15.3"} + +The 4.15.3 patch release includes a security update and some minor bug fixes: + +
      +
    • + Update a dependency of the [pillarjs/send module](https://www.npmjs.com/package/send) 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`. +
    • + +
    • + Fix error when `res.set` cannot add charset to `Content-Type`. +
    • + +
    • + Fix missing `` in HTML document. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4153--2017-05-16). + +### 4.15.2 - Release date: 2017-03-06 + +{: id="4.15.2"} + +The 4.15.2 patch release includes a minor bug fix: + +
      +
    • + Fix regression parsing keys starting with `[` in the extended (default) query parser. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4152--2017-03-06). + +### 4.15.1 - Release date: 2017-03-05 + +{: id="4.15.1"} + +The 4.15.1 patch release includes a minor bug fix: + +
      +
    • + Fix compatibility issue when using the datejs 1.x library where the [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) would incorrectly respond with 412 Precondition Failed. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4151--2017-03-05). + +### 4.15.0 - Release date: 2017-03-01 + +{: id="4.15.0"} + +The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 7.x. +
    • + +
    • + The [`express.static()` middleware](/{{ page.lang }}/4x/api.html#express.static) and [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now support the `If-Match` and `If-Unmodified-Since` request headers. +
    • + +
    • + Update to [jshttp/etag module](https://www.npmjs.com/package/etag) to generate the default ETags for responses which work when Node.js has [FIPS-compliant crypto enabled](https://nodejs.org/dist/latest/docs/api/cli.html#cli_enable_fips). +
    • + +
    • + Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4150--2017-03-01). + +### 4.14.1 - Release date: 2017-01-28 + +{: id="4.14.1"} + +The 4.14.1 patch release includes bug fixes and performance improvements, including: + +
      +
    • + Update to [pillarjs/finalhandler module](https://www.npmjs.com/package/finalhandler) fixes an exception when Express handles an `Error` object which has a `headers` property that is not an object. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4141--2017-01-28). + +### 4.14.0 - Release date: 2016-06-16 + +{: id="4.14.0"} + +The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including: + +
      +
    • + Starting with this version, Express supports Node.js 6.x. +
    • + +
    • + Update to [jshttp/negotiator module](https://www.npmjs.com/package/negotiator) fixes a [regular expression denial of service vulnerability](https://npmjs.com/advisories/106). +
    • + +
    • + The [`res.sendFile()` method](/{{ page.lang }}/4x/api.html#res.sendFile) now accepts two new options: `acceptRanges` and `cacheControl`. + +- `acceptRanges` (defaut is `true`), enables or disables accepting ranged requests. When disabled, the response does not send the `Accept-Ranges` header and ignores the contents of the `Range` request header. + +- `cacheControl`, (default is `true`), enables or disables the `Cache-Control` response header. Disabling it will ignore the `maxAge` option. + +- `res.sendFile` has also been updated to handle `Range` header and redirections better. + +
    • + +
    • + The [`res.location()` method](/{{ page.lang }}/4x/api.html#res.location) and [`res.redirect()` method](/{{ page.lang }}/4x/api.html#res.redirect) will now URL-encode the URL string, if it is not already encoded. +
    • + +
    • + The performance of the [`res.json()` method](/{{ page.lang }}/4x/api.html#res.json) and [`res.jsonp()` method](/{{ page.lang }}/4x/api.html#res.jsonp) have been improved in the common cases. +
    • + +
    • + The [jshttp/cookie module](https://www.npmjs.com/package/cookie) (in addition to a number of other improvements) has been updated and now the [`res.cookie()` method](/{{ page.lang }}/4x/api.html#res.cookie) supports the `sameSite` option to let you specify the [SameSite cookie attribute](https://tools.ietf.org/html/draft-west-first-party-cookies-07). + +{% capture note-4-14-0 %} + +``` +This attribute has not yet been fully standardized, may change in the future, and many clients may ignore it. +``` + +{% endcapture %} +{% include admonitions/note.html content=note-4-14-0 %} + +The possible value for the `sameSite` option are: + +- `true`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. +- `false`, which does not set the `SameSite` attribute. +- `'lax'`, which sets the `SameSite` attribute to `Lax` for lax same site enforcement. +- `'strict'`, which sets the `SameSite` attribute to `Strict` for strict same site enforcement. + +
    • + +
    • + Absolute path checking on Windows, which was incorrect for some cases, has been fixed. +
    • + +
    • + IP address resolution with proxies has been greatly improved. +
    • + +
    • + The [`req.range()` method](/{{ page.lang }}/4x/api.html#req.range) options object now supports a `combine` option (`false` by default), which when `true`, combines overlapping and adjacent ranges and returns them as if they were specified that way in the header. +
    • +
    + +For a complete list of changes in this release, see [History.md](https://github.com/expressjs/express/blob/master/History.md#4140--2016-06-16). + +
    diff --git a/zh-tw/guide/behind-proxies.md b/zh-tw/guide/behind-proxies.md old mode 100755 new mode 100644 index a6ce80599d..199fcea2d3 --- a/zh-tw/guide/behind-proxies.md +++ b/zh-tw/guide/behind-proxies.md @@ -1,20 +1,22 @@ --- layout: page title: 位於 Proxy 背後的 Express +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. menu: guide lang: zh-tw -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. +redirect_from: " " --- # 位於 Proxy 背後的 Express -當 Express 應用程式是在 Proxy 背後執行時,請使用 [app.set()](/{{ page.lang }}/4x/api.html#app.set),將 `trust proxy` 應用程式變數設為下表列出的其中一值。 +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.
    -雖然未設定 `trust proxy` 應用程式變數時,應用程式並不會無法執行,但除非配置 `trust proxy`,否則,它會將 Proxy 的 IP 位址登錄成錯誤的用戶端 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.
    +The application setting `trust proxy` may be set to one of the values listed in the following table. + @@ -23,17 +25,21 @@ description: Learn how to configure Express.js applications to work correctly be - + - +
    類型
    若為 `true`,會將用戶端的 IP 位址視為 `X-Forwarded-*` 標頭中的最左側項目。 -若為 `false`,會將應用程式視為直接面對網際網路,且用戶端的 IP 位址衍生自 `req.connection.remoteAddress`。這是預設值。 +若為 `false`,會將應用程式視為直接面對網際網路,且用戶端的 IP 位址衍生自 `req.connection.remoteAddress`。這是預設值。 This is the default setting. + +
    +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. +
    IP 位址IP addresses -要信任的 IP 位址、子網路,或是 IP 位址與子網路陣列。下列清單顯示預先配置的子網路名稱: +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: -* 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` +- 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` 您可以採下列任何方式來設定 IP 位址: @@ -44,20 +50,24 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple s app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array ``` -若有指定,位址判定程序中會排除 IP 位址或子網路,且會將最接近應用程式伺服器的未授信 IP 位址判斷為用戶端的 IP 位址。 +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. +
    號碼 -信任來自正面 Proxy 伺服器的第 `n` 個躍點就是用戶端。 +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. + +
    +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. +
    函數Function -自訂信任實作。只有在您清楚自己要做什麼時,才能使用此項。 - +Custom trust implementation. ```js app.set('trust proxy', (ip) => { @@ -65,20 +75,22 @@ app.set('trust proxy', (ip) => { else return false }) ``` +
    -如果設定 `false` `trust proxy` 以外的值,會造成三項重要的變更: +Enabling `trust proxy` will have the following impact:
    • [req.hostname](/{{ page.lang }}/api.html#req.hostname) 值會衍生自 `X-Forwarded-Host` 標頭中所設定的值,且該值可能由用戶端或 Proxy 所設定。
    • 反向 Proxy 可能設定 `X-Forwarded-Proto`,以告知應用程式它是 `https` 或 `http` 或甚至是無效的名稱。[req.protocol](/{{ page.lang }}/api.html#req.protocol) 會反映此值。 + This value is reflected by [req.protocol](/{{ page.lang }}/api.html#req.protocol).
    • [req.ip](/{{ page.lang }}/api.html#req.ip) 和 [req.ips](/{{ page.lang }}/api.html#req.ips) 值中會移入 `X-Forwarded-For` 中的位址清單。
    -會使用 [proxy-addr](https://www.npmjs.com/package/proxy-addr) 套件來實作 `trust proxy` 設定。如需相關資訊,請參閱其說明文件。 +會使用 [proxy-addr](https://www.npmjs.com/package/proxy-addr) 套件來實作 `trust proxy` 設定。如需相關資訊,請參閱其說明文件。 For more information, see its documentation. diff --git a/zh-tw/guide/database-integration.md b/zh-tw/guide/database-integration.md old mode 100755 new mode 100644 index 505a65740a..7569e2397e --- a/zh-tw/guide/database-integration.md +++ b/zh-tw/guide/database-integration.md @@ -1,336 +1,491 @@ --- layout: page title: Express 資料庫整合 +description: Discover how to integrate various databases with Express.js applications, including setup examples for MongoDB, MySQL, PostgreSQL, and more. menu: guide lang: zh-tw -description: Discover how to integrate various databases with Express.js applications, - including setup examples for MongoDB, MySQL, PostgreSQL, and more. +redirect_from: " " --- # 資料庫整合 -如果要在 Express 應用程式中新增連接資料庫的功能,只需在您的應用程式中載入資料庫的適當 Node.js 驅動程式即可。本文件簡要說明如何在您的 Express 應用程式中新增和使用一些最常用的 Node.js 資料庫系統模組。 - -* [Cassandra](#cassandra) -* [CouchDB](#couchdb) -* [LevelDB](#leveldb) -* [MySQL](#mysql) -* [MongoDB](#mongo) -* [Neo4j](#neo4j) -* [PostgreSQL](#postgres) -* [Redis](#redis) -* [SQLite](#sqlite) -* [ElasticSearch](#elasticsearch) +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: + +- [Cassandra](#cassandra) +- [Couchbase](#couchbase) +- [CouchDB](#couchdb) +- [LevelDB](#leveldb) +- [MySQL](#mysql) +- [MongoDB](#mongo) +- [Neo4j](#neo4j) +- [Oracle](#oracle) +- [PostgreSQL](#postgres) +- [Redis](#redis) +- +- [SQLite](#sqlite) +- [ElasticSearch](#elasticsearch)
    -這些資料庫驅動程式只是眾多可用驅動程式中的一部分。如需其他選項,請在 [npm](https://www.npmjs.com/) 網站中搜尋。 +These database drivers are among many that are available. For other options, +search on the [npm](https://www.npmjs.com/) site.
    - - ## Cassandra **模組**:[cassandra-driver](https://github.com/datastax/nodejs-driver) **安裝** +### Installation + ```bash $ npm install cassandra-driver ``` -**範例** +### 範例 + +```js +const cassandra = require('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) -
    -
    -var cassandra = require('cassandra-driver');
    -var client = new cassandra.Client({ contactPoints: ['localhost']});
    +### Installation
     
    -client.execute('select key from system.local', function(err, result) {
    -  if (err) throw err;
    -  console.log(result.rows[0]);
    -});
    -
    -
    +```bash +$ npm install couchbase +``` - +### 範例 + +```js +const couchbase = require('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) **安裝** +### Installation + ```bash $ npm install nano ``` -**範例** +### 範例 -
    -
    -var nano = require('nano')('http://localhost:5984');
    -nano.db.create('books');
    -var books = nano.db.use('books');
    +```js
    +const nano = require('nano')('http://localhost:5984')
    +nano.db.create('books')
    +const books = nano.db.use('books')
     
    -//Insert a book document in the books database
    -books.insert({name: 'The Art of war'}, null, function(err, body) {
    -  if (!err){
    -    console.log(body);
    +// Insert a book document in the books database
    +books.insert({ name: 'The Art of war' }, null, (err, body) => {
    +  if (err) {
    +    console.log(err)
    +  } else {
    +    console.log(body)
       }
    -});
    +})
     
    -//Get a list of all books
    -books.list(function(err, body){
    -  console.log(body.rows);
    -}
    -
    -
    - - +// Get a list of all books +books.list((err, body) => { + if (err) { + console.log(err) + } else { + console.log(body.rows) + } +}) +``` ## LevelDB **模組**:[levelup](https://github.com/rvagg/node-levelup) **安裝** +### Installation + ```bash $ npm install level levelup leveldown ``` -**範例** +### 範例 -
    -
    -var levelup = require('levelup');
    -var db = levelup('./mydb');
    +```js
    +const levelup = require('levelup')
    +const db = levelup('./mydb')
     
    -db.put('name', 'LevelUP', function (err) {
    +db.put('name', 'LevelUP', (err) => {
    +  if (err) return console.log('Ooops!', err)
     
    -  if (err) return console.log('Ooops!', err);
    -  db.get('name', function (err, value) {
    -    if (err) return console.log('Ooops!', err);
    -    console.log('name=' + value)
    -  });
    +  db.get('name', (err, value) => {
    +    if (err) return console.log('Ooops!', err)
     
    -});
    -
    -
    - - + console.log(`name=${value}`) + }) +}) +``` ## MySQL **模組**:[mysql](https://github.com/felixge/node-mysql/) **安裝** +### Installation + ```bash $ npm install mysql ``` -**範例** +### 範例 -
    -
    -var mysql      = require('mysql');
    -var connection = mysql.createConnection({
    -  host     : 'localhost',
    -  user     : 'dbuser',
    -  password : 's3kreee7'
    -});
    +```js
    +const mysql = require('mysql')
    +const connection = mysql.createConnection({
    +  host: 'localhost',
    +  user: 'dbuser',
    +  password: 's3kreee7',
    +  database: 'my_db'
    +})
     
    -connection.connect();
    +connection.connect()
     
    -connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
    -  if (err) throw err;
    -  console.log('The solution is: ', rows[0].solution);
    -});
    +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
    +  if (err) throw err
     
    -connection.end();
    -
    -
    + console.log('The solution is: ', rows[0].solution) +}) - +connection.end() +``` ## MongoDB **模組**:[mongodb](https://github.com/mongodb/node-mongodb-native) **安裝** +### Installation + ```bash $ npm install mongodb ``` -**範例** +### Example (v2.\*) -
    -
    -var MongoClient = require('mongodb').MongoClient;
    +```js
    +const MongoClient = require('mongodb').MongoClient
     
    -MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
    -  if (err) {
    -    throw err;
    -  }
    -  db.collection('mammals').find().toArray(function(err, result) {
    -    if (err) {
    -      throw err;
    -    }
    -    console.log(result);
    -  });
    -});
    -
    -
    +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { + if (err) throw err -如果您需要 MongoDB 物件模型驅動程式,請查看 [Mongoose](https://github.com/LearnBoost/mongoose)。 + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +### Example (v3.\*) - +```js +const MongoClient = require('mongodb').MongoClient + +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { + if (err) throw err + + const db = client.db('animals') + + db.collection('mammals').find().toArray((err, result) => { + if (err) throw err + + console.log(result) + }) +}) +``` + +如果您需要 MongoDB 物件模型驅動程式,請查看 [Mongoose](https://github.com/LearnBoost/mongoose)。 ## Neo4j -**模組**:[apoc](https://github.com/hacksparrow/apoc) -**安裝** +這些資料庫驅動程式只是眾多可用驅動程式中的一部分。如需其他選項,請在 [npm](https://www.npmjs.com/) 網站中搜尋。 + +### Installation ```bash -$ npm install apoc +$ npm install neo4j-driver ``` -**範例** +### 範例 -
    -
    -var apoc = require('apoc');
    +```js
    +const neo4j = require('neo4j-driver')
    +const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))
     
    -apoc.query('match (n) return n').exec().then(
    -  function (response) {
    -    console.log(response);
    -  },
    -  function (fail) {
    -    console.log(fail);
    +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
    +```
    +
    +### 範例
    +
    +```js
    +const oracledb = require('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) **安裝** +### Installation + ```bash $ npm install pg-promise ``` -**範例** +### 範例 -
    -
    -var pgp = require("pg-promise")(/*options*/);
    -var db = pgp("postgres://username:password@host:port/database");
    +```js
    +const pgp = require('pg-promise')(/* options */)
    +const db = pgp('postgres://username:password@host:port/database')
     
    -db.one("SELECT $1 AS value", 123)
    -    .then(function (data) {
    -        console.log("DATA:", data.value);
    -    })
    -    .catch(function (error) {
    -        console.log("ERROR:", error);
    -    });
    -
    -
    - - +db.one('SELECT $1 AS value', 123) + .then((data) => { + console.log('DATA:', data.value) + }) + .catch((error) => { + console.log('ERROR:', error) + }) +``` ## Redis **模組**:[redis](https://github.com/mranney/node_redis) **安裝** +### Installation + ```bash $ npm install redis ``` -**範例** +### 範例 + +```js +const redis = require('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 -
    -
    -var client = require('redis').createClient();
    +**Module**: [tedious](https://github.com/tediousjs/tedious)
     
    -client.on('error', function (err) {
    -  console.log('Error ' + err);
    -});
    +### Installation
     
    -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);
    +```bash
    +$ npm install tedious
    +```
     
    -client.hkeys('hash key', function (err, replies) {
    +### 範例
     
    -  console.log(replies.length + ' replies:');
    -  replies.forEach(function (reply, i) {
    -    console.log('    ' + i + ': ' + reply);
    -  });
    +```js
    +const Connection = require('tedious').Connection
    +const Request = require('tedious').Request
     
    -  client.quit();
    +const config = {
    +  server: 'localhost',
    +  authentication: {
    +    type: 'default',
    +    options: {
    +      userName: 'your_username', // update me
    +      password: 'your_password' // update me
    +    }
    +  }
    +}
    +
    +const connection = new Connection(config)
    +
    +connection.on('connect', (err) => {
    +  if (err) {
    +    console.log(err)
    +  } else {
    +    executeStatement()
    +  }
    +})
     
    -});
    -
    -
    +function executeStatement () { + request = new Request("select 123, 'hello world'", (err, rowCount) => { + if (err) { + console.log(err) + } else { + console.log(`${rowCount} rows`) + } + connection.close() + }) + + request.on('row', (columns) => { + columns.forEach((column) => { + if (column.value === null) { + console.log('NULL') + } else { + console.log(column.value) + } + }) + }) - + connection.execSql(request) +} +``` ## SQLite **模組**:[sqlite3](https://github.com/mapbox/node-sqlite3) **安裝** +### Installation + ```bash $ npm install sqlite3 ``` -**範例** - -
    -
    -var sqlite3 = require('sqlite3').verbose();
    -var db = new sqlite3.Database(':memory:');
    +### 範例
     
    -db.serialize(function() {
    +```js
    +const sqlite3 = require('sqlite3').verbose()
    +const db = new sqlite3.Database(':memory:')
     
    -  db.run('CREATE TABLE lorem (info TEXT)');
    -  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
    +db.serialize(() => {
    +  db.run('CREATE TABLE lorem (info TEXT)')
    +  const stmt = db.prepare('INSERT INTO lorem VALUES (?)')
     
    -  for (var i = 0; i < 10; i++) {
    -    stmt.run('Ipsum ' + i);
    +  for (let i = 0; i < 10; i++) {
    +    stmt.run(`Ipsum ${i}`)
       }
     
    -  stmt.finalize();
    -
    -  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
    -    console.log(row.id + ': ' + row.info);
    -  });
    -});
    +  stmt.finalize()
     
    -db.close();
    -
    -
    + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) + }) +}) - +db.close() +``` ## ElasticSearch **模組**:[elasticsearch](https://github.com/elastic/elasticsearch-js) **安裝** +### Installation + ```bash $ npm install elasticsearch ``` -**範例** +### 範例 -
    -
    -var elasticsearch = require('elasticsearch');
    -var client = elasticsearch.Client({
    +```js
    +const elasticsearch = require('elasticsearch')
    +const client = elasticsearch.Client({
       host: 'localhost:9200'
    -});
    +})
     
     client.search({
       index: 'books',
    @@ -343,10 +498,9 @@ client.search({
           }
         }
       }
    -}).then(function(response) {
    -  var hits = response.hits.hits;
    -}, function(error) {
    -  console.trace(error.message);
    -});
    -
    -
    +}).then((response) => { + const hits = response.hits.hits +}, (error) => { + console.trace(error.message) +}) +``` diff --git a/zh-tw/guide/debugging.md b/zh-tw/guide/debugging.md old mode 100755 new mode 100644 index 820b3f8286..a92ae53bfd --- a/zh-tw/guide/debugging.md +++ b/zh-tw/guide/debugging.md @@ -1,10 +1,10 @@ --- layout: page title: 對 Express 除錯 +description: Learn how to enable and use debugging logs in Express.js applications by setting the DEBUG environment variable for enhanced troubleshooting. menu: guide lang: zh-tw -description: Learn how to enable and use debugging logs in Express.js applications - by setting the DEBUG environment variable for enhanced troubleshooting. +redirect_from: " " --- # 對 Express 除錯 @@ -18,7 +18,7 @@ $ DEBUG=express:* node index.js 在 Windows 中,使用對應指令。 ```bash -> set DEBUG=express:* & node index.js +> $env:DEBUG = "express:*"; node index.js ``` 對 [express generator](/{{ page.lang }}/starter/generator.html) 產生的預設應用程式執行這個指令,會列印下列輸出: @@ -59,11 +59,11 @@ $ DEBUG=express:* node ./bin/www express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms - express:router use / <anonymous> +0ms + express:router use / &lt;anonymous&gt; +0ms express:router:layer new / +0ms ``` @@ -87,7 +87,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`,以此類推。 Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on. ## `express` 產生的應用程式 @@ -104,3 +104,27 @@ $ DEBUG=sample-app:* node ./bin/www ```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: + +| 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. | + +{% capture debug-text %} + +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 +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +{% endcapture %} + +{% include admonitions/note.html content=debug-text %} diff --git a/zh-tw/guide/error-handling.md b/zh-tw/guide/error-handling.md old mode 100755 new mode 100644 index c88008d02c..81ba18abf3 --- a/zh-tw/guide/error-handling.md +++ b/zh-tw/guide/error-handling.md @@ -1,16 +1,195 @@ --- layout: page title: Express 錯誤處理 +description: Understand how Express.js handles errors in synchronous and asynchronous code, and learn to implement custom error handling middleware for your applications. menu: guide lang: zh-tw -description: Understand how Express.js handles errors in synchronous and asynchronous - code, and learn to implement custom error handling middleware for your applications. +redirect_from: " " --- # 錯誤處理 -錯誤處理中介軟體函數的定義方式,與其他中介軟體函數相同,差別在於錯誤處理函數的引數是四個而非三個:`(err, req, res, next)`。例如: +_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. +## Catching Errors + +It's important to ensure that Express catches all errors that occur while +running route handlers and middleware. + +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: + +```js +app.get('/', (req, res) => { + throw new Error('BROKEN') // Express will catch this on its own. +}) +``` + +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: + +```js +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { + if (err) { + next(err) // Pass errors to Express. + } else { + res.send(data) + } + }) +}) +``` + +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: + +```js +app.get('/user/:id', async (req, res, next) => { + const user = await getUserById(req.params.id) + res.send(user) +}) +``` + +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. + +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. + +If the callback in a sequence provides no data, only errors, you can simplify +this code as follows: + +```js +app.get('/', [ + function (req, res, next) { + fs.writeFile('/inaccessible-path', 'data', next) + }, + function (req, res) { + res.send('OK') + } +]) +``` + +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. + +You must catch errors that occur in asynchronous code invoked by route handlers or +middleware and pass them to Express for processing. For example: + +```js +app.get('/', (req, res, next) => { + setTimeout(() => { + try { + throw new Error('BROKEN') + } catch (err) { + next(err) + } + }, 100) +}) +``` + +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. + +Use promises to avoid the overhead of the `try...catch` block or when using functions +that return promises. For example: + +```js +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { + throw new Error('BROKEN') + }).catch(next) // Errors will be passed to Express. +}) +``` + +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. + +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('/', [ + function (req, res, next) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { + res.locals.data = data + next(err) + }) + }, + function (req, res) { + res.locals.data = res.locals.data.split(',')[1] + res.send(res.locals.data) + } +]) +``` + +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. + +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. + +## 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. + +如果您傳遞錯誤至 `next()`,且您沒有在錯誤處理常式中處理它,將會交由內建錯誤處理常式處理;該錯誤會連同堆疊追蹤寫入至用戶端。在正式作業環境中,則不包含堆疊追蹤。 The stack trace is not included +in the production environment. + +
    +將 `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. + +在您開始撰寫回應之後,一旦在呼叫 `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: + +```js +function errorHandler (err, req, res, next) { + if (res.headersSent) { + return next(err) + } + res.status(500) + res.render('error', { error: err }) +} +``` + +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. + +Other error handling middleware can be found at [Express middleware](/{{ page.lang }}/resources/middleware.html). + +## Writing error handlers + +錯誤處理中介軟體函數的定義方式,與其他中介軟體函數相同,差別在於錯誤處理函數的引數是四個而非三個:`(err, req, res, next)`。例如: For example: ```js app.use((err, req, res, next) => { @@ -25,22 +204,31 @@ app.use((err, req, res, next) => { const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic }) ``` -中介軟體函數內的回應可以是任何您喜好的格式,如:HTML 錯誤頁面、簡式訊息或 JSON 字串。 +Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string. -為了方便組織(和更高層次的架構),您可以定義數個錯誤處理中介軟體函數,就像您處理一般中介軟體函數一樣。舉例來說,如果您想為使用及沒有使用 `XHR` 所建立的要求,各定義一個錯誤處理程式,您可以使用下列指令: +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: ```js const bodyParser = require('body-parser') const methodOverride = require('method-override') -app.use(bodyParser()) +app.use(bodyParser.urlencoded({ + extended: true +})) +app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) @@ -58,6 +246,8 @@ function logErrors (err, req, res, next) { 此外在本例中,`clientErrorHandler` 定義成如下;在此情況下,會將錯誤明確傳遞給下一個: +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) { if (req.xhr) { @@ -67,6 +257,7 @@ function clientErrorHandler (err, req, res, next) { } } ``` + "catch-all" `errorHandler` 函數的實作方式如下: ```js @@ -76,18 +267,16 @@ function errorHandler (err, req, res, next) { } ``` -不論您傳遞何者給 `next()` 函數(`'route'` 字串除外),Express 都會將現行要求視為發生錯誤,且會跳過其餘任何的非錯誤處理路由和中介軟體函數。如果您想以某種方式來處理該錯誤,您必須按照下一節的說明來建立錯誤處理路由。 - -如果您的路由處理程式有多個回呼函數,可以使用 `route` 參數來跳到下一個路由處理程式。例如: - +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: ```js app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { - // continue handling this request next('route') + } else { + next() } }, (req, res, next) => { PaidContent.find((err, doc) => { @@ -96,31 +285,9 @@ app.get('/a_route_behind_paywall', }) }) ``` -在本例中,會跳過 `getPaidContent` 處理程式,但是會繼續執行 `app` 中 `/a_route_behind_paywall` 的其餘處理程式。 - -
    -呼叫 `next()` 和 `next(err)`,指出現行處理程式已完成以及處於何種狀態。除了依上述說明設定成用來處理錯誤的那些處理程式,`next(err)` 會跳過處理程式鏈中其餘所有的處理程式。
    - -## 預設錯誤處理程式 - -Express 隨附一個內建錯誤處理常式,它會處理應用程式中可能遇到的任何錯誤。這個預設錯誤處理中介軟體函數新增於中介軟體函數堆疊尾端。 -如果您傳遞錯誤至 `next()`,且您沒有在錯誤處理常式中處理它,將會交由內建錯誤處理常式處理;該錯誤會連同堆疊追蹤寫入至用戶端。在正式作業環境中,則不包含堆疊追蹤。 +在本例中,會跳過 `getPaidContent` 處理程式,但是會繼續執行 `app` 中 `/a_route_behind_paywall` 的其餘處理程式。
    -將 `NODE_ENV` 環境變數設為 `production`,以便在正式作業模式下執行應用程式。 +Calls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next(err)` will skip all remaining handlers in the chain except for those that are set up to handle errors as described above.
    - -在您開始撰寫回應之後,一旦在呼叫 `next()` 時才發生錯誤(例如,當您將回應串流輸出至用戶端時遇到錯誤),Express 的預設錯誤處理程式會關閉連線,並使要求失敗。 - -因此,在您新增自訂錯誤處理常式時,如果標頭已傳送給用戶端,您會希望委派給 Express 中的預設錯誤處理機制處理: - -```js -function errorHandler (err, req, res, next) { - if (res.headersSent) { - return next(err) - } - res.status(500) - res.render('error', { error: err }) -} -``` diff --git a/zh-tw/guide/migrating-4.md b/zh-tw/guide/migrating-4.md old mode 100755 new mode 100644 index 2e512c198e..a7091b26f8 --- a/zh-tw/guide/migrating-4.md +++ b/zh-tw/guide/migrating-4.md @@ -1,17 +1,17 @@ --- layout: page title: 移轉至 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. menu: guide lang: zh-tw -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. +redirect_from: " " --- # 移至 Express 4

    概觀

    -Express 4 是對 Express 3 的突破性變更。也就是說,如果您在其相依關係中更新 Express 版本,現有的 Express 3 應用程式將無法運作。 +Express 4 是對 Express 3 的突破性變更。也就是說,如果您在其相依關係中更新 Express 版本,現有的 Express 3 應用程式將無法運作。 That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies. 本文涵蓋: @@ -26,7 +26,7 @@ Express 4 是對 Express 3 的突破性變更。也就是說,如果您在其 Express 4 有數項明顯的變更:
      -
    • Express 核心和中介軟體系統的變更。Connect 和內建中介軟體的相依關係已移除,因此您必須自行新增中介軟體。 +
    • Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself.
    • 路由系統的變更。
    • 其他各項變更。
    • @@ -34,16 +34,18 @@ Express 4 有數項明顯的變更: 另請參閱: -* [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) +- [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)

      Express 核心和中介軟體系統的變更

      -Express 4 不再相依於 Connect,除了 `express.static` 函數,其他所有的內建中介軟體皆已從其核心移除。也就是說,Express 現在是一個獨立的路由與中介軟體 Web 架構,Express 的版本化與版次不受中介軟體更新的影響。 +Express 4 不再相依於 Connect,除了 `express.static` 函數,其他所有的內建中介軟體皆已從其核心移除。也就是說,Express 現在是一個獨立的路由與中介軟體 Web 架構,Express 的版本化與版次不受中介軟體更新的影響。 This means that +Express is now an independent routing and middleware web framework, and +Express versioning and releases are not affected by middleware updates. -由於沒有內建中介軟體,您必須明確新增執行您應用程式所需的所有中介軟體。只需遵循下列步驟: +由於沒有內建中介軟體,您必須明確新增執行您應用程式所需的所有中介軟體。只需遵循下列步驟: Simply follow these steps: 1. 安裝模組:`npm install --save ` 2. 在您的應用程式中,需要模組:`require('module-name')` @@ -52,7 +54,7 @@ Express 4 不再相依於 Connect,除了 `express.static` 函數,其他所 下表列出 Express 3 中介軟體和其在 Express 4 中的對應項目。 - + @@ -84,23 +86,26 @@ Express 4 不再相依於 Connect,除了 `express.static` 函數,其他所 -
      Express 3Express 4
      Express 3Express 4
      express.bodyParser body-parser + multer
      serve-index
      express.static serve-static
      +
    以下是 Express 4 中介軟體的[完整清單](https://github.com/senchalabs/connect#middleware)。 -在大部分情況下,只需將舊有第 3 版中介軟體取代為其 Express 4 對應項目。如需詳細資料,請參閱 GitHub 中的模組說明文件。 +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.

    app.use 接受參數

    -在第 4 版中,您可以使用變數參數,來定義中介軟體函數的載入路徑,然後從路由處理程式讀取參數值。例如: - +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: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ``` +

    路由系統

    @@ -110,32 +115,36 @@ Apps 現在隱含地載入了路由中介軟體,因此您不用再擔心該中 路由的定義方式不變,但是路由系統多了兩個新特性,可協助您組織路由: {: .doclist } -* 新方法 `app.route()`,用來為路由路徑建立可鏈接的路由處理程式。 -* 新類別 `express.Router`,用來建立可裝載的模組路由處理程式。 + +- 新方法 `app.route()`,用來為路由路徑建立可鏈接的路由處理程式。 +- 新類別 `express.Router`,用來建立可裝載的模組路由處理程式。

    app.route() 方法

    -新的 `app.route()` 方法可讓您為路由路徑建立可鏈接的路由處理程式。由於是在單一位置指定路徑,建立模組路由很有用,因為它可減少冗餘和打錯字的情況。如需路由的相關資訊,請參閱 [`Router()` 說明文件](/{{ page.lang }}/4x/api.html#router)。 +新的 `app.route()` 方法可讓您為路由路徑建立可鏈接的路由處理程式。由於是在單一位置指定路徑,建立模組路由很有用,因為它可減少冗餘和打錯字的情況。如需路由的相關資訊,請參閱 [`Router()` 說明文件](/{{ page.lang }}/4x/api.html#router)。 Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more +information about routes, see [`Router()` documentation](/{{ page.lang }}/4x/api.html#router). 下列範例顯示利用 `app.route()` 函數所定義的路由處理程式鏈。 ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ```

    express.Router 類別

    -有助於組織路由的另一項特性是一個新類別 `express.Router`,可用來建立可裝載的模組路由處理程式。`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". 下列範例是將路由器建立成模組、 在其中載入中介軟體、定義一些路由,並將它裝載在主要應用程式中的路徑。 @@ -147,16 +156,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -168,7 +177,7 @@ module.exports = router ```js var birds = require('./birds') -/// ... +// ... app.use('/birds', birds) ``` @@ -182,9 +191,9 @@ app.use('/birds', birds) 下表列出 Express 4 其他小幅卻很重要的變更: - - - + + + @@ -195,7 +204,10 @@ app.use('/birds', birds) `http.createServer()` @@ -203,7 +215,9 @@ app.use('/birds', birds) `app.configure()` @@ -234,7 +248,7 @@ Express 4 中依預設會停用 `json spaces` 應用程式內容。 `req.params` @@ -242,7 +256,7 @@ Express 4 中依預設會停用 `json spaces` 應用程式內容。 `res.locals` @@ -282,15 +296,18 @@ Express 4 中依預設會停用 `json spaces` 應用程式內容。 `res.setHeader('Set-Cookie', val)` -
    物件說明
    ObjectDescription
    Node.js + 不再需要 `http` 模組,除非您需要直接使用它 (socket.io/SPDY/HTTPS)。應用程式可藉由使用 `app.listen()` 函數來啟動。 + The app can be started by using the +`app.listen()` function.
    +The `app.configure()` function has been removed. `app.configure()` 函數已移除。請使用 `process.env.NODE_ENV` 或 `app.get('env')` 函數來偵測環境,並據以配置應用程式。 +
    -之前是陣列;現在是物件。 +Was an array; now an object.
    -之前是函數;現在是物件。 +Was a function; now an object.
    +Functionality is now limited to setting the basic cookie value. 現在功能僅限於設定基本 Cookie 值。請使用 `res.cookie()` 來取得新增的功能。 +
    +

    應用程式移轉範例

    下列範例顯示如何將 Express 3 應用程式移轉至 Express 4。值得一提的檔案是 `app.js` 和 `package.json`。 +The files of interest are `app.js` and `package.json`.

    第 3 版應用程式 @@ -329,7 +346,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -366,11 +383,13 @@ $ npm install serve-favicon morgan method-override express-session body-parser m 對 `app.js` 進行下列變更: 1. `express` 物件中不再提供內建 Express 中介軟體函數 -`express.favicon`、`express.logger`, `express.methodOverride`、`express.session`、`express.bodyParser` 和 `express.errorHandler`。您必須手動安裝其替代項目,並將它們載入到應用程式。 + `express.favicon`、`express.logger`, `express.methodOverride`、`express.session`、`express.bodyParser` 和 `express.errorHandler`。您必須手動安裝其替代項目,並將它們載入到應用程式。 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. + 不再需要載入 `app.router` 函數。它不是有效的 Express 4 應用程式物件,因此請移除 `app.use(app.router);` 程式碼。 -3. 請確定中介軟體函數的載入順序正確 - 載入應用程式路由之後,再載入 `errorHandler`。 +3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes.

    第 4 版應用程式

    @@ -391,7 +410,7 @@ $ npm install serve-favicon morgan method-override express-session body-parser m "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", - "pug": "^2.0.0-beta6", + "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", @@ -402,7 +421,8 @@ $ 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 var http = require('http') @@ -456,16 +476,17 @@ server.listen(app.get('port'), () => { 除非您需要直接使用 `http` 模組 (socket.io/SPDY/HTTPS),並不需要載入它,只需採下列方式就能啟動應用程式: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ```
    -

    執行應用程式

    +

    Run the app

    -移轉程序已完成,現在應用程式是一個 Express 4 應用程式。若要確認,請使用下列指令來啟動應用程式: +The migration process is complete, and the app is now an +Express 4 app. To confirm, start the app by using the following command: ```bash $ node . @@ -497,14 +518,15 @@ $ npm install -g express-generator 現在,您系統上的 `express` 指令已更新為 Express 4 產生器。 -

    應用程式產生器的變更

    +

    Changes to the app generator

    除了以下,指令的選項與用法大致不變: {: .doclist } -* 已移除 `--sessions` 選項。 -* 已移除 `--jshtml` 選項。 -* 新增了 `--hogan` 選項,以支援 [Hogan.js](http://twitter.github.io/hogan.js/)。 + +- 已移除 `--sessions` 選項。 +- 已移除 `--jshtml` 選項。 +- 新增了 `--hogan` 選項,以支援 [Hogan.js](http://twitter.github.io/hogan.js/)。

    範例

    @@ -526,17 +548,21 @@ $ npm start 如果您查看 `package.json` 檔中的 npm 啟動 Script,您會發現,啟動應用程式的實際指令是 `node ./bin/www`,這在 Express 3 中是 `node app.js`。 -由於 Express 4 產生器產生的 `app.js` 檔現在是一個 Node.js 模組,因此無法再以應用程式形式單獨啟動它(除非您修改程式碼)。模組必須載入到 Node.js 檔,並透過 Node.js 檔啟動。在本例中,Node.js 檔是 `./bin/www`。 +由於 Express 4 產生器產生的 `app.js` 檔現在是一個 Node.js 模組,因此無法再以應用程式形式單獨啟動它(除非您修改程式碼)。模組必須載入到 Node.js 檔,並透過 Node.js 檔啟動。在本例中,Node.js 檔是 `./bin/www`。 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 應用程式或啟動應用程式時,`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. 若要除去 `www` 目錄,並採用「Express 3 形式」,請刪除 `app.js` 檔尾端的 `module.exports = app;` 字行,然後在該處貼上下列程式碼: ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` @@ -549,4 +575,6 @@ var debug = require('debug')('app4') 然後將 `package.json` 檔中的 `"start": "node ./bin/www"` 變更為 `"start": "node app.js"`。 -現在您已將 `./bin/www` 的功能移回至 `app.js`。不建議進行這項變更,但這項練習有助您瞭解 `./bin/www` 檔的運作方式,以及 `app.js` 檔不再自行啟動的原因。 +現在您已將 `./bin/www` 的功能移回至 `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/zh-tw/guide/migrating-5.md b/zh-tw/guide/migrating-5.md old mode 100755 new mode 100644 index c9db2d0deb..a4301d2cf7 --- a/zh-tw/guide/migrating-5.md +++ b/zh-tw/guide/migrating-5.md @@ -1,31 +1,45 @@ --- layout: page title: 移轉至 Express 5 +description: A comprehensive guide to migrating your Express.js applications from version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. menu: guide lang: zh-tw -description: A comprehensive guide to migrating your Express.js applications from - version 4 to 5, detailing breaking changes, deprecated methods, and new improvements. +redirect_from: " " --- # 移至 Express 5

    概觀

    -Express 5.0 尚在 Alpha 版階段,這裡讓您預覽版本中的變更以及如何將 Express 4 應用程式移轉至 Express 5。 +Express 5 與 Express 4 之間差異不大:API 的變更不會像從 3.0 至 4.0 那樣顯著。雖然基本 API 維持相同,仍有一些突破性變更;換句話說,如果您更新成使用 Express 5,現有 Express 4 程式可能無法運作。 Therefore, an application built with Express 4 might not work if you update it to use Express 5. -Express 5 與 Express 4 之間差異不大:API 的變更不會像從 3.0 至 4.0 那樣顯著。雖然基本 API 維持相同,仍有一些突破性變更;換句話說,如果您更新成使用 Express 5,現有 Express 4 程式可能無法運作。 +To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: -如果要安裝最新的 Alpha 版並預覽 Express 5,請在您應用程式根目錄中輸入下列指令: +```sh +npm install "express@5" +``` + +然後您可以執行自動化測試,查看失敗之處,並根據下方列出的更新項目來修正問題。解決測試失敗之後,請執行您的應用程式,查看發生哪些錯誤。只要應用程式使用任何不支援的方法或內容,您會馬上發現。 After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported. + +## Express 5 Codemods + +To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. + +Run the following command for run all the codemods available: -```bash -$ npm install "express@5" --save +```sh +npx @expressjs/codemod upgrade ``` -然後您可以執行自動化測試,查看失敗之處,並根據下方列出的更新項目來修正問題。解決測試失敗之後,請執行您的應用程式,查看發生哪些錯誤。只要應用程式使用任何不支援的方法或內容,您會馬上發現。 +If you want to run a specific codemod, you can run the following command: -

    Express 5 中的變更

    +```sh +npx @expressjs/codemod name-of-the-codemod +``` -這裡列出將會影響您(作為 Express 使用者)的變更(起自 Alpha 2 版)。如需所有規劃的特性清單,請參閱 [pull request](https://github.com/expressjs/express/pull/2237)。 +You can find the list of available codemods [here](https://github.com/expressjs/codemod?tab=readme-ov-file#available-codemods). + +

    Express 5 中的變更

    **已移除的方法和內容** @@ -33,101 +47,461 @@ $ npm install "express@5" --save
  • app.del()
  • app.param(fn)
  • 複數化的方法名稱
  • -
  • app.param(name, fn) 名稱引數中的前導冒號
  • +
  • Leading colon in name argument to app.param(name, fn)
  • req.param(name)
  • res.json(obj, status)
  • res.jsonp(obj, status)
  • +
  • res.redirect('back') and res.location('back')
  • +
  • res.redirect(url, status)
  • res.send(body, status)
  • res.send(status)
  • res.sendfile()
  • +
  • router.param(fn)
  • +
  • express.static.mime
  • +
  • express:router debug logs
  • -**已變更** +**改良** -**改良** +**已變更** -

    已移除的方法和內容

    +### 已移除的方法和內容 -如果您在應用程式中使用上述任何方法或內容,應用程式將會當機。因此,更新至第 5 版之後,您需要變更應用程式。 +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.

    app.del()

    -Express 5 不再支援 `app.del()` 函數。如果您使用此函數,會擲出錯誤。若要登錄 HTTP DELETE 路由,請改用 `app.delete()` 函數。 +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. + +最初是使用 `del` 而非 `delete`,因為 `delete` 是 JavaScript 中的保留關鍵字。不過,從 ECMAScript 6 起,`delete` 和其他保留關鍵字可以合法作為內容名稱。您可以在這裡閱讀導致淘汰 `app.del` 函數的相關討論。 However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. + +{% capture codemod-deprecated-signatures %} +You can replace the deprecated signatures with the following command: -最初是使用 `del` 而非 `delete`,因為 `delete` 是 JavaScript 中的保留關鍵字。不過,從 ECMAScript 6 起,`delete` 和其他保留關鍵字可以合法作為內容名稱。您可以在這裡閱讀導致淘汰 `app.del` 函數的相關討論。 +```plain-text +npx @expressjs/codemod v4-deprecated-signatures +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.del('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) + +// v5 +app.delete('/user/:id', (req, res) => { + res.send(`DELETE /user/${req.params.id}`) +}) +```

    app.param(fn)

    -`app.param(fn)` 簽章用來修改 `app.param(name, fn)` 函數的行為。從 4.11.0 版起就已淘汰,Express 5 已全然不再支援。 +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. + +

    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.acceptsLanguage()` 以 `req.acceptsLanguages()` 取代。 `req.acceptsCharset()` 以 `req.acceptsCharsets()` 取代。 `req.acceptsEncoding()` 以 `req.acceptsEncodings()` 取代。 -`req.acceptsLanguage()` 以 `req.acceptsLanguages()` 取代。 +{% capture codemod-pluralized-methods %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod pluralized-methods +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-pluralized-methods %} + +```js +// v4 +app.all('/', (req, res) => { + req.acceptsCharset('utf-8') + req.acceptsEncoding('br') + req.acceptsLanguage('en') + + // ... +}) + +// v5 +app.all('/', (req, res) => { + req.acceptsCharsets('utf-8') + req.acceptsEncodings('br') + req.acceptsLanguages('en') + + // ... +}) +```

    app.param(name, fn) 名稱中的前導冒號 (:)

    -`app.param(name, fn)` 函數名稱中的前導冒號字元 (:) 遺留自 Express 3,基於舊版相容性,Express 4 仍支援它,只是會發出淘汰警示。Express 5 會無聲自動忽略它,並使用少了冒號字首的名稱參數。 +`app.param(name, fn)` 函數名稱中的前導冒號字元 (:) 遺留自 Express 3,基於舊版相容性,Express 4 仍支援它,只是會發出淘汰警示。Express 5 會無聲自動忽略它,並使用少了冒號字首的名稱參數。 Express 5 will silently ignore it and use the name parameter without prefixing it with a colon. 如果您遵循 Express 4 [app.param](/{{ page.lang }}/4x/api.html#app.param) 說明文件,應該不會影響您的程式碼,因為該說明文件不會提及前導冒號。

    req.param(name)

    -這個用來擷取表單資料的方法因可能造成混淆且招致危險,而已經移除。現在您需要明確尋找 `req.params`、`req.body` 或 `req.query` 物件中所提交的參數名稱。 +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. + +{% capture codemod-req-param %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod req-param +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-req-param %} + +```js +// v4 +app.post('/user', (req, res) => { + const id = req.param('id') + const body = req.param('body') + const query = req.param('query') + + // ... +}) + +// v5 +app.post('/user', (req, res) => { + const id = req.params.id + const body = req.body + const query = req.query + + // ... +}) +```

    res.json(obj, status)

    -Express 5 不再支援 `res.json(obj, status)` 簽章。請改以設定狀態,然後與 `res.json()` 方法鏈接,如下所示:`res.status(status).json(obj)`。 +Express 5 不再支援 `res.json(obj, status)` 簽章。請改以設定狀態,然後與 `res.json()` 方法鏈接,如下所示:`res.status(status).json(obj)`。 Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.json({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).json({ name: 'Ruben' }) +}) +```

    res.jsonp(obj, status)

    -Express 5 不再支援 `res.jsonp(obj, status)` 簽章。請改以設定狀態,然後與 `res.jsonp()` 方法鏈接,如下所示:`res.status(status).jsonp(obj)`。 +Express 5 不再支援 `res.jsonp(obj, status)` 簽章。請改以設定狀態,然後與 `res.jsonp()` 方法鏈接,如下所示:`res.status(status).jsonp(obj)`。 Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.post('/user', (req, res) => { + res.jsonp({ name: 'Ruben' }, 201) +}) + +// v5 +app.post('/user', (req, res) => { + res.status(201).jsonp({ name: 'Ruben' }) +}) +``` + +

    res.redirect(url, status)

    + +Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('/users', 301) +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(301, '/users') +}) +``` + +

    res.redirect('back') and res.location('back')

    + +Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. + +{% capture codemod-magic-redirect %} +You can replace the deprecated signatures with the following command: + +```plain-text +npx @expressjs/codemod magic-redirect +``` + +{% endcapture %} + +{% include admonitions/note.html content=codemod-magic-redirect %} + +```js +// v4 +app.get('/user', (req, res) => { + res.redirect('back') +}) + +// v5 +app.get('/user', (req, res) => { + res.redirect(req.get('Referrer') || '/') +}) +```

    res.send(body, status)

    -Express 5 不再支援 `res.send(obj, status)` 簽章。請改以設定狀態,然後與 `res.send()` 方法鏈接,如下所示:`res.status(status).send(obj)`。 +Express 5 不再支援 `res.send(obj, status)` 簽章。請改以設定狀態,然後與 `res.send()` 方法鏈接,如下所示:`res.status(status).send(obj)`。 Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send({ name: 'Ruben' }, 200) +}) + +// v5 +app.get('/user', (req, res) => { + res.status(200).send({ name: 'Ruben' }) +}) +```

    res.send(status)

    -Express 5 不再支援 res.send(status) 簽章,其中 *`status`* 是數字。請改用 `res.sendStatus(statusCode)` 函數,此函數是設定 HTTP 回應標頭狀態碼,並傳送文字版的程式碼:「找不到」、「內部伺服器錯誤」等。 -如果您需要使用 `res.send()` 函數來傳送數字,請將數字括上引號來轉換成字串,這樣 Express 就不會解譯它以試圖使用不支援的舊簽章。 +Express 5 不再支援 res.send(status) 簽章,其中 _`status`_ 是數字。請改用 `res.sendStatus(statusCode)` 函數,此函數是設定 HTTP 回應標頭狀態碼,並傳送文字版的程式碼:「找不到」、「內部伺服器錯誤」等。 +如果您需要使用 `res.send()` 函數來傳送數字,請將數字括上引號來轉換成字串,這樣 Express 就不會解譯它以試圖使用不支援的舊簽章。 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. + +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.send(200) +}) + +// v5 +app.get('/user', (req, res) => { + res.sendStatus(200) +}) +```

    res.sendfile()

    `res.sendfile()` 函數已被 Express 5 中的駝峰式大小寫版本 `res.sendFile()` 取代。 +{% include admonitions/note.html content=codemod-deprecated-signatures %} + +```js +// v4 +app.get('/user', (req, res) => { + res.sendfile('/path/to/file') +}) + +// v5 +app.get('/user', (req, res) => { + res.sendFile('/path/to/file') +}) +``` + +

    router.param(fn)

    + +The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. + +

    express.static.mime

    + +In Express 5, `mime` is no longer an exported property of the `static` field. +Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values. + +```js +// v4 +express.static.mime.lookup('json') + +// v5 +const mime = require('mime-types') +mime.lookup('json') +``` + +

    express:router debug logs

    + +In Express 5, router handling logic is performed by a dependency. Therefore, the +debug logs for the router are no longer available under the `express:` namespace. +In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, +and `express:router:route`. All of these were included under the namespace `express:*`. +In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. +The logs from `router:layer` and `router:route` are included in the namespace `router:*`. +To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of +`express:*`, `router`, and `router:*`. + +```sh +# v4 +DEBUG=express:* node index.js + +# v5 +DEBUG=express:*,router,router:* node index.js +``` +

    已變更

    +

    Path route matching syntax

    + +Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: + +- The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` + +```js +// v4 +app.get('/*', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/*splat', async (req, res) => { + res.send('ok') +}) +``` + +{% capture note_wildcard %} +`*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. + +```js +// v5 +app.get('/{*splat}', async (req, res) => { + res.send('ok') +}) +``` + +{% endcapture %} +{% include admonitions/note.html content=note_wildcard %} + +- The optional character `?` is no longer supported, use braces instead. + +```js +// v4 +app.get('/:file.:ext?', async (req, res) => { + res.send('ok') +}) + +// v5 +app.get('/:file{.:ext}', async (req, res) => { + res.send('ok') +}) +``` + +- Regexp characters are not supported. For example: + +```js +app.get('/[discussion|page]/:slug', async (req, res) => { + res.status(200).send('ok') +}) +``` + +should be changed to: + +```js +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { + res.status(200).send('ok') +}) +``` + +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +

    Rejected promises handled from middleware and handlers

    + +Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. + +Details of how Express handles errors is covered in the [error handling documentation](/en/guide/error-handling.html). + +

    express.urlencoded

    + +The `express.urlencoded` method makes the `extended` option `false` by default. + +

    app.listen

    + +In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. +For example: + +```js +const server = app.listen(8080, '0.0.0.0', (error) => { + if (error) { + throw error // e.g. EADDRINUSE + } + console.log(`Listening on ${JSON.stringify(server.address())}`) +}) +``` +

    app.router

    `app.router` 物件已在 Express 4 中移除,在 Express 5 中又重新納入。 -在新版本中,這個物件只用來參照至基本 Express 路由器,不像在 Express 3 中,應用程式還得明確載入它。 +在新版本中,這個物件只用來參照至基本 Express 路由器,不像在 Express 3 中,應用程式還得明確載入它。 In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it. + +

    req.body

    + +The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default.

    req.host

    -在 Express 4 中,`req.host` 函數會不當去除埠號(如果有的話)。在 Express 5 中,會維護埠號。 +In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5, the port number is maintained.

    req.query

    -在 Express 4.7 以及從 Express 5 開始,當您想使用自己的函數作為查詢字串剖析邏輯時,查詢剖析器選項可以接受 `false` 以停用查詢字串剖析。 +The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from "extended" to "simple". -

    改良

    +

    res.clearCookie

    + +The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. + +

    res.status

    + +The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. + +

    res.vary

    + +The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console + +### 改良

    res.render()

    此方法現在會針對所有視圖引擎施行非同步行為,可避免採行同步實作及違反建議介面的視圖引擎所造成的錯誤。 + +

    Brotli encoding support

    + +Express 5 supports Brotli encoding for requests received from clients that support it. diff --git a/zh-tw/guide/overriding-express-api.md b/zh-tw/guide/overriding-express-api.md new file mode 100644 index 0000000000..2234c632eb --- /dev/null +++ b/zh-tw/guide/overriding-express-api.md @@ -0,0 +1,73 @@ +--- +layout: page +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. +menu: guide +lang: zh-tw +--- + +# Overriding the Express 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: + +1. The global prototypes at `express.request` and `express.response`. +2. App-specific prototypes at `app.request` and `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. + +## 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.html#res.sendStatus). + +```js +app.response.sendStatus = function (statusCode, type, message) { + // code is intentionally kept simple for demonstration purpose + return this.contentType(type) + .status(statusCode) + .send(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. + +The overridden method may now be used this way: + +```js +res.sendStatus(404, 'application/json', '{"error":"resource not found"}') +``` + +## Properties + +Properties in the Express API are either: + +1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) +2. Defined as getters (ex: `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. + +Properties under category 2 can be overwritten using the Express API extensions 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. + +```js +Object.defineProperty(app.request, 'ip', { + configurable: true, + enumerable: true, + get () { return this.get('Client-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. + +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 +// for the given app reference +Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) +Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) +``` diff --git a/zh-tw/guide/routing.md b/zh-tw/guide/routing.md old mode 100755 new mode 100644 index 7b7d4fd972..30035312cd --- a/zh-tw/guide/routing.md +++ b/zh-tw/guide/routing.md @@ -1,17 +1,29 @@ --- layout: page title: Express 路由 +description: Learn how to define and use routes in Express.js applications, including route methods, route paths, parameters, and using Router for modular routing. menu: guide lang: zh-tw -description: Learn how to define and use routes in Express.js applications, including - route methods, route paths, parameters, and using Router for modular routing. +redirect_from: " " --- # 路由 -*路由*是指應用程式端點 (URI) 的定義,以及應用程式如何回應用戶端要求。如需路由簡介,請參閱[基本路由](/{{ page.lang }}/starter/basic-routing.html)。 +_Routing_ refers to how an application's endpoints (URIs) respond to client requests. +For an introduction to routing, see [Basic routing](/{{ page.lang }}/starter/basic-routing.html). -下列程式碼範例說明相當基本的路由。 +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](/{{ page.lang }}/5x/api.html#app.METHOD). You can also use [app.all()](/{{ page.lang }}/5x/api.html#app.all) to handle all HTTP methods and [app.use()](/{{ page.lang }}/5x/api.html#app.use) to +specify middleware as the callback function (See [Using middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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. + +以下是以字串為基礎的部分路由路徑範例。 ```js const express = require('express') @@ -41,17 +53,10 @@ app.post('/', (req, res) => { }) ``` -Express 支援下列的路由方法,這些方法對應至 HTTP 方法:`get`、 -`post`、`put`、`head`、`delete`、`options`、 -`trace`、`copy`、`lock`、`mkcol`、`move`、`purge`、`propfind`、`proppatch`、`unlock`、`report`、`mkactivity`、`checkout`、`merge`、`m-search`、`notify`、`subscribe`、`unsubscribe`、`patch`、`search`,以及 `connect`。 +Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. +For a full list, see [app.METHOD](/{{ page.lang }}/5x/api.html#app.METHOD). -
    -如果要遞送的方法會轉換成無效的 JavaScript 變數名稱,請使用括弧表示法。例如,`app['m-search']('/', function ...` -
    - -`app.all()` 是一個特殊的路由方法,它不是衍生自任何 HTTP 方法。此方法用來在所有要求方法的路徑中載入中介軟體函數。 - -在下列範例中,不論您使用的是 GET、POST、PUT、DELETE 或 [http 模組](https://nodejs.org/api/http.html#http_http_methods)中支援的其他任何 HTTP 要求方法,都會針對傳給 "/secret" 的要求執行處理程式。 +`app.all()` 是一個特殊的路由方法,它不是衍生自任何 HTTP 方法。此方法用來在所有要求方法的路徑中載入中介軟體函數。 在下列範例中,不論您使用的是 GET、POST、PUT、DELETE 或 [http 模組](https://nodejs.org/api/http.html#http_http_methods)中支援的其他任何 HTTP 要求方法,都會針對傳給 "/secret" 的要求執行處理程式。 ```js app.all('/secret', (req, res, next) => { @@ -62,19 +67,36 @@ app.all('/secret', (req, res, next) => {

    路由路徑

    -當路由路徑配上要求方法時,即定義了發出要求時的目標端點。路由路徑可以是字串、字串型樣或正規表示式。 +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 使用 [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) 來找出相符的路由路徑;請參閱 path-to-regexp 說明文件,取得可用來定義路由路徑的所有可行方法。[Express Route Tester](http://forbeslindesay.github.io/express-route-tester/) 是一個用來測試 Express 基本路由的方便工具,只不過它不支援型樣相符。 -
    +{% capture caution-character %} In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} -
    -查詢字串不是路由路徑的一部分。 -
    +{% include admonitions/caution.html content=caution-character %} -以下是以字串為基礎的部分路由路徑範例。 +{% capture note-dollar-character %}In express 4, regular expression characters such as `$` need to be escaped with a `\`. +{% endcapture %} + +{% include admonitions/caution.html content=note-dollar-character %} + +{% capture note-path-to-regexp %} + +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. + +{% endcapture %} + +{% include admonitions/note.html content=note-path-to-regexp %} + +{% capture query-string-note %} + +Query strings are not part of the route path. -此路由路徑將符合傳送給根路由 `/` 的要求。 +{% endcapture %} + +{% include admonitions/warning.html content=query-string-note %} + +### Route paths based on strings + +This route path will match requests to the root route, `/`. ```js app.get('/', (req, res) => { @@ -82,7 +104,7 @@ app.get('/', (req, res) => { }) ``` -此路由路徑將符合傳送給 `/about` 的要求。 +This route path will match requests to `/about`. ```js app.get('/about', (req, res) => { @@ -98,7 +120,11 @@ app.get('/random.text', (req, res) => { }) ``` -以下是以字串型樣為基礎的部分路由路徑範例。 +### Route paths based on string patterns + +{% capture caution-string-patterns %} The string patterns in Express 5 no longer work. Please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax) for more information.{% endcapture %} + +{% include admonitions/caution.html content=caution-string-patterns %} 此路由路徑將符合 `acd` 和 `abcd`。 @@ -132,13 +158,9 @@ app.get('/ab(cd)?e', (req, res) => { }) ``` -
    - ?、+、* 和 () 字元是其正規表示式對應項目的一部分。以字串為基礎的路徑會照字面來解譯連字符號 (-) 和句點 (.)。 -
    - -以正規表示式為基礎的路由路徑範例: +### 以正規表示式為基礎的路由路徑範例: -只要路由名稱中有 "a",都與這個路由路徑相符。 +This route path will match anything with an "a" in it. ```js app.get(/a/, (req, res) => { @@ -154,15 +176,78 @@ app.get(/.*fly$/, (req, res) => { }) ``` -

    路由處理程式

    +

    當路由路徑配上要求方法時,即定義了發出要求時的目標端點。路由路徑可以是字串、字串型樣或正規表示式。

    + +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. -您可以提供其行為類似[中介軟體](/{{ page.lang }}/guide/using-middleware.html)的多個回呼函數,以處理要求。唯一的例外情況是這些回呼可能會呼叫 -`next('route')`,來略過其餘的路由回呼。如果沒有理由繼續處理現行路由,您可以使用這項機制,在路由中強制施行前置條件,然後將控制權傳遞給後續的路由。 +``` +Route path: /users/:userId/books/:bookId +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) => { + res.send(req.params) +}) +``` -單一回呼函數可以處理路由。例如: +
    +The name of route parameters must be made up of "word characters" ([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 +Request URL: http://localhost:3000/flights/LAX-SFO +req.params: { "from": "LAX", "to": "SFO" } +``` + +``` +Route path: /plantae/:genus.:species +Request URL: http://localhost:3000/plantae/Prunus.persica +req.params: { "genus": "Prunus", "species": "persica" } +``` + +{% capture warning-regexp %} +In express 5, Regexp characters are not supported in route paths, for more information please refer to the [migration guide](/{{ page.lang }}/guide/migrating-5.html#path-syntax).{% endcapture %} + +{% include admonitions/caution.html content=warning-regexp %} + +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+) +Request URL: http://localhost:3000/user/42 +req.params: {"userId": "42"} +``` + +{% capture escape-advisory %} + +Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. + +{% endcapture %} + +{% include admonitions/warning.html content=escape-advisory %} + +{% capture warning-version %} + +In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. + +{% endcapture %} + +{% include admonitions/warning.html content=warning-version %} + +

    Route handlers

    + +You can provide multiple callback functions that behave like [middleware](/{{ page.lang }}/guide/using-middleware.html) 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. + +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) => { @@ -170,8 +255,7 @@ app.get('/example/a', (req, res) => { }) ``` -多個回呼函數可以處理路由(請確定您有指定 `next` 物件)。例如: - +More than one callback function can handle a route (make sure you specify the `next` object). For example: ```js app.get('/example/b', (req, res, next) => { @@ -181,8 +265,8 @@ app.get('/example/b', (req, res, next) => { res.send('Hello from B!') }) ``` -回呼函數陣列可以處理路由。例如: +An array of callback functions can handle a route. For example: ```js const cb0 = function (req, res, next) { @@ -202,8 +286,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) { @@ -226,24 +309,25 @@ app.get('/example/d', [cb0, cb1], (req, res, next) => {

    回應方法

    -在下表中,回應物件 (`res`) 中的方法可以傳送回應給用戶端,並終止要求/回應循環。如果路由處理程式都沒有呼叫這些方法,用戶端要求將會停擺。 +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.download()](/{{ page.lang }}/4x/api.html#res.download) | 提示您提供要下載的檔案。 -| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | 結束回應程序。 -| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | 傳送 JSON 回應。 -| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | 傳送 JSON 回應,並支援 JSONP。 -| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 將要求重新導向。 -| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | 呈現視圖範本。 -| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 傳送各種類型的回應。 -| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 以八位元組串流形式傳送檔案。 -| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | 設定回應狀態碼,並以回應內文形式傳送其字串表示法。 +| 方法 | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| [res.download()](/{{ page.lang }}/4x/api.html#res.download) | 提示您提供要下載的檔案。 | +| [res.end()](/{{ page.lang }}/4x/api.html#res.end) | End the response process. | +| [res.json()](/{{ page.lang }}/4x/api.html#res.json) | 傳送 JSON 回應。 | +| [res.jsonp()](/{{ page.lang }}/4x/api.html#res.jsonp) | 傳送 JSON 回應,並支援 JSONP。 | +| [res.redirect()](/{{ page.lang }}/4x/api.html#res.redirect) | 將要求重新導向。 | +| [res.render()](/{{ page.lang }}/4x/api.html#res.render) | Render a view template. | +| [res.send()](/{{ page.lang }}/4x/api.html#res.send) | 傳送各種類型的回應。 | +| [res.sendFile()](/{{ page.lang }}/4x/api.html#res.sendFile) | 以八位元組串流形式傳送檔案。 | +| [res.sendStatus()](/{{ page.lang }}/4x/api.html#res.sendStatus) | Set the response status code and send its string representation as the response body. |

    app.route()

    您可以使用 `app.route()`,來為路由路徑建立可鏈接的路由處理程式。 由於是在單一位置指定路徑,建立模組路由很有用,因為它可減少冗餘和打錯字的情況。如需路由的相關資訊,請參閱 [Router() 說明文件](/{{ page.lang }}/4x/api.html#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](/{{ page.lang }}/5x/api.html#router). 下列範例顯示利用 `app.route()` 所定義的路由處理程式鏈。 @@ -262,11 +346,9 @@ app.route('/book')

    express.Router

    -`express.Router` 類別用來建立可裝載的模組路由處理程式。`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". -下列範例是將路由器建立成模組、 -在其中載入中介軟體函數、定義一些路由,並且將路由器模組裝載在主要應用程式中的路徑。 +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. 在應用程式目錄中建立一個名為 `birds.js` 的路由器檔案,內含下列內容: @@ -275,10 +357,12 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use((req, res, next) => { +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') @@ -296,9 +380,15 @@ module.exports = router ```js const birds = require('./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](/{{ page.lang }}/5x/api.html#app.use). + +```js +const router = express.Router({ mergeParams: true }) +``` diff --git a/zh-tw/guide/using-middleware.md b/zh-tw/guide/using-middleware.md old mode 100755 new mode 100644 index 734bb0ecdd..f046216d69 --- a/zh-tw/guide/using-middleware.md +++ b/zh-tw/guide/using-middleware.md @@ -1,44 +1,46 @@ --- layout: page title: 使用 Express 中介軟體 +description: Learn how to use middleware in Express.js applications, including application-level and router-level middleware, error handling, and integrating third-party middleware. menu: guide lang: zh-tw -description: Learn how to use middleware in Express.js applications, including application-level - and router-level middleware, error handling, and integrating third-party middleware. +redirect_from: " " --- # 使用中介軟體 Express 是一個本身功能極簡的路由與中介軟體 Web 架構:本質上,Express 應用程式是一系列的中介軟體函數呼叫。 -*中介軟體*函數是一些有權存取[要求物件](/{{ page.lang }}/4x/api.html#req) (`req`)、[回應物件](/{{ page.lang }}/4x/api.html#res) (`res`) 和應用程式要求/回應循環中之下一個中介軟體函數的函數。下一個中介軟體函數通常以名為 `next` 的變數表示。 +_Middleware_ functions are functions that have access to the [request object](/{{ page.lang }}/4x/api.html#req) (`req`), the [response object](/{{ page.lang }}/4x/api.html#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: -* 執行任何程式碼。 -* 對要求和回應物件進行變更。 -* 結束要求/回應循環。 -* 呼叫堆疊中的下一個中介軟體函數。 +- 執行任何程式碼。 +- Make changes to the request and the response objects. +- End the request-response cycle. +- Call the next middleware function in the stack. -如果現行中介軟體函數不會結束要求/回應循環,它必須呼叫 `next()`,以便將控制權傳遞給下一個中介軟體函數。否則,要求將會停擺。 +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. Express 應用程式可以使用下列類型的中介軟體: - - [應用程式層次的中介軟體](#middleware.application) - - [路由器層次的中介軟體](#middleware.router) - - [錯誤處理中介軟體](#middleware.error-handling) - - [內建中介軟體](#middleware.built-in) - - [協力廠商中介軟體](#middleware.third-party) +- [應用程式層次的中介軟體](#middleware.application) +- [路由器層次的中介軟體](#middleware.router) +- [錯誤處理中介軟體](#middleware.error-handling) +- [內建中介軟體](#middleware.built-in) +- [協力廠商中介軟體](#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.

    應用程式層次的中介軟體

    使用 `app.use()` 和 `app.METHOD()` 函數,將應用程式層次的中介軟體連結至 [app object](/{{ page.lang }}/4x/api.html#app) 實例,其中 `METHOD` 是中介軟體函數要處理的 HTTP 要求方法(例如 GET、PUT 或 POST),並採小寫。 -本例顯示沒有裝載路徑的中介軟體函數。每當應用程式收到要求時,就會執行此函數。 +This example shows a middleware function with no mount path. The function is executed every time the app receives a request. ```js +const express = require('express') const app = express() app.use((req, res, next) => { @@ -47,7 +49,8 @@ app.use((req, res, next) => { }) ``` -本例顯示裝載在 `/user/:id` 路徑的中介軟體函數。會對 `/user/:id` 路徑上任何類型的 HTTP 要求,執行此函數。 +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. ```js app.use('/user/:id', (req, res, next) => { @@ -56,7 +59,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -本例顯示路由和其處理程式函數(中介軟體系統)。此函數會處理指向 `/user/:id` 路徑的 GET 要求。 +This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. ```js app.get('/user/:id', (req, res, next) => { @@ -64,7 +67,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('/user/:id', (req, res, next) => { @@ -76,7 +80,7 @@ app.use('/user/:id', (req, res, next) => { }) ``` -路由處理程式可讓您為一個路徑定義多個路由。下列範例為指向 `/user/:id` 路徑的 GET 要求,定義兩個路由。第二個路由不會造成任何問題,卻絕不會呼叫,因為第一個路由會結束要求/回應循環。 +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 要求。 @@ -90,12 +94,19 @@ app.get('/user/:id', (req, res, next) => { // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { - res.end(req.params.id) + res.send(req.params.id) }) ``` -如果要跳過路由器中介軟體堆疊中其餘的中介軟體函數,請呼叫 `next('route')`,將控制權傳遞給下一個路由。**附註**: -`next('route')` 只適用於使用 `app.METHOD()` 或 `router.METHOD()` 函數載入的中介軟體函數。 +To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route. + +{% capture next-function %} + +`next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. + +{% endcapture %} + +{% include admonitions/note.html content=next-function %} 本例顯示中介軟體子堆疊,它處理了指向 `/user/:id` 路徑的 GET 要求。 @@ -104,15 +115,36 @@ app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack - else next() // + else next() }, (req, res, next) => { - // render a regular page - res.render('regular') + // send a regular response + res.send('regular') }) -// handler for the /user/:id path, which renders a special page +// handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { - res.render('special') + res.send('special') +}) +``` + +Middleware can also be declared in an array for reusability. + +本例顯示裝載在 `/user/:id` 路徑的中介軟體函數。會對 `/user/:id` 路徑上任何類型的 HTTP 要求,執行此函數。 + +```js +function logOriginalUrl (req, res, next) { + console.log('Request URL:', req.originalUrl) + next() +} + +function logMethod (req, res, next) { + console.log('Request Type:', req.method) + next() +} + +const logStuff = [logOriginalUrl, logMethod] +app.get('/user/:id', logStuff, (req, res, next) => { + res.send('User Info') }) ``` @@ -123,11 +155,13 @@ app.get('/user/:id', (req, res, next) => { ```js const router = express.Router() ``` + 請利用 `router.use()` 和 `router.METHOD()` 函數來載入路由器層次的中介軟體。 下列的程式碼範例是使用路由器層次的中介軟體,抄寫上述針對應用程式層次的中介軟體顯示的中介軟體系統: ```js +const express = require('express') const app = express() const router = express.Router() @@ -151,7 +185,7 @@ 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() // + else next() }, (req, res, next) => { // render a regular page res.render('regular') @@ -166,77 +200,64 @@ router.get('/user/:id', (req, res, next) => { // mount the router on the app app.use('/', router) ``` -

    錯誤處理中介軟體

    -
    -錯誤處理中介軟體一律會使用*四個*引數。您必須提供這四個引數,將它識別為錯誤處理中介軟體函數。即使您不需要使用 `next` 物件也必須指定,以維護簽章。否則,會將 `next` 物件解譯為一般中介軟體,而無法處理錯誤。 -
    +To skip the rest of the router's middleware functions, call `next('router')` +to pass control back out of the router instance. -錯誤處理中介軟體函數的定義方式,與其他中介軟體函數相同,差別在於引數是四個而非三個,具體來說,就是使用 `(err, req, res, next)`) 簽章: +本例顯示中介軟體子堆疊,它處理了指向 `/user/:id` 路徑的 GET 要求。 ```js -app.use((err, req, res, next) => { - console.error(err.stack) - res.status(500).send('Something broke!') -}) -``` - -如需錯誤處理中介軟體的詳細資料,請參閱:[錯誤處理](/{{ page.lang }}/guide/error-handling.html)。 - -

    內建中介軟體

    - -從 4.x 版起,Express 不再相依於 [Connect](https://github.com/senchalabs/connect)。除了 `express.static`,Express 先前隨附的所有中介軟體函數現在位於個別的模組中。請檢視[中介軟體函數清單](https://github.com/senchalabs/connect#middleware)。 +const express = require('express') +const app = express() +const router = express.Router() -

    express.static(root, [options])

    +// 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() +}) -Express 唯一的內建中介軟體函數是 `express.static`。此函數以 [serve-static](https://github.com/expressjs/serve-static) 為基礎,負責在 Express 應用程式中提供靜態資產。 +router.get('/user/:id', (req, res) => { + res.send('hello, user!') +}) -`root` 引數指定提供靜態資產的根目錄。 +// use the router and 401 anything falling through +app.use('/admin', router, (req, res) => { + res.sendStatus(401) +}) +``` -`options` 選用物件可具有下列內容: +

    Error-handling middleware

    -| 內容 | 說明 | 類型 | 預設值 | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | 用來提供點檔案的選項。可能的值是 "allow"、"deny" 和 "ignore" | 字串 | "ignore" | -| `etag` | 啟用或停用 etag 的產生 | 布林 | `true` | -| `extensions` | 設定副檔名遞補。 | 陣列 | `[]` | -| `index` | 傳送目錄索引檔。設定 `false`,會停用目錄檢索。 | 混合 | "index.html" | - `lastModified` | 將 `Last-Modified` 標頭設為作業系統上檔案的前次修改日期。可能的值是 `true` 或 `false`。 | 布林 | `true` | -| `maxAge` | 設定 Cache-Control 標頭的 max-age 內容,以毫秒為單位或 [ms 格式](https://www.npmjs.org/package/ms)的字串 | 數字 | 0 | -| `redirect` | 當路徑名稱是目錄時,重新導向至尾端 "/"。 | 布林 | `true` | -| `setHeaders` | 用來設定 HTTP 標頭以提供檔案的函數。 | 函數 | | +
    +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. +
    -下列範例顯示如何使用 `express.static` 中介軟體函數,且其中詳細闡述了 options 物件: +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)`: ```js -const options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) +app.use((err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +}) ``` -每一個應用程式可有多個靜態目錄: +For details about error-handling middleware, see: [Error handling](/{{ page.lang }}/guide/error-handling.html). -```js -app.use(express.static('public')) -app.use(express.static('uploads')) -app.use(express.static('files')) -``` +

    Built-in middleware

    + +從 4.x 版起,Express 不再相依於 [Connect](https://github.com/senchalabs/connect)。除了 `express.static`,Express 先前隨附的所有中介軟體函數現在位於個別的模組中。請檢視[中介軟體函數清單](https://github.com/senchalabs/connect#middleware)。 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 has the following built-in middleware functions: -如需 `serve-static` 函數和其選項的詳細資料,請參閱 [serve-static](https://github.com/expressjs/serve-static) 說明文件。 +- [express.static](/en/4x/api.html#express.static) serves static assets such as HTML files, images, and so on. +- [express.json](/en/4x/api.html#express.json) parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** +- [express.urlencoded](/en/4x/api.html#express.urlencoded) parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+** -

    協力廠商中介軟體

    +

    Third-party middleware

    -使用協力廠商中介軟體,在 Express 應用程式中新增功能。 +Use third-party middleware to add functionality to Express apps. 針對必要的功能安裝 Node.js 模組,然後在應用程式層次或路由器層次將它載入到您的應用程式中。 @@ -255,4 +276,4 @@ const cookieParser = require('cookie-parser') app.use(cookieParser()) ``` -如需 Express 中常用的部分協力廠商中介軟體函數清單,請參閱:[協力廠商中介軟體](../resources/middleware.html)。 +For a partial list of third-party middleware functions that are commonly used with Express, see: [Third-party middleware](../resources/middleware.html). diff --git a/zh-tw/guide/using-template-engines.md b/zh-tw/guide/using-template-engines.md old mode 100755 new mode 100644 index b871041b55..3b6d5c724b --- a/zh-tw/guide/using-template-engines.md +++ b/zh-tw/guide/using-template-engines.md @@ -1,29 +1,24 @@ --- layout: page title: 在 Express 中使用模板引擎 +description: Discover how to integrate and use template engines like Pug, Handlebars, and EJS with Express.js to render dynamic HTML pages efficiently. menu: guide lang: zh-tw -description: Discover how to integrate and use template engines like Pug, Handlebars, - and EJS with Express.js to render dynamic HTML pages efficiently. +redirect_from: " " --- # 在 Express 中使用模板引擎 -模板引擎讓您能在應用程式中使用靜態模板檔案。在執行時,模板引擎會將靜態模板檔案中的變數取代為真實的值,並將模板轉換為 HTML 檔案發送至客戶端,這種方法使得設計一個 HTML 頁面變得更加容易。 +A _template engine_ enables you to use static template files in your application. 模板引擎讓您能在應用程式中使用靜態模板檔案。在執行時,模板引擎會將靜態模板檔案中的變數取代為真實的值,並將模板轉換為 HTML 檔案發送至客戶端,這種方法使得設計一個 HTML 頁面變得更加容易。 +This approach makes it easier to design an HTML page. 部分主流的模板引擎 [Pug](https://pugjs.org/api/getting-started.html)、[Mustache](https://www.npmjs.com/package/mustache) 和 [EJS](https://www.npmjs.com/package/ejs) 均可被使用於 Express 中。[Express 應用程式產生器](http://expressjs.com/en/starter/generator.html)預設採用 [Jade](https://www.npmjs.com/package/jade),但也支援包含上述的多種模板引擎。 -您可以參閱 [Express Wiki](https://github.com/expressjs/express/wiki#template-engines) 以得知在 Express 中可使用的模板引擎,亦可參閱這篇文章 -:[Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More](https://web.archive.org/web/20240000000000/https://strongloop.com/strongblog/compare-javascript-templates-jade-mustache-dust/)。 - -
    -**注意**:Jade 已改名為 [Pug](https://www.npmjs.com/package/pug)。您仍可繼續於應用程式中使用 Jade,它仍能良好運作。然而,若您想取得其最新的版本,則必須在應用程式中將其取代為 Pug。 -
    - 若要渲染模板檔案,您必須在應用程式產生器產生的 `app.js` 設定以下[應用程式屬性](http://expressjs.com/en/4x/api.html#app.set): -- `views`:範本檔所在的目錄。例如:`app.set('views', './views')`,其預設為應用程式根目錄的 `views` 資料夾。 -- `view engine`:要使用的範本引擎,例如若要使用 Pug 模板引擎:`app.set('view engine', 'pug')` +- `views`, the directory where the template files are located. `views`:範本檔所在的目錄。例如:`app.set('views', './views')`,其預設為應用程式根目錄的 `views` 資料夾。 + This defaults to the `views` directory in the application root directory. +- `view engine`, the template engine to use. `view engine`:要使用的範本引擎,例如若要使用 Pug 模板引擎:`app.set('view engine', 'pug')` 並安裝對應的模板引擎 npm 套件,例如安裝 Pug: @@ -34,7 +29,7 @@ $ npm install pug --save
    與 Express 相容的範本引擎(例如 Pug)會匯出一個名稱是 `__express(filePath, options, callback)` 的函數,以供 `res.render()` 函數呼叫,來呈現範本程式碼。 -有些範本引擎不遵循這項慣例。[Consolidate.js](https://www.npmjs.org/package/consolidate) 程式庫遵循這項慣例,它會對映所有常見的 Node.js 範本引擎,因此能在 Express 內平順無礙地運作。 +Some template engines do not follow this convention. 有些範本引擎不遵循這項慣例。[Consolidate.js](https://www.npmjs.org/package/consolidate) 程式庫遵循這項慣例,它會對映所有常見的 Node.js 範本引擎,因此能在 Express 內平順無礙地運作。
    @@ -54,7 +49,8 @@ html h1= message ``` -建立路由以呈現 `index.pug` 檔。如果未設定 `view engine` 內容,您必須指定 `view` 檔的副檔名,否則可以省略此步驟。 +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. ```js app.get('/', (req, res) => { @@ -64,6 +60,4 @@ app.get('/', (req, res) => { 當您向首頁發出請求時,`index.pug` 檔會以 HTML 被渲染出來。 -注意:模板引擎緩存不會快取住模板輸出的內容,只會快取模板本身。即使開啟快取,視圖仍會隨著每個請求重新被渲染。 - -如需進一步瞭解範本引擎在 Express 中的運作方式,請參閱:[開發 Express 範本引擎](/{{ page.lang }}/advanced/developing-template-engines.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/zh-tw/guide/writing-middleware.md b/zh-tw/guide/writing-middleware.md old mode 100755 new mode 100644 index 72a8751639..adb852855c --- a/zh-tw/guide/writing-middleware.md +++ b/zh-tw/guide/writing-middleware.md @@ -1,39 +1,39 @@ --- layout: page title: 撰寫中介軟體以用於 Express 應用程式中 +description: Learn how to write custom middleware functions for Express.js applications, including examples and best practices for enhancing request and response handling. menu: guide lang: zh-tw -description: Learn how to write custom middleware functions for Express.js applications, - including examples and best practices for enhancing request and response handling. +redirect_from: " " --- # 撰寫中介軟體以用於 Express 應用程式中

    概觀

    -*中介軟體*函數是一些有權存取[要求物件](/{{ page.lang }}/4x/api.html#req) (`req`)、[回應物件](/{{ page.lang }}/4x/api.html#res) (`res`) 和應用程式要求/回應循環中之下一個中介軟體函數的函數。下一個中介軟體函數通常以名為 `next` 的變數表示。 +_Middleware_ functions are functions that have access to the [request object](/{{ page.lang }}/4x/api.html#req) (`req`), the [response object](/{{ page.lang }}/4x/api.html#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: -* 執行任何程式碼。 -* 對要求和回應物件進行變更。 -* 結束要求/回應循環。 -* 呼叫堆疊中的下一個中介軟體。 +- 執行任何程式碼。 +- Make changes to the request and the response objects. +- End the request-response cycle. +- Call the next middleware in the stack. -如果現行中介軟體函數不會結束要求/回應循環,它必須呼叫 `next()`,以便將控制權傳遞給下一個中介軟體函數。否則,要求將會停擺。 +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. -下列範例顯示中介軟體函數呼叫中的元素: +The following figure shows the elements of a middleware function call: - -
    要套用中介軟體函數的路徑(路由)。
    +
    Path (route) for which the middleware function applies.
    -
    中介軟體函數。
    +
    The middleware function.
    中介軟體函數的回呼引數,依慣例,稱為 "next"。
    @@ -43,7 +43,14 @@ description: Learn how to write custom middleware functions for Express.js appli
    +
    Elements of a middleware function call -
    要套用中介軟體函數的 HTTP 方法。
    +
    HTTP method for which the middleware function applies.
    +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. + +

    範例

    + 下列範例顯示簡單的 "Hello World" Express 應用程式,您將為這個應用程式定義兩個中介軟體函數: +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 const express = require('express') @@ -56,9 +63,8 @@ app.get('/', (req, res) => { app.listen(3000) ``` -

    開發

    - -以下的簡單範例顯示一個稱為 "myLogger" 的中介軟體函數。當透過這個函數將要求傳遞給應用程式時,此函數只會列印 "LOGGED"。中介軟體函數會指派給名為 `myLogger` 的變數。 +

    Middleware function 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`. ```js const myLogger = function (req, res, next) { @@ -68,10 +74,13 @@ const myLogger = function (req, res, next) { ```
    -請注意上述對 `next()` 的呼叫。呼叫這個函數時,會呼叫應用程式中的下一個中介軟體函數。`next()` 函數並非 Node.js 或 Express API 的一部分,而是傳遞給中介軟體函數的第三個引數。`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` 中介軟體函數。 +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 const express = require('express') @@ -93,13 +102,16 @@ app.listen(3000) 每當應用程式收到要求時,它會將 "LOGGED" 訊息列印至終端機。 -中介軟體的載入順序很重要:先載入的中介軟體函數也會先執行。 +The order of middleware loading is important: middleware functions that are loaded first are also executed first. 如果 `myLogger` 是在根路徑路由之後才載入,要求永不會抵達該函數,應用程式也不會列印 "LOGGED",因為根路徑的路由處理程式會終止要求/回應循環。 -中介軟體函數 `myLogger` 只會列印訊息,然後呼叫 `next()` 函數,將要求傳遞給堆疊中的下一個中介軟體函數。 +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. -下一個範例是在要求物件中新增一個稱為 `requestTime` 的內容。我們將這個中介軟體函數命名為 "requestTime"。 +

    Middleware function requestTime

    + +Next, we'll create a middleware function called "requestTime" and add a property called `requestTime` +to the request object. ```js const requestTime = function (req, res, next) { @@ -108,7 +120,7 @@ const requestTime = function (req, res, next) { } ``` -現在,應用程式會使用 `requestTime` 中介軟體函數。此外,根路徑路由的回呼函數會使用中介軟體函數新增至 `req`(要求物件)的內容。 +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 const express = require('express') @@ -129,8 +141,80 @@ app.get('/', (req, res) => { app.listen(3000) ``` -當您對應用程式根位置發出要求時,應用程式現在會在瀏覽器中顯示該要求的時間戳記。 -由於您有權存取要求物件、回應物件、堆疊中的下一個中介軟體函數,以及整個 Node.js API,因此,中介軟體函數的可能性無止盡。 +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

    + +Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. + +Here's an example function that validates cookies with an external async service. + +```js +async function cookieValidator (cookies) { + try { + await externallyValidateCookie(cookies.testCookie) + } catch { + throw new Error('Invalid cookies') + } +} +``` + +Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser.html) 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 +const express = require('express') +const cookieParser = require('cookie-parser') +const cookieValidator = require('./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. +
    + +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. + +For more information about Express middleware, see: [Using Express middleware](/{{ page.lang }}/guide/using-middleware.html). + +

    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 +module.exports = 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') + +app.use(mw({ option1: '1', option2: '2' })) +``` -如需 Express 中介軟體的相關資訊,請參閱:[使用 Express 中介軟體](/{{ page.lang }}/guide/using-middleware.html)。 +Refer to [cookie-session](https://github.com/expressjs/cookie-session) and [compression](https://github.com/expressjs/compression) for examples of configurable middleware. diff --git a/zh-tw/resources/community.md b/zh-tw/resources/community.md old mode 100755 new mode 100644 index 897ae461aa..15dcb4f99d --- a/zh-tw/resources/community.md +++ b/zh-tw/resources/community.md @@ -1,23 +1,89 @@ --- layout: page title: Express 社群 +description: Connect with the Express.js community, learn about the technical committee, find resources, explore community-contributed modules, and get involved in discussions. menu: resources lang: zh-tw -description: Connect with the Express.js community, learn about the technical committee, - find resources, explore community-contributed modules, and get involved in discussions. +redirect_from: " " --- # 社群 -## 範例 +## Technical committee -檢視儲存庫中數十個 Express 應用程式[範例](https://github.com/expressjs/express/tree/master/examples),從 API 設計與鑑別,到範本引擎的整合,樣樣涵蓋在內。 +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. + +The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). + +Members of the Express technical committee are: + +**Active:** + +- [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey +- [@crandmck](https://github.com/crandmck) - Rand McKinney +- [@LinusU](https://github.com/LinusU) - Linus Unnebäck +- [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón +- [@sheplu](https://github.com/sheplu) - Jean Burellier +- [@wesleytodd](https://github.com/wesleytodd) - Wes Todd +- [@jonchurch](https://github.com/jonchurch) - Jon Church +- [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida + +**Inactive:** + +- [@dougwilson](https://github.com/dougwilson) - Douglas Wilson +- [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa +- [@jonathanong](https://github.com/jonathanong) - jongleberry +- [@niftylettuce](https://github.com/niftylettuce) - niftylettuce +- [@troygoode](https://github.com/troygoode) - Troy Goode + +## Express is made of many modules + +我們的熱情活躍的社群已建立各式各樣的延伸項目、[中介軟體模組](/{{ page.lang }}/resources/middleware.html),以及更高層次的架構。相關資訊請參閱 [Wiki](https://github.com/expressjs/express/wiki)。 + +Additionally, the Express community maintains modules in these two GitHub orgs: + +- [jshttp](https://jshttp.github.io/) modules providing useful utility functions; see [Utility modules](/{{ page.lang }}/resources/utils.html). +- [pillarjs](https://pillarjs.github.io/): low-level modules that Express uses internally. + +To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## 議題 如果您恰巧碰到您認為是錯誤之處,或者只是想提出一項特性要求,請在[議題列表](https://github.com/expressjs/express/issues)中開立問題單。 -## 協力廠商 +## 範例 -我們的熱情活躍的社群已建立各式各樣的延伸項目、[中介軟體模組](/{{ page.lang }}/resources/middleware.html),以及更高層次的架構。相關資訊請參閱 [Wiki](https://github.com/expressjs/express/wiki)。 +檢視儲存庫中數十個 Express 應用程式[範例](https://github.com/expressjs/express/tree/master/examples),從 API 設計與鑑別,到範本引擎的整合,樣樣涵蓋在內。 + +## 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. + +# Branding of Express.js + +## 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. +
    +
    +

    Logotype

    + Express.js logo + + + Express.js logo + +
    +
    +

    Logomark

    + Express.js mark + + + Express.js mark + +
    +
    +
    \ No newline at end of file diff --git a/zh-tw/resources/contributing.md b/zh-tw/resources/contributing.md new file mode 100644 index 0000000000..d1e22b5dcd --- /dev/null +++ b/zh-tw/resources/contributing.md @@ -0,0 +1,551 @@ +--- +layout: page +title: Contributing to Express +description: Find out how to contribute to Express.js, including guidelines for reporting issues, submitting pull requests, becoming a collaborator, and understanding security policies. +menu: resources +lang: zh-tw +redirect_from: " " +--- + +# Contributing to Express + +### Looking to contribute to Expressjs.com? Click [here](#expressjs-website-contributing). + +Express and the other projects in the [expressjs organization on GitHub](https://github.com/expressjs) are projects of the [OpenJs Foundation](https://openjsf.org/). +These projects are governed under the general policies and guidelines of the Node.js Foundation along with the additional guidelines below. + +- [Technical committee](#technical-committee) +- [Community contributing guide](#community-contributing-guide) +- [Collaborator's guide](#collaborators-guide) +- [Security policies and procedures](#security-policies-and-procedures) + +## Technical committee + +The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](community.html#technical-committee). + +## Community contributing guide + + + +The goal of this document is to create a contribution process that: + +- Encourages new contributions. +- Encourages contributors to remain involved. +- Avoids unnecessary processes and bureaucracy whenever possible. +- Creates a transparent decision making process that makes it clear how + contributors can be involved in decision making. + +### Vocabulary + +- A **Contributor** is any individual creating or commenting on an issue or pull request. +- A **Committer** is a subset of contributors who have been given write access to the repository. +- A **Project Captain** is the lead maintainer of a repository. +- A **TC (Technical Committee)** is a group of committers representing the required technical + expertise to resolve rare disputes. +- A **Triager** is a subset of contributors who have been given triage access to the repository. + +### Logging Issues + +Log an issue for any question or problem you might have. When in doubt, log an issue, and +any additional policies about what to include will be provided in the responses. The only +exception is security disclosures which should be sent privately. + +Committers may direct you to another repository, ask for additional clarifications, and +add appropriate metadata before the issue is addressed. + +Please be courteous and respectful. Every participant is expected to follow the +project's Code of Conduct. + +### Contributions + +Any change to resources in this repository must be through pull requests. This applies to all changes +to documentation, code, binary files, etc. Even long term committers and TC members must use +pull requests. + +No pull request can be merged without being reviewed. + +For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that +contributors in other timezones have time to review. Consideration should also be given to +weekends and other holiday periods to ensure active committers all have reasonable time to +become involved in the discussion and review process if they wish. + +The default for each contribution is that it is accepted once no committer has an objection. +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. There is no additional "sign off" +process for contributions to land. Once all issues brought by committers are addressed it can +be landed by any committer. + +In the case of an objection being raised in a pull request by another committer, all involved +committers should seek to arrive at a consensus by way of addressing concerns being expressed +by discussion, compromise on the proposed change, or withdrawal of the proposed change. + +If a contribution is controversial and committers cannot agree about how to get it to land +or if it should land then it should be escalated to the TC. TC members should regularly +discuss pending contributions in order to find a resolution. It is expected that only a +small minority of issues be brought to the TC for resolution and that discussion and +compromise among committers be the default resolution mechanism. + +### Becoming a Triager + +Anyone can become a triager! Read more about the process of being a triager in +[the triage process document](https://github.com/expressjs/express/blob/master/Triager-Guide.md). + +Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate +a new triager. If you are interested in becoming a triager, our best advice is to actively participate +in the community by helping triaging issues and pull requests. As well we recommend +to engage in other community activities like attending the TC meetings, and participating in the Slack +discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd +be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. + +You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) +if you have questions or need guidance. + +### Becoming a Committer + +All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, +and added as a committer, and be given write access to the repository. + +Committers are expected to follow this policy and continue to send pull requests, go through +proper review, and have other committers merge their pull requests. + +### TC Process + +The TC uses a "consensus seeking" process for issues that are escalated to the TC. +The group tries to find a resolution that has no open objections among TC members. +If a consensus cannot be reached that has no objections then a majority wins vote +is called. It is also expected that the majority of decisions made by the TC are via +a consensus seeking process and that voting is only used as a last-resort. + +Resolution may involve returning the issue to project captains with suggestions on +how to move forward towards a consensus. It is not expected that a meeting of the TC +will resolve all issues on its agenda during that meeting and may prefer to continue +the discussion happening among the project captains. + +Members can be added to the TC at any time. 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. The TC will consist of a minimum of 3 active members and a +maximum of 10. If the TC should drop below 5 members the active TC members should nominate +someone new. If a TC member is stepping down, they are encouraged (but not required) to +nominate someone to take their place. + +TC members will be added as admin's on the Github orgs, npm orgs, and other resources as +necessary to be effective in the role. + +To remain "active" a TC member should have participation within the last 12 months and miss +no more than six consecutive TC meetings. 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). Members who do not meet this +are expected to step down. If A TC member does not step down, an issue can be opened in the +discussions repo to move them to inactive status. TC members who step down or are removed due +to inactivity will be moved into inactive status. + +Inactive status members can become active members by self nomination if the TC is not already +larger than the maximum of 10. They will also be given preference if, while at max size, an +active member steps down. + +### Project Captains + +The Express TC can designate captains for individual projects/repos in the +organizations. These captains are responsible for being the primary +day-to-day maintainers of the repo on a technical and community front. +Repo captains are empowered with repo ownership and package publication rights. +When there are conflicts, especially on topics that effect the Express project +at large, captains are responsible to raise it up to the TC and drive +those conflicts to resolution. Captains are also responsible for making sure +community members follow the community guidelines, maintaining the repo +and the published package, as well as in providing user support. + +Like TC members, Repo captains are a subset of committers. + +To become a captain for a project the candidate is expected to participate in that +project for at least 6 months as a committer prior to the request. They should have +helped with code contributions as well as triaging issues. They are also required to +have 2FA enabled on both their GitHub and npm accounts. + +Any TC member or an existing captain on the **same** repo can nominate another committer +to the captain role. To do so, they should submit a PR to this document, updating the +**Active Project Captains** section (while maintaining the sort order) with the project +name, the nominee's GitHub handle, and their npm username (if different). + +- Repos can have as many captains as make sense for the scope of work. +- A TC member or an existing repo captain **on the same project** can nominate a new captain. + Repo captains from other projects should not nominate captains for a different project. + +The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow +for comment and/or dissent. When the PR is merged, a TC member will add them to the +proper GitHub/npm groups. + +#### Active Projects and Captains + +- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd +- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon +- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon +- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon +- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon +- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon +- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon +- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon +- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd +- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon +- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon +- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon +- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas +- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon +- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd +- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon +- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon +- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon +- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon +- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon +- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon +- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon +- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon +- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd +- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon +- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon +- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey +- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey +- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey +- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey +- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey +- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey +- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey +- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey +- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey +- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon +- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey +- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey +- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon +- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon +- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey +- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon +- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey +- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon +- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey +- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey +- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey +- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey +- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey +- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon +- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey +- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon +- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon +- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey +- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey +- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey +- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd +- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey +- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon +- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey +- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon + +#### Current Initiative Captains + +- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon + +### Developer's Certificate of Origin 1.1 + +```text +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +## Collaborator's guide + + + +### Website Issues + +Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. + +### PRs and Code contributions + +- Tests must pass. +- Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. +- If you fix a bug, add a test. + +### Branches + +Use the `master` branch for bug fixes or minor work that is intended for the +current release stream. + +Use the correspondingly named branch, e.g. `5.0`, for anything intended for +a future release of Express. + +### Steps for contributing + +1. [Create an issue](https://github.com/expressjs/express/issues/new) for the + bug you want to fix or the feature that you want to add. +2. Create your own [fork](https://github.com/expressjs/express) on GitHub, then + checkout your fork. +3. Write your code in your local copy. It's good practice to create a branch for + each new issue you work on, although not compulsory. +4. To run the test suite, first install the dependencies by running `npm install`, + then run `npm test`. +5. Ensure your code is linted by running `npm run lint` -- fix any issue you + see listed. +6. If the tests pass, you can commit your changes to your fork and then create + a pull request from there. Make sure to reference your issue from the pull + request comments by including the issue number e.g. `#123`. + +### Issues which are questions + +We will typically close any vague issues or questions that are specific to some +app you are writing. Please double check the docs and other references before +being trigger happy with posting a question issue. + +Things that will help get your question issue looked at: + +- Full and runnable JS code. +- Clear description of the problem or unexpected behavior. +- Clear description of the expected result. +- Steps you have taken to debug it yourself. + +If you post a question and do not outline the above items or make it easy for +us to understand and reproduce your issue, it will be closed. + +## Security Policies and Procedures + + + +This document outlines security procedures and general policies for the Express +project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +### Reporting a Bug + +The Express team and community take all security bugs in Express seriously. +Thank you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `express-security@lists.openjsf.org`. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. 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. + +Report security bugs in third-party modules to the person or team maintaining +the module. + +### Pre-release Versions + +Alpha and Beta releases are unstable and **not suitable for production use**. +Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section. +Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release. + +### 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. + +### The Express Threat Model + +We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) + +### Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. + +---- + +# Contributing to Expressjs.com {#expressjs-website-contributing} + + + +### The Official Documentation of the Express JS Framework + +This is the contribution documentation for the [Expressjs.com](https://github.com/expressjs/expressjs.com) website. + +#### Need some ideas? These are some typical issues. + +1. **Website issues**: + If you see anything on the site that could use a tune-up, think about how to fix it. + + - Display or screen sizing problems + - Mobile responsiveness issues + - Missing or broken accessibility features + - Website outages + - Broken links + - Page structure or user interface enhancements + +2. **Content Issues**: + Fix anything related to site content or typos. + - Spelling errors + - Incorrect/outdated Express JS documentation + - Missing content + +3. **Translation Issues**: Fix any translation errors or contribute new content. + - Fix spelling errors + - Fix incorrect/poorly translated words + - Translate new content + +> **IMPORTANT:** +> All translation submissions are currently paused. See this [notice](#notice-we-have-paused-all-translation-contributions) for more information. + +- Check out the [Contributing translations](#contributing-translations) section below for a contributing guide. + +#### Want to work on a backlog issue? + +We often have bugs or enhancements that need work. You can find these under our repo's [Issues tab](https://github.com/expressjs/expressjs.com/issues). Check out the tags to find something that's a good match for you. + +#### Have an idea? Found a bug? + +If you've found a bug or a typo, or if you have an idea for an enhancement, you can: + +- Submit a [new issue](https://github.com/expressjs/expressjs.com/issues/new/choose) on our repo. Do this for larger proposals, or if you'd like to discuss or get feedback first. +- Make a [Github pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). If you have already done work and it's ready to go, feel free to send it our way. + +## Getting Started + +The steps below will guide you through the Expressjs.com contribution process. + +#### Step 1: (OPTIONAL) Open a New Issue + +So you've found a problem that you want to fix, or have a site enhancement you want to make. + +1. If you want to get feedback or discuss, open a discussion [issue](https://github.com/expressjs/expressjs.com/issues/new/choose) prior to starting work. This is not required, but encouraged for larger proposals. + - While we highly encourage this step, it is only for submissions proposing significant change. It helps us to clarify and focus the work, and ensure it aligns with overall project priorities. + - For submissions proposing minor improvements or corrections, this is not needed. You can skip this step. + - When opening an issue please give it a title and fill in the description section. The more details you provide, the more feedback we can give. + +2. After receiving your issue the Express JS documentation team will respond with feedback. We read every submission and always try to respond quickly with feedback. + - For submissions proposing significant change, we encourage you to follow the review process before starting work. + +#### Step 2: Get the Application Code Base + +Clone the repo and get the code: + +``` +git clone https://github.com/expressjs/expressjs.com.git +``` + +After you've got the code you're ready to start making your changes! + +But just in case you need a little extra explanation, this section below outlines the main sections of the code base, where most changes are likely to be made. + +**Markdown Page Files**: + +- These files render to html and make up the individual pages of the site. Most of the site's documentation text content is written in `md` files. +- Change these to make changes to individual pages' content/text or markup. +- Each language has its own complete set of pages, located under their respective language directories - all the Spanish markdown content is found in the `es` directory, for example. + +**Includes Partials and Layout Templates** + +- `_includes` are partials that are imported and reused across multiple pages. + - These are used to import text content for reuse across pages, such as the API documentation, e.g., `_includes > api > en > 5x`, which is included in every language. + - These are used to include the page components that make up site-wide user interface and periphery structure, e.g., Header, Footer, etc. +- `_layouts` are the templates used to wrap the site's individual pages. + - These are used to display the structure of the site's periphery, such as the header and footer, and for injecting and displaying individual markdown pages inside the `content` tag. + +**Blog Markdown Files** + +- These files make up the individual blog posts. If you want to contribute a blog post please + follow the specific instructions for [How to write a blog post.](https://expressjs.com/en/blog/write-post.html) +- Located under the `_posts` directory. + +**CSS or Javascript** + +- All css and js files are kept in `css` and `js` folders on the project root. + +The Express JS website is build using [Jeykyll](https://jekyllrb.com/) and is hosted on [Github Pages](https://pages.github.com/). + +#### Step 3: Running the Application + +Now you'll need a way to see your changes, which means you'll need a running version of the application. You have two options. + +1. **Run Locally**: This gets the local version of the application up and running on your machine. Follow our [Local Setup Guide](https://github.com/expressjs/expressjs.com?tab=readme-ov-file#local-setup) to use this option. + - This is the recommended option for moderate to complex work. +2. **Run using Deploy Preview**: Use this option if you don't want to bother with a local installation. Part of our continuous integration pipeline includes [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/). + 1. To use this you'll need to get your changes online - after you've made your first commit on your feature branch, make a _draft_ pull request. + 2. After the build steps are complete, you'll have access to a **Deploy Preview** tab that will run your changes on the web, rebuilding after each commit is pushed. + 3. After you are completely done your work and it's ready for review, remove the draft status on your pull request and submit your work. + +## Contributing translations + +#### Notice: We have paused all translation contributions. + +> **IMPORTANT:** +> We are currently working toward a more streamlined translations workflow. As long as this notice is posted, we will _not_ be accepting any translation submissions. + +We highly encourage community translations! We no longer have professional translations, and we believe in the power of our community to provide accurate and helpful translations. + +The documentation is translated into these languages: + +- English (`en`) +- Spanish (`es`) +- French (`fr`) +- Italian (`it`) +- Indonesian (`id`) +- Japanese (`ja`) +- Korean (`ko`) +- Brazilian Portuguese (`pt-br`) +- Russian (`ru`) +- Slovak (`sk`) +- Thai (`th`) +- Turkish (`tr`) +- Ukrainian (`uk`) +- Uzbek (`uz`) +- Simplified Chinese (`zh-cn`) +- Traditional Chinese (`zh-tw`) + +### Adding New Full Site Translations + +If you find a translation is missing from the list you can create a new one. + +To translate Expressjs.com into a new language, follow these steps: + +1. Clone the [`expressjs.com`](https://github.com/expressjs/expressjs.com) repository. +2. Create a directory for the language of your choice using its [ISO 639-1 code](https://www.loc.gov/standards/iso639-2/php/code_list.php) as its name. +3. Copy `index.md`, `api.md`, `starter/`, `guide/`, `advanced/`, `resources/`, `4x/`, and `3x/`, to the language directory. +4. Remove the link to 2.x docs from the "API Reference" menu. +5. Update the `lang` variable in the copied markdown files. +6. Update the `title` variable in the copied markdown files. +7. Create the header, footer, notice, and announcement file for the language in the `_includes/` directory, in the respective directories, and make necessary edits to the contents. +8. Create the announcement file for the language in the `_includes/` directory. +9. Make sure to append `/{{ page.lang }}` to all the links within the site. +10. Update the [CONTRIBUTING.md](https://github.com/expressjs/expressjs.com/blob/gh-pages/CONTRIBUTING.md#contributing-translations) and the `.github/workflows/translation.yml` files with the new language. + +### Adding Page and Section Translations + +Many site translations are still missing pages. To find which ones we need help with, you can [filter for merged PRs](https://github.com/expressjs/expressjs.com/pulls?q=is%3Apr+is%3Aclosed+label%3Arequires-translation-es) that include the tag for your language, such as `requires-translation-es` for requires Spanish translation. + +If you contribute a page or section translation, please reference the original PR. This helps the person merging your translation to remove the tag from the original PR. diff --git a/zh-tw/resources/glossary.md b/zh-tw/resources/glossary.md old mode 100755 new mode 100644 index 9a8792a06e..267dda0ae8 --- a/zh-tw/resources/glossary.md +++ b/zh-tw/resources/glossary.md @@ -1,58 +1,66 @@ --- layout: page title: Express 名詞解釋 +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. menu: resources lang: zh-tw -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. +redirect_from: " " --- # 名詞解釋 +### 應用程式 (application) + +In general, one or more programs that are designed to carry out operations for a specific purpose. 通常是指設計成實行作業以達特定目的的一或多個程式。就 Express 環境定義來說,是指使用 Express API(在 Node.js 平台上執行)的程式。亦可稱為[應用程式物件 (app object)](/{{ page.lang }}/api.html#express)。 Might also refer to an [app object](/{{ page.lang }}/api.html#express). + ### API -應用程式設計介面。在第一次使用時,會拼寫出縮寫。 +Application programming interface. Spell out the abbreviation when it is first used. ### Express -快速、集思廣益、極簡的 Node.js 應用程式 Web 架構。一般而言,"Express" 比 "Express.js" 合適,不過,也能接受後者。 +A fast, un-opinionated, minimalist web framework for Node.js applications. 快速、集思廣益、極簡的 Node.js 應用程式 Web 架構。一般而言,"Express" 比 "Express.js" 合適,不過,也能接受後者。 ### libuv 多平台支援的程式庫,著重在非同步 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: + +- `var foo = require('middleware')` 可稱為_需要_或_使用_ Node.js 模組。接著,`var mw = foo()` 陳述式通常會傳回中介軟體。 Then the statement `var mw = foo()` typically returns the middleware. +- `app.use(mw)` 可稱為_將中介軟體新增至廣域處理程序堆疊_。 +- `app.get('/foo', mw, function (req, res) { ... })` 可稱為_將中介軟體新增至 "GET /foo" 處理程序堆疊_。 + ### Node.js -一種軟體平台,用來建置可調式網路應用程式。Node.js 使用 JavaScript 作為其 Scripting 語言,並透過非封鎖 I/O 和單一執行緒事件迴圈,來達到高傳輸量。請參閱 [nodejs.org](http://nodejs.org/)。**使用注意事項**:一開始稱為 "Node.js",之後稱為 "Node"。 +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". + +### 開放程式碼 (open-source, open source) -### 中介軟體 (middleware) +當作為形容詞時,會加連號;例如:"This is open-source software." 請參閱[維基百科上的開放程式碼軟體](http://en.wikipedia.org/wiki/Open-source_software)。附註:雖然此術語通常不會加連號,我們仍採用標準的英文規則,加上連號來代表複合形容詞。 -Express 路由層在最終要求處理程式之前所呼叫的函數,因此它位於原始要求與最終預期的路由中間。中介軟體周圍會有少許合宜的專有名詞點: +{% capture english-rules %} - * `var foo = require('middleware')` 可稱為*需要*或*使用* Node.js 模組。接著,`var mw = foo()` 陳述式通常會傳回中介軟體。 - * `app.use(mw)` 可稱為*將中介軟體新增至廣域處理程序堆疊*。 - * `app.get('/foo', mw, function (req, res) { ... })` 可稱為*將中介軟體新增至 "GET /foo" 處理程序堆疊*。 +Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. -### 回應 (response) +{% endcapture %} -一種 HTTP 回應。伺服器傳回 HTTP 回應訊息給用戶端。回應包含要求的相關完成狀態資訊,也可能將要求內容包含在其訊息內文中。 +{% include admonitions/note.html content=english-rules %} ### 要求 (request) -一種 HTTP 要求。用戶端提交 HTTP 要求訊息給伺服器,再由伺服器傳回回應。要求必須使用其中一種[要求方法](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods),例如 GET、POST 等。 +An HTTP request. A client submits an HTTP request message to a server, which returns a response. 一種 HTTP 要求。用戶端提交 HTTP 要求訊息給伺服器,再由伺服器傳回回應。要求必須使用其中一種[要求方法](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods),例如 GET、POST 等。 -### 開放程式碼 (open-source, open source) +### 回應 (response) -當作為形容詞時,會加連號;例如:"This is open-source software." 請參閱[維基百科上的開放程式碼軟體](http://en.wikipedia.org/wiki/Open-source_software)。附註:雖然此術語通常不會加連號,我們仍採用標準的英文規則,加上連號來代表複合形容詞。 +一種 HTTP 回應。伺服器傳回 HTTP 回應訊息給用戶端。回應包含要求的相關完成狀態資訊,也可能將要求內容包含在其訊息內文中。 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. ### 路由 (route) -URL 的一部分,用來識別資源。例如,在 `http://foo.com/products/id` 中,"/products/id" 就是路由。 +Part of a URL that identifies a resource. URL 的一部分,用來識別資源。例如,在 `http://foo.com/products/id` 中,"/products/id" 就是路由。 ### 路由器 (router) 請參閱 API 參照中的[路由器](/{{ page.lang }}/4x/api.html#router)。 - -### 應用程式 (application) - -通常是指設計成實行作業以達特定目的的一或多個程式。就 Express 環境定義來說,是指使用 Express API(在 Node.js 平台上執行)的程式。亦可稱為[應用程式物件 (app object)](/{{ page.lang }}/api.html#express)。 diff --git a/zh-tw/resources/middleware.md b/zh-tw/resources/middleware.md old mode 100755 new mode 100644 index 3bea5d275b..7f23f370f0 --- a/zh-tw/resources/middleware.md +++ b/zh-tw/resources/middleware.md @@ -1,64 +1,45 @@ --- -layout: page +layout: middleware title: Express 中介軟體 +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. menu: resources lang: zh-tw -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. +redirect_from: " " +module: mw-home --- -# 協力廠商中介軟體 +## Express 中介軟體 -以下是部分的 Express 中介軟體模組: +The Express middleware modules listed here are maintained by the +[Expressjs team](https://github.com/orgs/expressjs/people). - - [body-parser](https://github.com/expressjs/body-parser):即先前的 `express.bodyParser`、`json` 和 `urlencoded`。另請參閱: - - [body](https://github.com/raynos/body) - - [co-body](https://github.com/visionmedia/co-body) - - [raw-body](https://github.com/stream-utils/raw-body) - - [compression](https://github.com/expressjs/compression):即先前的 `express.compress` - - [connect-image-optimus](https://github.com/msemenistyi/connect-image-optimus):可提供最佳影像的 Connect/Express 中介軟體模組。如果可能的話,請將影像切換成 `.webp` 或 `.jxr`。 - - [connect-timeout](https://github.com/expressjs/timeout):即先前的 `express.timeout` - - [cookie-parser](https://github.com/expressjs/cookie-parser):即先前的 `express.cookieParser` - - [cookie-session](https://github.com/expressjs/cookie-session):即先前的 `express.cookieSession` - - [errorhandler](https://github.com/expressjs/errorhandler):即先前的 `express.errorHandler` - - [express-debug](https://github.com/devoidfury/express-debug):低調的開發工具,可在您的應用程式中新增標籤,內含範本變數 (locals)、現行階段作業、有用的要求資料等相關資訊。 - - [express-partial-response](https://github.com/nemtsov/express-partial-response):Express 中介軟體模組,會根據 `fields` 查詢字串,使用 Google API 的 Partial Response 來濾除 JSON 回應部分。 - - [express-session](https://github.com/expressjs/session):即先前的 `express.session` - - [express-simple-cdn](https://github.com/jamiesteven/express-simple-cdn):Express 中介軟體模組,會將 CDN 用於靜態資產,並支援多部主機(例如:cdn1.host.com、cdn2.host.com)。 - - [express-slash](https://github.com/ericf/express-slash):Express 中介軟體模組,供嚴格看待尾端斜線的人員使用。 - - [express-stormpath](https://github.com/stormpath/stormpath-express):Express 中介軟體模組,供使用者執行儲存、鑑別、授權、SSO 和資料安全。 - - [express-uncapitalize](https://github.com/jamiesteven/express-uncapitalize):中介軟體模組,可將含有大寫的 HTTP 要求重新導向至標準小寫形式。 - - [helmet](https://github.com/helmetjs/helmet):此模組會設定各種 HTTP 標頭,有助於保護您應用程式的安全。 - - [join-io](https://github.com/coderaiser/join-io "join-io"):此模組會即時結合檔案,來減少要求計數。 - - [method-override](https://github.com/expressjs/method-override):即先前的 `express.methodOverride` - - [morgan](https://github.com/expressjs/morgan):即先前的 `logger` - - [passport](https://github.com/jaredhanson/passport):鑑別用的 Express 中介軟體模組。 - - [response-time](https://github.com/expressjs/response-time):即先前的 `express.responseTime` - - [serve-favicon](https://github.com/expressjs/serve-favicon):即先前的 `express.favicon` - - [serve-index](https://github.com/expressjs/serve-index):即先前的 `express.directory` - - [serve-static](https://github.com/expressjs/serve-static):此模組可提供靜態內容。 - - [static-expiry](https://github.com/paulwalker/connect-static-expiry):靜態資產的加指紋 URL 或「快取標頭」,還支援一或多個外部網域。 - - [vhost](https://github.com/expressjs/vhost):即先前的 `express.vhost` - - [view-helpers](https://github.com/madhums/node-view-helpers):Express 中介軟體模組,可提供一般 helper 方法給視圖。 - - [sriracha-admin](https://github.com/hdngr/siracha):Express 中介軟體模組,可為 Mongoose 動態產生管理網站。 +| Middleware module | Description | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [body-parser](/{{page.lang}}/resources/middleware/body-parser.html) | Parse HTTP request body. | +| [compression](/{{page.lang}}/resources/middleware/compression.html) | Compress HTTP responses. | +| [connect-rid](/{{page.lang}}/resources/middleware/connect-rid.html) | Generate unique request ID. | +| [cookie-parser](/{{page.lang}}/resources/middleware/cookie-parser.html) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | +| [cookie-session](/{{page.lang}}/resources/middleware/cookie-session.html) | Establish cookie-based sessions. | +| [cors](/{{page.lang}}/resources/middleware/cors.html) | Enable cross-origin resource sharing (CORS) with various options. | +| [errorhandler](/{{page.lang}}/resources/middleware/errorhandler.html) | Development error-handling/debugging. | +| [method-override](/{{page.lang}}/resources/middleware/method-override.html) | Override HTTP methods using header. | +| [morgan](/{{page.lang}}/resources/middleware/morgan.html) | HTTP request logger. | +| [multer](/{{page.lang}}/resources/middleware/multer.html) | Handle multi-part form data. | +| [response-time](/{{page.lang}}/resources/middleware/response-time.html) | Record HTTP response time. | +| [serve-favicon](/{{page.lang}}/resources/middleware/serve-favicon.html) | Serve a favicon. | +| [serve-index](/{{page.lang}}/resources/middleware/serve-index.html) | Serve directory listing for a given path. | +| [serve-static](/{{page.lang}}/resources/middleware/serve-static.html) | Serve static files. | +| [session](/{{page.lang}}/resources/middleware/session.html) | Establish server-based sessions (development only). | +| [timeout](/{{page.lang}}/resources/middleware/timeout.html) | Set a timeout perioHTTP request processing. | +| [vhost](/{{page.lang}}/resources/middleware/vhost.html) | Create virtual domains. | -Connect/Express 團隊不再支援 Connect 先前隨附的一些中介軟體模組。這些模組會以替代模組取代,或者應以更好的模組取代。請使用下列其中一個替代項目: +## Additional middleware modules - - express.cookieParser - - [cookies](https://github.com/jed/cookies) 和 [keygrip](https://github.com/jed/keygrip) - - express.limit - - [raw-body](https://github.com/stream-utils/raw-body) - - express.multipart - - [connect-busboy](https://github.com/mscdex/connect-busboy) - - [multer](https://github.com/expressjs/multer) - - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) - - express.query - - [qs](https://github.com/visionmedia/node-querystring) - - express.staticCache - - [st](https://github.com/isaacs/st) - - [connect-static](https://github.com/andrewrk/connect-static) +These are some additional popular middleware modules. -如需其他的中介軟體模組,請參閱: +{% include community-caveat.html %} - - [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) - - [expressjs](https://github.com/expressjs) +| Middleware module | Description | +| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [helmet](https://github.com/helmetjs/helmet):此模組會設定各種 HTTP 標頭,有助於保護您應用程式的安全。 | Helps secure your apps by setting various HTTP headers. | +| [passport](https://github.com/jaredhanson/passport):鑑別用的 Express 中介軟體模組。 | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | diff --git a/zh-tw/resources/middleware/body-parser.md b/zh-tw/resources/middleware/body-parser.md new file mode 100644 index 0000000000..a5fa461057 --- /dev/null +++ b/zh-tw/resources/middleware/body-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express body-parser middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: body-parser +--- diff --git a/zh-tw/resources/middleware/compression.md b/zh-tw/resources/middleware/compression.md new file mode 100644 index 0000000000..db65c0d7b8 --- /dev/null +++ b/zh-tw/resources/middleware/compression.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express compression middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: compression +--- diff --git a/zh-tw/resources/middleware/connect-rid.md b/zh-tw/resources/middleware/connect-rid.md new file mode 100644 index 0000000000..112b5d25f2 --- /dev/null +++ b/zh-tw/resources/middleware/connect-rid.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express connect-rid middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: connect-rid +--- diff --git a/zh-tw/resources/middleware/cookie-parser.md b/zh-tw/resources/middleware/cookie-parser.md new file mode 100644 index 0000000000..be2357fbc4 --- /dev/null +++ b/zh-tw/resources/middleware/cookie-parser.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-parser middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: cookie-parser +--- diff --git a/zh-tw/resources/middleware/cookie-session.md b/zh-tw/resources/middleware/cookie-session.md new file mode 100644 index 0000000000..bb982184b1 --- /dev/null +++ b/zh-tw/resources/middleware/cookie-session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cookie-session middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: cookie-session +--- diff --git a/zh-tw/resources/middleware/cors.md b/zh-tw/resources/middleware/cors.md new file mode 100644 index 0000000000..71d9afac24 --- /dev/null +++ b/zh-tw/resources/middleware/cors.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express cors middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: cors +--- diff --git a/zh-tw/resources/middleware/errorhandler.md b/zh-tw/resources/middleware/errorhandler.md new file mode 100644 index 0000000000..529ade05a2 --- /dev/null +++ b/zh-tw/resources/middleware/errorhandler.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express errorhandler middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: errorhandler +--- diff --git a/zh-tw/resources/middleware/method-override.md b/zh-tw/resources/middleware/method-override.md new file mode 100644 index 0000000000..083ee4d20f --- /dev/null +++ b/zh-tw/resources/middleware/method-override.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express method-override middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: method-override +--- diff --git a/zh-tw/resources/middleware/morgan.md b/zh-tw/resources/middleware/morgan.md new file mode 100644 index 0000000000..4fa8a1b85b --- /dev/null +++ b/zh-tw/resources/middleware/morgan.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express morgan middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: morgan +--- diff --git a/zh-tw/resources/middleware/multer.md b/zh-tw/resources/middleware/multer.md new file mode 100644 index 0000000000..cbdb8ae738 --- /dev/null +++ b/zh-tw/resources/middleware/multer.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express multer middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: multer +--- diff --git a/zh-tw/resources/middleware/response-time.md b/zh-tw/resources/middleware/response-time.md new file mode 100644 index 0000000000..e691cf7b6b --- /dev/null +++ b/zh-tw/resources/middleware/response-time.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express response-time middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: response-time +--- diff --git a/zh-tw/resources/middleware/serve-favicon.md b/zh-tw/resources/middleware/serve-favicon.md new file mode 100644 index 0000000000..1497900098 --- /dev/null +++ b/zh-tw/resources/middleware/serve-favicon.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-favicon middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: serve-favicon +--- diff --git a/zh-tw/resources/middleware/serve-index.md b/zh-tw/resources/middleware/serve-index.md new file mode 100644 index 0000000000..cb61ebecc3 --- /dev/null +++ b/zh-tw/resources/middleware/serve-index.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-index middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: serve-index +--- diff --git a/zh-tw/resources/middleware/serve-static.md b/zh-tw/resources/middleware/serve-static.md new file mode 100644 index 0000000000..80848a8342 --- /dev/null +++ b/zh-tw/resources/middleware/serve-static.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express serve-static middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: serve-static +--- diff --git a/zh-tw/resources/middleware/session.md b/zh-tw/resources/middleware/session.md new file mode 100644 index 0000000000..bf0866c3c2 --- /dev/null +++ b/zh-tw/resources/middleware/session.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express session middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: session +--- diff --git a/zh-tw/resources/middleware/timeout.md b/zh-tw/resources/middleware/timeout.md new file mode 100644 index 0000000000..17c659bae9 --- /dev/null +++ b/zh-tw/resources/middleware/timeout.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express timeout middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: timeout +--- diff --git a/zh-tw/resources/middleware/vhost.md b/zh-tw/resources/middleware/vhost.md new file mode 100644 index 0000000000..f834f1cf0e --- /dev/null +++ b/zh-tw/resources/middleware/vhost.md @@ -0,0 +1,8 @@ +--- +layout: middleware +title: Express vhost middleware +menu: resources +lang: zh-tw +redirect_from: " " +module: vhost +--- diff --git a/zh-tw/resources/utils.md b/zh-tw/resources/utils.md new file mode 100644 index 0000000000..fcefb3835c --- /dev/null +++ b/zh-tw/resources/utils.md @@ -0,0 +1,26 @@ +--- +layout: page +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. +menu: resources +lang: zh-tw +redirect_from: " " +--- + +## Express utility functions + +The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules +for utility functions that may be generally useful. + +| 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. | + +For additional low-level HTTP-related modules, see [jshttp](http://jshttp.github.io/). diff --git a/zh-tw/starter/basic-routing.md b/zh-tw/starter/basic-routing.md old mode 100755 new mode 100644 index 9ea60f14ee..aa6c435f10 --- a/zh-tw/starter/basic-routing.md +++ b/zh-tw/starter/basic-routing.md @@ -1,25 +1,25 @@ --- layout: page title: Express 基本路由 +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. menu: starter lang: zh-tw -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. +redirect_from: " " --- # 基本路由 -*路由*是指判斷應用程式如何回應用戶端對特定端點的要求,而這個特定端點是一個 URI(或路徑)與一個特定的 HTTP 要求方法(GET、POST 等)。 +_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). -每一個路由可以有一或多個處理程式函數,當路由相符時,就會執行這些函數。 +Each route can have one or more handler functions, which are executed when the route is matched. 路由定義的結構如下: + ```js app.METHOD(PATH, HANDLER) ``` -其中: +Where: - `app` 是 `express` 的實例。 - `METHOD` 是 [HTTP 要求方法](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)。 @@ -27,7 +27,9 @@ app.METHOD(PATH, HANDLER) - `HANDLER` 是當路由相符時要執行的函數。
    +This tutorial assumes that an instance of `express` named `app` is created and the server is running. 這項指導教學假設已建立名稱為 `app` 的 `express` 實例,且伺服器正在執行。如果您不熟悉如何建立和啟動應用程式,請參閱 [Hello world 範例](/{{ page.lang }}/starter/hello-world.html)。 +
    下列範例說明如何定義簡單的路由。 @@ -65,3 +67,5 @@ app.delete('/user', (req, res) => { ``` 如需路由的詳細資料,請參閱[路由手冊](/{{ page.lang }}/guide/routing.html)。 + +### [Previous: Express application generator ](/{{ page.lang }}/starter/generator.html)    [Next: Serving static files in Express ](/{{ page.lang }}/starter/static-files.html) \ No newline at end of file diff --git a/zh-tw/starter/examples.md b/zh-tw/starter/examples.md new file mode 100644 index 0000000000..2cfef82d16 --- /dev/null +++ b/zh-tw/starter/examples.md @@ -0,0 +1,22 @@ +--- +layout: page +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. +menu: starter +lang: zh-tw +redirect_from: " " +--- + +{% capture examples %}{% include readmes/express-master/examples.md %}{% endcapture %} +{{ examples | replace: "](.", "](https://github.com/expressjs/express/tree/master/examples" }} + +## Additional examples + +These are some additional examples with more extensive integrations. + +{% include community-caveat.html %} + +- [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 + +### [Previous: Static Files ](/{{ page.lang }}/starter/static-files.html)    [Next: FAQ ](/{{ page.lang }}/starter/faq.html) diff --git a/zh-tw/starter/faq.md b/zh-tw/starter/faq.md old mode 100755 new mode 100644 index e612ebe2a1..3b15caa89f --- a/zh-tw/starter/faq.md +++ b/zh-tw/starter/faq.md @@ -1,54 +1,74 @@ --- layout: page title: Express 常見問題 (FAQ) +description: Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more. menu: starter lang: zh-tw -description: Find answers to frequently asked questions about Express.js, including - topics on application structure, models, authentication, template engines, error - handling, and more. +redirect_from: " " --- # 常見問題 (FAQ) ## 我該如何建立我的應用程式結構? -這個問題沒有明確答案。此答案取決於您應用程式的規模和涉及的團隊。為了盡可能靈活,Express 對於結構沒有任何的假設。 +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. -您可以根據自己的喜好,將路由和應用程式特定的其他邏輯放在任意數目的檔案和任何的目錄結構中。請檢視下列範例,以獲得一些啟發: +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: -* [路由清單](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) -* [路由對映](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) -* [MVC 樣式控制器](https://github.com/expressjs/express/tree/master/examples/mvc) +- [路由清單](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-47) +- [路由對映](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66) +- [MVC 樣式控制器](https://github.com/expressjs/express/tree/master/examples/mvc) 此外,Express 有一些協力廠商延伸,可簡化部分這些型樣: -* [express-resource 路由](https://github.com/expressjs/express-resource) +- [express-resource 路由](https://github.com/expressjs/express-resource) ## 如何定義模型? -Express 不會注意到資料庫的存在。此概念留給協力廠商 Node 模組處理,如此可讓您與幾近全部的資料庫溝通。 +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. 請參閱 [LoopBack](http://loopback.io),取得以模組為中心的 Express 型架構。 ## 如何鑑別使用者? -鑑別是 Express 另一個不涉及的自用領域。您可以使用任何您想要的鑑別方法。如需簡易使用者名稱 / 密碼方法,請參閱[這個範例](https://github.com/expressjs/express/tree/master/examples/auth)。 - +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 支援哪些範本引擎? Express 支援符合 `(path, locals, callback)` 簽章的任何範本引擎。若要使範本引擎介面和快取正規化,請參閱 [consolidate.js](https://github.com/visionmedia/consolidate.js) 專案,以取得支援。未列出的範本引擎可能仍支援 Express 簽章。 +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. + +For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). ## 如何處理 404 回應? -在 Express 中,404 回應並不是錯誤的結果,因此錯誤處理常式中介軟體不會擷取它們。會有此行為是因為 404 回應僅表示沒有額外的工作來執行;換句話說,Express 已執行所有的中介軟體函數和路由,並發現它們都沒有回應。您唯一要做的是在堆疊的最底端(其他所有函數下方),新增一個中介軟體函數,以處理 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: ```js app.use((req, res, next) => { - res.status(404).send('Sorry cant find that!') + res.status(404).send("Sorry can't find that!") }) ``` +Add routes dynamically at runtime on an instance of `express.Router()` +so the routes are not superseded by a middleware function. + ## 如何設定錯誤處理程式? 錯誤處理中介軟體的定義方式,與其他中介軟體相同,差別在於引數是四個而非三個,具體來說,就是使用 `(err, req, res, next)` 簽章: @@ -64,4 +84,14 @@ app.use((err, req, res, next) => { ## 如何呈現一般 HTML? -不需要!不需要用 `res.render()` 函數來「呈現」HTML。如果您有特定的檔案,請使用 `res.sendFile()` 函數。如果您會從目錄提供許多資產,請使用 `express.static()` 中介軟體函數。 +You don't! 不需要!不需要用 `res.render()` 函數來「呈現」HTML。如果您有特定的檔案,請使用 `res.sendFile()` 函數。如果您會從目錄提供許多資產,請使用 `express.static()` 中介軟體函數。 +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. + +## What version of Node.js does Express require? + +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + +### [Previous: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/zh-tw/starter/generator.md b/zh-tw/starter/generator.md old mode 100755 new mode 100644 index f2272daae4..87fee251d3 --- a/zh-tw/starter/generator.md +++ b/zh-tw/starter/generator.md @@ -1,20 +1,27 @@ --- layout: page title: Express 應用程式產生器 +description: Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration. menu: starter lang: zh-tw -description: Learn how to use the Express application generator tool to quickly create - a skeleton for your Express.js applications, streamlining setup and configuration. +redirect_from: " " --- # Express 應用程式產生器 -使用應用程式產生器工具 `express`,快速建立應用程式架構。 +Use the application generator tool, `express-generator`, to quickly create an application skeleton. -使用下列指令來安裝 `express`: +You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash -$ npm install express-generator -g +$ npx express-generator +``` + +For earlier Node versions, install the application generator as a global npm package and then launch it: + +```bash +$ npm install -g express-generator +$ express ``` 使用 `-h` 選項來顯示指令選項: @@ -22,7 +29,7 @@ $ npm install express-generator -g ```bash $ express -h - Usage: express [options][dir] + Usage: express [options] [dir] Options: @@ -33,13 +40,13 @@ $ express -h --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine - -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) - -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` -舉例來說,以下是在現行工作目錄中建立一個名為 _myapp_ 的 Express 應用程式: +舉例來說,以下是在現行工作目錄中建立一個名為 _myapp_ 的 Express 應用程式: The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp @@ -82,9 +89,15 @@ $ DEBUG=myapp:* npm start > set DEBUG=myapp:* & npm start ``` -然後在瀏覽器中載入 `http://localhost:3000/`,以存取應用程式。 +On Windows PowerShell, use this command: -產生的應用程式具有如下的目錄結構: +```bash +PS> $env:DEBUG='myapp:*'; npm start +``` + +Then, load `http://localhost:3000/` in your browser to access the app. + +The generated app has the following directory structure: ```bash . @@ -109,5 +122,7 @@ $ DEBUG=myapp:* npm start ```
    -使用產生器來建立應用程式結構,只是多種用來建立 Express 應用程式結構的其中一種方式。您有權使用這種結構,或是加以修改盡量符合您的需求。 +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.
    + +### [Previous: Hello World ](/{{ page.lang }}/starter/hello-world.html)    [Next: Basic routing](/{{ page.lang }}/starter/basic-routing.html) diff --git a/zh-tw/starter/hello-world.md b/zh-tw/starter/hello-world.md old mode 100755 new mode 100644 index 53d6dcc817..3071f11790 --- a/zh-tw/starter/hello-world.md +++ b/zh-tw/starter/hello-world.md @@ -1,21 +1,19 @@ --- layout: page title: Express "Hello World" 範例 +description: Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners. menu: starter lang: zh-tw -description: Get started with Express.js by building a simple 'Hello World' application, - demonstrating the basic setup and server creation for beginners. +redirect_from: " " --- # Hello world 範例
    +Embedded below is essentially the simplest Express app you can create. 本質上,這是您所能建立的最簡易 Express 應用程式。它是單一檔案應用程式 — 與您使用 [Express 產生器](/{{ page.lang }}/starter/generator.html)所產生的結果*不同*,Express 產生器會建立完整應用程式框架,其中含有眾多 JavaScript 檔案、Jade 範本,以及各種用途的子目錄。 -
    - -首先請建立一個名為 `myapp` 的目錄,切換至該目錄,並執行 `npm init`。然後按照[安裝手冊](/{{ page.lang }}/starter/installing.html),將 `express` 安裝成一個相依關係。 -在 `myapp` 目錄中,建立名為 `app.js` 的檔案,並新增下列程式碼: +
    ```js const express = require('express') @@ -31,7 +29,13 @@ app.listen(port, () => { }) ``` -應用程式會啟動伺服器,並在埠 3000 接聽連線。應用程式對指向根 URL (`/`) 或*路由*的要求,以 "Hello World!" 回應。對於其他每一個路徑,它的回應是 **404 找不到**。 +This app starts a server and listens on port 3000 for connections. 應用程式會啟動伺服器,並在埠 3000 接聽連線。應用程式對指向根 URL (`/`) 或_路由_的要求,以 "Hello World!" 回應。對於其他每一個路徑,它的回應是 **404 找不到**。 + +### Running Locally + +首先請建立一個名為 `myapp` 的目錄,切換至該目錄,並執行 `npm init`。然後按照[安裝手冊](/{{ page.lang }}/starter/installing.html),將 `express` 安裝成一個相依關係。 Then, install `express` as a dependency, as per the [installation guide](/{{ page.lang }}/starter/installing.html). + +在 `myapp` 目錄中,建立名為 `app.js` 的檔案,並新增下列程式碼:
    `req`(要求)和 `res`(回應)與 Node 提供的物件完全相同,因此您可以呼叫 `req.pipe()`、`req.on('data', callback)`,以及任何您要執行的項目,而不需要 Express 涉及。 @@ -45,3 +49,4 @@ $ node app.js 然後在瀏覽器中載入 [http://localhost:3000/](http://localhost:3000/),以查看輸出。 +### [Previous: Installing ](/{{ page.lang }}/starter/installing.html)    [Next: Express Generator ](/{{ page.lang }}/starter/generator.html) diff --git a/zh-tw/starter/installing.md b/zh-tw/starter/installing.md old mode 100755 new mode 100644 index 8a1af3de95..a645dfb179 --- a/zh-tw/starter/installing.md +++ b/zh-tw/starter/installing.md @@ -1,48 +1,56 @@ --- layout: page title: 安裝 Express +description: Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm. menu: starter lang: zh-tw -description: Learn how to install Express.js in your Node.js environment, including - setting up your project directory and managing dependencies with npm. +redirect_from: " " --- # 安裝 假設您已安裝 [Node.js](https://nodejs.org/),請建立目錄來保留您的應用程式,並使它成為您的工作目錄。 +- [Express 4.x](/{{ page.lang }}/4x/api.html) requires Node.js 0.10 or higher. +- [Express 5.x](/{{ page.lang }}/5x/api.html) requires Node.js 18 or higher. + ```bash $ mkdir myapp $ cd myapp ``` +Use the `npm init` command to create a `package.json` file for your application. 使用 `npm init` 指令,為您的應用程式建立 `package.json` 檔。如需 `package.json` 如何運作的相關資訊,請參閱 [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json)。 ```bash $ npm init ``` -這個指令會提示您提供一些事項,例如:您應用程式的名稱和版本。現在,您只需按下 RETURN 鍵,接受大部分的預設值,但下列除外: +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: -```bash +``` entry point: (index.js) ``` -輸入 `app.js`,或您所要的主要檔名稱。如果您希望其名稱是 `index.js`,請按 RETURN 鍵,接受建議的預設檔名。 - -現在,將 Express 安裝在 `myapp` 目錄中,並儲存在相依關係清單中。例如: +輸入 `app.js`,或您所要的主要檔名稱。如果您希望其名稱是 `index.js`,請按 RETURN 鍵,接受建議的預設檔名。 If you want it to be `index.js`, hit RETURN to accept the suggested default file name. +現在,將 Express 安裝在 `myapp` 目錄中,並儲存在相依關係清單中。例如: For example: ```bash -$ npm install express --save +$ npm install express ``` 如果只想暫時安裝 Express,而不新增至相依關係清單,請省略 `--save` 選項: ```bash -$ npm install express +$ npm install express --no-save ```
    + 安裝 Node 模組時,如果指定了 `--save` 選項,則會將這些模組新增至 `package.json` 檔中的 `dependencies` 清單。之後,當您在 `app` 目錄中執行 `npm install` 時,就會自動安裝相依關係清單中的模組。 + Then, afterwards, running `npm install` in the app directory will automatically install modules in the dependencies list.
    + +### [Next: Hello World ](/{{ page.lang }}/starter/hello-world.html) \ No newline at end of file diff --git a/zh-tw/starter/static-files.md b/zh-tw/starter/static-files.md old mode 100755 new mode 100644 index 9c95d908a5..4727075904 --- a/zh-tw/starter/static-files.md +++ b/zh-tw/starter/static-files.md @@ -1,17 +1,26 @@ --- layout: page title: 在 Express 中提供靜態檔案 +description: Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware. menu: starter lang: zh-tw -description: Understand how to serve static files like images, CSS, and JavaScript - in Express.js applications using the built-in 'static' middleware. +redirect_from: " " --- # 在 Express 中提供靜態檔案 -如果要提供影像、CSS 檔案和 JavaScript 檔案等之類的靜態檔案,請使用 Express 中的 `express.static` 內建中介軟體函數。 +To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express. -將含有靜態資產的目錄名稱傳遞給 `express.static` 中介軟體函數,就能直接開始提供檔案。舉例來說,使用下列程式碼在名稱是 `public` 的目錄中,提供影像、CSS 檔案和 JavaScript 檔案: +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](/{{page.lang}}/4x/api.html#express.static). + +For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`: ```js app.use(express.static('public')) @@ -31,14 +40,19 @@ http://localhost:3000/hello.html Express 會查閱靜態目錄的相對檔案,因此靜態目錄的名稱不是 URL 的一部分。
    -如果要使用多個靜態資產目錄,請呼叫 `express.static` 中介軟體函數多次: +To use multiple static assets directories, call the `express.static` middleware function multiple times: ```js app.use(express.static('public')) app.use(express.static('files')) ``` -Express 在查閱檔案時,會依照您使用 `express.static` 中介軟體函數來設定靜態目錄的順序。 +Express looks up the files in the order in which you set the static directories with the `express.static` middleware function. + +{% capture alert_content %} +For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. +{% endcapture %} +{% include admonitions/note.html content=alert_content %} 如果要為 `express.static` 函數所提供的檔案,建立虛擬路徑字首(其中的路徑事實上不存在於檔案系統中),請為靜態目錄[指定裝載路徑](/{{ page.lang }}/4x/api.html#app.use),如下所示: @@ -56,9 +70,13 @@ http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html ``` -不過,您提供給 `express.static` 函數的路徑,是相對於您從中啟動 `node` 程序的目錄。如果您是從另一個目錄執行 Express 應用程式,保險作法是使用您想提供之目錄的絕對路徑: +不過,您提供給 `express.static` 函數的路徑,是相對於您從中啟動 `node` 程序的目錄。如果您是從另一個目錄執行 Express 應用程式,保險作法是使用您想提供之目錄的絕對路徑: 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 const path = require('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.html). + +### [Previous: Basic Routing ](/{{ page.lang }}/starter/basic-routing.html)    [Next: More examples ](/{{ page.lang }}/starter/examples.html) diff --git a/zh-tw/support/index.md b/zh-tw/support/index.md index b20df8c04c..710e57ef41 100644 --- a/zh-tw/support/index.md +++ b/zh-tw/support/index.md @@ -1,6 +1,7 @@ --- layout: page 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. menu: support lang: zh-tw --- @@ -11,17 +12,17 @@ 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**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | -| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | -| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | -| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | -| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | -| **v0.14.x**{: .eol } | 0.1.98 | December 2010 | December 2010 | +| Major Version | Minimum Node.js Version | Support Start Date | Support End Date | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------ | ---------------------------------------------------------- | +| [**v5.x**{: .supported }](/{{page.lang}}/5x/api.html){: .ignore-underline} | 18 | September 2024 | **ongoing**{: .supported } | +| [**v4.x**{: .supported }](/{{page.lang}}/4x/api.html){: .ignore-underline} | 0.10.0 | April 2014 | **ongoing**{: .supported } | +| [**v3.x**{: .eol }](/{{page.lang}}/3x/api.html){: .ignore-underline} | 0.8.0 | October 2012 | July 2015 | +| [**v2.x**{: .eol }](/2x/){: .ignore-underline} | 0.4.1 | March 2011 | July 2012 | +| **v1.x**{: .eol } | 0.2.0 | December 2010 | March 2011 | +| **v0.14.x**{: .eol } | 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: - - [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page) +- [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page)