快乐 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:3000http://127.0.0.1:3000 以查看响应。

有关 Express 框架的更多信息,你可以查看 Web Apps With Express 部分