你好,世界示例
Note
下面嵌入的基本上是你可以创建的最简单的 Express 应用。它是一个单文件应用——而不是你使用 Express generator 时得到的那种,会创建一个完整应用的框架,包含众多 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}`);});import express from '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}`);});import express, { type Express, type Request, type Response } from 'express';
const app: Express = express();const port = 3000;
app.get('/', (req: Request, res: Response) => { res.send('Hello World!');});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});这个应用启动一个服务器,并在端口3000监听连接。对于根URL(/)或 route 的请求,应用会响应“Hello World!”。对于其他路径,它将响应 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.
本地运行
🌐 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.
Caution
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.