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 generator时得到的,Express generator为一个完整的应用程序创建了框架,其中包含大量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 at http://localhost:${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.对于根URL(/)或路由的请求,应用程序会以“Hello World!”响应。For every other path, it will respond with a 404 Not Found.对于每一个其他路径,它将以404 Not Found响应。

The example above is actually a working server: Go ahead and click on the URL shown.上面的示例实际上是一个工作服务器:继续并单击所示的URL。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.这是由RunKit提供的,它提供了一个交互式JavaScript游乐场,连接到在web浏览器中运行的完整节点环境。Below are instructions for running the same app on your local machine.以下是在本地计算机上运行相同应用程序的说明。

RunKit is a third-party service not affiliated with the Express project.RunKit是与Express项目无关的第三方服务。

Running Locally本地运行

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

In the myapp directory, create a file named app.js and copy in 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(响应)是节点提供的完全相同的对象,因此您可以调用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 GeneratorExpress生成器