NodeJS :追加のミドルウェアをExpressサーバーに追加する方法
8437 ワード
イントロ
それで、我々は我々の機械に乗っています.
私たちも学びました.
今、我々はどのように追加のミドルウェアを我々のExpressサーバーに追加する方法を学びたい.
からの我々の単純なサーバーを再利用してください
index.js
:touch index.js
const express = require('express');
const app = express();
const PORT = 8080;
app.get('/', (request, response) => {
response.send('Hello World');
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
注:これは私たちの出発点です、我々は1つの作業ルートを持っています.更新しました
req
to request
& res
to response
読みやすさを向上させる.追加ミドルウェア
ミドルウェアとは
既定のリクエスト応答サイクルの間に追加機能を追加する場合もあります.のは、現在の要求についての詳細な情報を取得したいとしましょう.
あなたは、このタスクを処理する簡単なミドルウェアを書くことができますし、Expressのアプリに追加します.
ミドルウェアを作る
logger.js
:touch logger.js
const logger = (req, res, next) => {
console.log(`Time: ${new Date()} - Method: ${req.method} - Path: ${req.originalUrl}`);
next();
};
module.exports = logger;
// import express (after npm install express)
const express = require('express');
// import the logger
const logger = require('./logger');
// create new express app and save it as app
const app = express();
// server configuration
const PORT = 8080;
// use the middleware
app.use(logger);
// create a route for the app
app.get('/', (req, res) => {
res.send('Hello World');
});
// make the server listen to requests
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
端末から実行する
node index.js
Server running at: http://localhost:8080/
Time: Tue Sep 03 2019 17:32:30 GMT+0200 (Central European Summer Time) - Method: GET - Path: /
ExpressとPostgreSQLのシリーズ
ここでは見つけることができます
更なる読書
質問
Reference
この問題について(NodeJS :追加のミドルウェアをExpressサーバーに追加する方法), 我々は、より多くの情報をここで見つけました https://dev.to/miku86/nodejs-how-to-add-additional-middleware-to-our-express-server-dcaテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol