Hello World 示例

¥Hello world example

下面嵌入的本质上是你可以创建的最简单的 Express 应用。它是一个单文件应用 - 不是你使用 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, which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.


const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

此应用启动一个服务器并在端口 3000 上监听连接。应用以 “Hello World!” 响应对根 URL (/) 或路由的请求。对于所有其他路径,它将响应 404 Not Found。

¥This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

上面的例子实际上是一个工作服务器:继续并单击显示的 URL。你会收到响应,页面上会显示实时日志,并且你所做的任何更改都会实时反映。这由 RunKit 提供支持,它提供了一个交互式 JavaScript 在线运行,连接到在你的 Web 浏览器中运行的完整 Node 环境。以下是在本地计算机上运行相同应用的说明。

¥The example above is actually a working server: Go ahead and click on the URL shown. You’ll get a response, with real-time logs on the page, and any changes you make will be reflected in real time. This is powered by RunKit, which provides an interactive JavaScript playground connected to a complete Node environment that runs in your web browser. Below are instructions for running the same app on your local machine.

RunKit 是一个第三方服务,不隶属于 Express 项目。

¥RunKit is a third-party service not affiliated with the Express project.

本地运行

¥Running Locally

首先创建一个名为 myapp 的目录,切换到它并运行 npm init。然后,根据 安装指南 安装 express 作为依赖。

¥First create a directory named myapp, change to it and run npm init. Then, install express as a dependency, as per the installation guide.

myapp 目录中,创建一个名为 app.js 的文件并从上面的示例中复制代码。

¥In the myapp directory, create a file named app.js and copy the code from the example above.

req(请求)和 res(响应)与 Node 提供的对象完全相同,因此你可以调用 req.pipe()req.on('data', callback) 以及无需 Express 参与的任何其他操作。

¥The req (request) and res (response) are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback), and anything else you would do without Express involved.

使用以下命令运行应用:

¥Run the app with the following command:

$ node app.js

然后,在浏览器中加载 http://localhost:3000/ 以查看输出。

¥Then, load http://localhost:3000/ in a browser to see the output.