快樂 Hello World
以下示例使用 Express 建立偵聽埠 3000 的 HTTP 伺服器,該伺服器以 Hello World!
響應。Express 是一種常用的 Web 框架,可用於建立 HTTP API。
首先,建立一個新資料夾,例如 myApp
。進入 myApp
並建立一個包含以下程式碼的新 JavaScript 檔案(例如,我們將其命名為 hello.js
)。然後從命令列使用 npm install --save express
安裝快速模組。*有關如何安裝軟體包的更多資訊,*請參閱此文件 。
// Import the top-level function of express
const express = require('express');
// Creates an Express application using the top-level function
const app = express();
// Define port number as 3000
const port = 3000;
// Routes HTTP GET requests to the specified path "/" with the specified callback function
app.get('/', function(request, response) {
response.send('Hello, World!');
});
// Make the app listen on port 3000
app.listen(port, function() {
console.log('Server listening on http://localhost:' + port);
});
從命令列執行以下命令:
node hello.js
開啟瀏覽器並導航到 http://localhost:3000
或 http://127.0.0.1:3000
以檢視響應。
有關 Express 框架的更多資訊,你可以檢視 Web Apps With Express 部分