Hello world example示例

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.下面嵌入的是您可以创建的最简单的Express应用程序。这是一个单文件应用程序——如果你使用Express生成器,你就不会得到这样的应用程序,它为一个完整的应用程序创建了脚手架,其中包含许多JavaScript文件、Jade模板和用于各种目的的子目录。

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}`)
})

This app starts a server and listens on port 3000 for connections. 此应用程序启动服务器并在端口3000上侦听连接。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(/)或路由的请求,应用程序会以“Hello World!”作为响应。对于其他每条路径,它将返回404 Not Found

Running Locally本地运行

First create a directory named myapp, change to it and run npm init. 首先创建一个名为myapp的目录,切换到它并运行npm initThen, install express as a dependency, as per the installation guide.然后,按照安装指南将express作为依赖项安装。

In the myapp directory, create a file named app.js and copy the code from the example above.myapp目录中,创建一个名为app.js的文件,并复制上面示例中的代码。

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.req(请求)和res(响应)是Node提供的完全相同的对象,因此您可以调用req.pipe()req.on('data', callback)以及任何不涉及Express的操作。

Run the app with the following command:使用以下命令运行应用程序:

$ node app.js

Then, load http://localhost:3000/ in a browser to see the output.然后,在浏览器中加载http://localhost:3000/以查看输出。

Previous: Installing安装     Next: Express Generator生成器