node.js 创建服务器_如何使用HTTP模块在Node.js中创建Web服务器

node.js 创建服务器

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

作者选择了COVID-19救济基金来接受捐赠,这是Write for DOnations计划的一部分。

介绍 (Introduction)

When you view a webpage in your browser, you are making a request to another computer on the internet, which then provides you the webpage as a response. That computer you are talking to via the internet is a web server. A web server receives HTTP requests from a client, like your browser, and provides an HTTP response, like an HTML page or JSON from an API.

当您在浏览器中查看网页时,您正在向互联网上的另一台计算机发出请求,该计算机随后将网页作为响应。 您通过互联网与之交谈的那台计算机是Web服务器 。 Web服务器从客户端(例如您的浏览器)接收HTTP请求,并从API提供HTTP响应(例如HTML页面或JSON)

A lot of software is involved for a server to return a webpage. This software generally falls into two categories: frontend and backend. Front-end code is concerned with how the content is presented, such as the color of a navigation bar and the text styling. Back-end code is concerned with how data is exchanged, processed, and stored. Code that handles network requests from your browser or communicates with the database is primarily managed by back-end code.

服务器返回网页需要使用许多软件。 该软件通常分为两类:前端和后端。 前端代码与内容的显示方式有关,例如导航栏的颜色和文本样式。 后端代码与数据的交换,处理和存储方式有关。 处理来自浏览器的网络请求或与数据库通信的代码主要由后端代码管理。

Node.js allows developers to use JavaScript to write back-end code, even though traditionally it was used in the browser to write front-end code. Having both the frontend and backend together like this reduces the effort it takes to make a web server, which is a major reason why Node.js is a popular choice for writing back-end code.

Node.js允许开发人员使用JavaScript编写后端代码,尽管传统上它是在浏览器中用于编写前端代码的。 这样将前端和后端结合在一起可以减少制作Web服务器的工作量,这是Node.js成为编写后端代码的热门选择的主要原因。

In this tutorial, you will learn how to build web servers using the http module that’s included in Node.js. You will build web servers that can return JSON data, CSV files, and HTML web pages.

在本教程中,您将学习如何使用Node.js中包含的http模块构建Web服务器。 您将构建可返回JSON数据,CSV文件和HTML网页的Web服务器。

先决条件 (Prerequisites)

第1步-创建基本的HTTP服务器 (Step 1 — Creating a Basic HTTP Server)

Let’s start by creating a server that returns plain text to the user. This will cover the key concepts required to set up a server, which will provide the foundation necessary to return more complex data formats like JSON.

让我们从创建一个向用户返回纯文本的服务器开始。 这将涵盖设置服务器所需的关键概念,这将为返回更复杂的数据格式(如JSON)提供必要的基础。

First, we need to set up an accessible coding environment to do our exercises, as well as the others in the article. In the terminal, create a folder called first-servers:

首先,我们需要建立一个可访问的编码环境来进行练习,以及本文中的其他内容。 在终端中,创建一个名为first-servers的文件夹:

  • mkdir first-servers

    mkdir 第一台服务器

Then enter that folder:

然后输入该文件夹:

  • cd first-servers

    cd 第一服务器

Now, create the file that will house the code:

现在,创建将包含代码的文件:

  • touch hello.js

    触摸hello.js

Open the file in a text editor. We will use nano as it’s available in the terminal:

在文本编辑器中打开文件。 我们将使用nano因为它在终端中可用:

  • nano hello.js

    纳米hello.js

We start by loading the http module that’s standard with all Node.js installations. Add the following line to hello.js:

我们首先加载所有Node.js安装的标准http模块。 hello.js添加到hello.js

first-servers/hello.js
第一服务器/hello.js
const http = require("http");

The http module contains the function to create the server, which we will see later on. If you would like to learn more about modules in Node.js, check out our How To Create a Node.js Module article.

http模块包含用于创建服务器的功能,我们将在稍后看到。 如果您想了解有关Node.js中模块的更多信息,请查看我们的如何创建Node.js模块文章。

Our next step will be to define two constants, the host and port that our server will be bound to:

下一步将定义两个常量,服务器将绑定到的主机和端口:

first-servers/hello.js
第一服务器/hello.js
...
const host = 'localhost';
const port = 8000;

As mentioned before, web servers accept requests from browsers and other clients. We may interact with a web server by entering a domain name, which is translated to an IP address by a DNS server. An IP address is a unique sequence of numbers that identify a machine on a network, like the internet. For more information on domain name concepts, take a look at our An Introduction to DNS Terminology, Components, and Concepts article.

如前所述,Web服务器接受来自浏览器和其他客户端的请求。 我们可能会通过输入域名来与Web服务器进行交互,域名由DNS服务器转换为IP地址。 IP地址是唯一的数字序列,用于标识网络(如Internet)上的计算机。 有关域名概念的更多信息,请参阅我们的DNS术语,组件和概念简介文章。

The value localhost is a special private address that computers use to refer to themselves. It’s typically the equivalent of the internal IP address 127.0.0.1 and it’s only available to the local computer, not to any local networks we’ve joined or to the internet.

localhost是计算机用来引用自己的特殊专用地址。 它通常等效于内部IP地址127.0.0.1 ,并且仅适用于本地计算机,不适用于我们已加入的任何本地网络或Internet。

The port is a number that servers use as an endpoint or “door” to our IP address. In our example, we will use port 8000 for our web server. Ports 8080 and 8000 are typically used as default ports in development, and in most cases developers will use them rather than other ports for HTTP servers.

端口是服务器用作我们IP地址的端点或“门”的数字。 在我们的示例中,我们将为Web服务器使用端口8000 。 端口80808000通常在开发中用作默认端口,并且在大多数情况下,开发人员将使用它们而不是HTTP服务器使用其他端口。

When we bind our server to this host and port, we will be able to reach our server by visiting http://localhost:8000 in a local browser.

当我们将服务器绑定到该主机和端口时,我们可以通过在本地浏览器中访问http://localhost:8000来访问服务器。

Let’s add a special function, which in Node.js we call a request listener. This function is meant to handle an incoming HTTP request and return an HTTP response. This function must have two arguments, a request object and a response object. The request object captures all the data of the HTTP request that’s coming in. The response object is used to return HTTP responses for the server.

让我们添加一个特殊的函数,在Node.js中,我们将其称为请求侦听器 。 此函数用于处理传入的HTTP请求并返回HTTP响应。 该函数必须有两个参数,一个请求对象和一个响应对象。 请求对象捕获传入的HTTP请求的所有数据。响应对象用于返回服务器的HTTP响应。

We want our first server to return this message whenever someone accesses it: "My first server!".

我们希望我们的第一台服务器在有人访问它时返回此消息: "My first server!"

Let’s add that function next:

接下来添加该功能:

first-servers/hello.js
第一服务器/hello.js
...

const requestListener = function (req, res) {
    res.writeHead(200);
    res.end("My first server!");
};

The function would usually be named based on what it does. For example, if we created a request listener function to return a list of books, we would likely name it listBooks(). Since this one is a sample case, we will use the generic name requestListener.

该函数通常根据其功能进行命名。 例如,如果我们创建了一个请求侦听器函数以返回一本书列表,则可能将其命名为listBooks() 。 由于这是一个示例案例,因此我们将使用通用名称requestListener

All request listener functions in Node.js accept two arguments: req and res (we can name them differently if we want). The HTTP request the user sends is captured in a Request object, which corresponds to the first argument, req. The HTTP response that we return to the user is formed by interacting with the Response object in second argument, res.

Node.js中的所有请求侦听器函数都接受两个参数: reqres (如果需要,可以使用不同的名称)。 用户发送的HTTP请求被捕获在Request对象中,该对象对应于第一个参数req 。 我们返回给用户的HTTP响应是通过与第二个参数res的Response对象进行交互而形成的。

The first line res.writeHead(200); sets the HTTP status code of the response. HTTP status codes indicate how well an HTTP request was handled by the server. In this case, the status code 200 corresponds to "OK". If you are interested in learning about the various HTTP codes that your web servers can return with the meaning they signify, our guide on How To Troubleshoot Common HTTP Error Codes is a good place to start.

第一行res.writeHead(200); 设置响应的HTTP状态代码。 HTTP状态代码指示服务器处理HTTP请求的状态。 在这种情况下,状态代码200对应于"OK" 。 如果您有兴趣了解Web服务器可以返回的各种HTTP代码以及它们所表示的含义,那么有关如何解决常见HTTP错误代码的指南就是一个不错的起点。

The next line of the function, res.end("My first server!");, writes the HTTP response back to the client who requested it. This function returns any data the server has to return. In this case, it’s returning text data.

函数的下一行res.end("My first server!"); ,将HTTP响应写回到请求它的客户端。 此函数返回服务器必须返回的所有数据。 在这种情况下,它将返回文本数据。

Finally, we can now create our server and make use of our request listener:

最后,我们现在可以创建服务器并利用我们的请求侦听器:

first-servers/hello.js
第一服务器/hello.js
...

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

Save and exit nano by pressing CTRL+X.

通过按CTRL+X保存并退出nano

In the first line, we create a new server object via the http module’s createServer() function. This server accepts HTTP requests and passes them on to our requestListener() function.

在第一行中,我们通过http模块的createServer()函数创建一个新的server对象。 该服务器接受HTTP请求,并将其传递给我们的requestListener()函数。

After we create our server, we must bind it to a network address. We do that with the server.listen() method. It accepts three arguments: port, host, and a callback function that fires when the server begins to listen.

创建服务器后,必须将其绑定到网络地址。 我们使用server.listen()方法做到这一点。 它接受三个参数: porthost和一个在服务器开始侦听时触发的回调函数

All of these arguments are optional, but it is a good idea to explicitly state which port and host we want a web server to use. When deploying web servers to different environments, knowing the port and host it is running on is required to set up load balancing or a DNS alias.

所有这些参数都是可选的,但是最好明确声明要使用Web服务器的端口和主机。 将Web服务器部署到不同的环境时,需要知道正在运行的端口和主机来设置负载平衡或DNS别名。

The callback function logs a message to our console so we can know when the server began listening to connections.

回调函数会将消息记录到控制台,以便我们可以知道服务器何时开始侦听连接。

Note: Even though requestListener() does not use the req object, it must still be the first argument of the function.

注意:即使requestListener()不使用req对象,它仍必须是函数的第一个参数。

With less than fifteen lines of code, we now have a web server. Let’s see it in action and test it end-to-end by running the program:

现在,使用不到十五行的代码,我们有了一个Web服务器。 让我们看看它的运行情况,并通过运行该程序进行端到端测试:

  • node hello.js

    节点hello.js

In the console, we will see this output:

在控制台中,我们将看到以下输出:


   
   
Output
Server is running on http://localhost:8000

Notice that the prompt disappears. This is because a Node.js server is a long running process. It only exits if it encounters an error that causes it to crash and quit, or if we stop the Node.js process running the server.

请注意提示消失。 这是因为Node.js服务器是一个长期运行的过程。 仅当它遇到导致其崩溃并退出的错误时,或者如果我们停止运行服务器的Node.js进程,它才会退出。

In a separate terminal window, we’ll communicate with the server using cURL, a CLI tool to transfer data to and from a network. Enter the command to make an HTTP GET request to our running server:

在一个单独的终端窗口中,我们将使用cURL (一种CLI工具,用于在网络之间传输数据)与服务器进行通信。 输入命令向运行中的服务器发出HTTP GET请求:

  • curl http://localhost:8000

    卷曲http:// localhost:8000

When we press ENTER, our terminal will show the following output:

当我们按ENTER ,终端将显示以下输出:


   
   
Output
My first server!

We’ve now set up a server and got our first server response.

现在,我们已经设置了服务器,并得到了第一个服务器响应。

Let’s break down what happened when we tested our server. Using cURL, we sent a GET request to the server at http://localhost:8000. Our Node.js server listened to connections from that address. The server passed that request to the requestListener() function. The function returned text data with the status code 200. The server then sent that response back to cURL, which displayed the message in our terminal.

让我们分解一下测试服务器时发生的情况。 使用cURL,我们将GET请求发送到位于http://localhost:8000的服务器。 我们的Node.js服务器监听了来自该地址的连接。 服务器将该请求传递给requestListener()函数。 该函数返回状态数据为200文本数据。 然后,服务器将该响应发送回cURL,后者在我们的终端中显示该消息。

Before we continue, let’s exit our running server by pressing CTRL+C. This interrupts our server’s execution, bringing us back to the command line prompt.

在继续之前,让我们按CTRL+C退出运行的服务器。 这会中断服务器的执行,使我们回到命令行提示符。

In most web sites we visit or APIs we use, the server responses are seldom in plain text. We get HTML pages and JSON data as common response formats. In the next step, we will learn how to return HTTP responses in common data formats we encounter in the web.

在我们访问的大多数网站或使用的API中,服务器响应很少以纯文本形式出现。 我们将HTML页面和JSON数据作为常见的响应格式。 在下一步中,我们将学习如何以网络上常见的数据格式返回HTTP响应。

第2步-返回不同类型的内容 (Step 2 — Returning Different Types of Content)

The response we return from a web server can take a variety of formats. JSON and HTML were mentioned before, and we can also return other text formats like XML and CSV. Finally, web servers can return non-text data like PDFs, zipped files, audio, and video.

我们从Web服务器返回的响应可以采用多种格式。 前面提到了JSON和HTML,我们还可以返回其他文本格式,例如XML和CSV。 最后,Web服务器可以返回非文本数据,例如PDF,压缩文件,音频和视频。

In this article, in addition to the plain text we just returned, you’ll learn how to return the following types of data:

在本文中,除了我们刚刚返回的纯文本之外,您还将学习如何返回以下类型的数据:

  • JSON

    JSON格式
  • CSV

    CSV
  • HTML

    HTML

The three data types are all text-based, and are popular formats for delivering content on the web. Many server-side development languages and tools have support for returning these different data types. In the context of Node.js, we need to do two things:

这三种数据类型都是基于文本的,并且是用于在Web上传递内容的流行格式。 许多服务器端开发语言和工具都支持返回这些不同的数据类型。 在Node.js的上下文中,我们需要做两件事:

  1. Set the Content-Type header in our HTTP responses with the appropriate value.

    使用适当的值在我们的HTTP响应中设置Content-Type标头。

  2. Ensure that res.end() gets the data in the right format.

    确保res.end()以正确的格式获取数据。

Let’s see this in action with some examples. The code we will be writing in this section and later ones have many similarities to the code we wrote previously. Most changes exist within the requestListener() function. Let’s create files with this “template code” to make future sections easier to follow.

让我们来看一些示例。 我们将在本节中编写的代码,以后的代码与我们之前编写的代码有很多相似之处。 大多数更改存在于requestListener()函数中。 让我们使用此“模板代码”创建文件,以使以后的部分更容易理解。

Create a new file called html.js. This file will be used later to return HTML text in an HTTP response. We’ll put the template code here and copy it to the other servers that return various types.

创建一个名为html.js的新文件。 稍后将使用此文件在HTTP响应中返回HTML文本。 我们将模板代码放在此处,并将其复制到其他返回各种类型的服务器。

In the terminal, enter the following:

在终端中,输入以下内容:

  • touch html.js

    触摸html.js

Now open this file in a text editor:

现在,在文本编辑器中打开此文件:

  • nano html.js

    纳米html.js

Let’s copy the “template code.” Enter this in nano:

让我们复制“模板代码”。 在nano输入:

first-servers/html.js
第一服务器/html.js
const http = require("http");

const host = 'localhost';
const port = 8000;

const requestListener = function (req, res) {};

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

Save and exit html.js with CTRL+X, then return to the terminal.

使用CTRL+X保存并退出html.js ,然后返回到终端。

Now let’s copy this file into two new files. The first file will be to return CSV data in the HTTP response:

现在,让我们将该文件复制到两个新文件中。 第一个文件将在HTTP响应中返回CSV数据:

  • cp html.js csv.js

    cp html.js csv.js

The second file will return a JSON response in the server:

第二个文件将在服务器中返回JSON响应:

  • cp html.js json.js

    cp html.js json.js

The remaining files will be for later exercises:

其余文件将用于以后的练习:

  • cp html.js htmlFile.js

    cp html.js htmlFile.js
  • cp html.js routes.js

    cp html.jsroutes.js

We’re now set up to continue our exercises. Let’s begin with returning JSON.

现在,我们开始继续练习。 让我们从返回JSON开始。

提供JSON (Serving JSON)

JavaScript Object Notation, commonly referred to as JSON, is a text-based data exchange format. As its name suggests, it is derived from JavaScript objects, but it is language independent, meaning it can be used by any programming language that can parse its syntax.

JavaScript Object Notation (通常称为JSON)是一种基于文本的数据交换格式。 顾名思义,它是从JavaScript对象派生的,但是它与语言无关,这意味着它可以被任何能够解析其语法的编程语言使用。

JSON is commonly used by APIs to accept and return data. Its popularity is due to lower data transfer size than previous data exchange standards like XML, as well as the tooling that exists that allow programs to parse them without excessive effort. If you’d like to learn more about JSON, you can read our guide on How To Work with JSON in JavaScript.

API通常使用JSON来接收和返回数据。 它之所以受欢迎,是因为它的数据传输大小比以前的数据交换标准(例如XML)低,并且现有的工具可以使程序无需花费过多精力即可解析它们。 如果您想了解有关JSON的更多信息,可以阅读有关如何在JavaScript中使用JSON的指南。

Open the json.js file with nano:

使用nano打开json.js文件:

  • nano json.js

    纳米json.js

We want to return a JSON response. Let’s modify the requestListener() function to return the appropriate header all JSON responses have by changing the highlighted lines like so:

我们想返回一个JSON响应。 让我们通过更改突出显示的行来修改requestListener()函数,以返回所有JSON响应都具有的适当标头,如下所示:

first-servers/json.js
第一服务器/json.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
};
...

The res.setHeader() method adds an HTTP header to the response. HTTP headers are additional information that can be attached to a request or a response. The res.setHeader() method takes two arguments: the header’s name and its value.

res.setHeader()方法将HTTP标头添加到响应中。 HTTP标头是可以附加到请求或响应的其他信息。 res.setHeader()方法采用两个参数:标头的名称和其值。

The Content-Type header is used to indicate the format of the data, also known as media type, that’s being sent with the request or response. In this case our Content-Type is application/json.

Content-Type标头用于指示与请求或响应一起发送的数据格式,也称为媒体类型。 在这种情况下,我们的Content-Typeapplication/json

Now, let’s return JSON content to the user. Modify json.js so it looks like this:

现在,让我们将JSON内容返回给用户。 修改json.js使其如下所示:

first-servers/json.js
第一服务器/json.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    res.writeHead(200);
    res.end(`{"message": "This is a JSON response"}`);
};
...

Like before, we tell the user that their request was successful by returning a status code of 200. This time in the response.end() call, our string argument contains valid JSON.

像以前一样,我们通过返回状态码200告知用户其请求已成功。 这次在response.end()调用中,我们的字符串参数包含有效的JSON。

Save and exit json.js by pressing CTRL+X. Now, let’s run the server with the node command:

通过按CTRL+X保存并退出json.js 现在,让我们使用node命令运行服务器:

  • node json.js

    节点json.js

In another terminal, let’s reach the server by using cURL:

在另一个终端中,让我们使用cURL到达服务器:

  • curl http://localhost:8000

    卷曲http:// localhost:8000

As we press ENTER, we will see the following result:

当我们按ENTER ,我们将看到以下结果:


   
   
Output
{"message": "This is a JSON response"}

We now have successfully returned a JSON response, just like many of the popular APIs we create apps with. Be sure to exit the running server with CTRL+C so we can return to the standard terminal prompt. Next, let’s look at another popular format of returning data: CSV.

现在,我们已经成功返回了JSON响应,就像我们创建应用程序时使用的许多流行API一样。 确保使用CTRL+C退出正在运行的服务器,以便我们可以返回到标准终端提示符。 接下来,让我们看一下返回数据的另一种流行格式:CSV。

提供CSV (Serving CSV)

The Comma Separated Values (CSV) file format is a text standard that’s commonly used for providing tabular data. In most cases, each row is separated by a newline, and each item in the row is separated by a comma.

逗号分隔值 (CSV)文件格式是一种文本标准,通常用于提供表格数据。 在大多数情况下,每行用换行符分隔,而行中的每一项均用逗号分隔。

In our workspace, open the csv.js file with a text editor:

在我们的工作区中,使用文本编辑器打开csv.js文件:

  • nano csv.js

    纳米csv.js

Let’s add the following lines to our requestListener() function:

让我们requestListener()添加到我们的requestListener()函数中:

first-servers/csv.js
第一服务器/csv.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", "attachment;filename=oceanpals.csv");
};
...

This time, our Content-Type indicates that a CSV file is being returned as the value is text/csv. The second header we add is Content-Disposition. This header tells the browser how to display the data, particularly in the browser or as a separate file.

这次,我们的Content-Type表示正在返回CSV文件,因为其值为text/csv 。 我们添加的第二个标头是Content-Disposition 。 此标头告诉浏览器如何显示数据,尤其是在浏览器中或作为单独的文件显示。

When we return CSV responses, most modern browsers automatically download the file even if the Content-Disposition header is not set. However, when returning a CSV file we should still add this header as it allows us to set the name of the CSV file. In this case, we signal to the browser that this CSV file is an attachment and should be downloaded. We then tell the browser that the file’s name is oceanpals.csv.

当我们返回CSV响应时,即使未设置Content-Disposition标头,大多数现代浏览器也会自动下载文件。 但是,在返回CSV文件时,我们仍应添加此标头,因为它允许我们设置CSV文件的名称。 在这种情况下,我们会向浏览器发出此CSV文件为附件的信号,应下载该文件。 然后,我们告诉浏览器该文件的名称是oceanpals.csv

Let’s write the CSV data in the HTTP response:

让我们在HTTP响应中写入CSV数据:

first-servers/csv.js
第一服务器/csv.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", "attachment;filename=oceanpals.csv");
    res.writeHead(200);
    res.end(`id,name,email\n1,Sammy Shark,shark@ocean.com`);
};
...

Like before we return a 200/OK status with our response. This time, our call to res.end() has a string that’s a valid CSV. The comma separates the value in each column and the new line character (\n) separates the rows. We have two rows, one for the table header and one for the data.

就像之前,我们用响应返回200 / OK状态。 这次,我们对res.end()调用res.end()一个有效的CSV字符串。 逗号分隔每列中的值,换行符( \n )分隔行。 我们有两行,一行用于表头,另一行用于数据。

We’ll test this server in the browser. Save csv.js and exit the editor with CTRL+X.

我们将在浏览器中测试该服务器。 保存csv.js并使用CTRL+X退出编辑器。

Run the server with the Node.js command:

使用Node.js命令运行服务器:

  • node csv.js

    节点csv.js

In another Terminal, let’s reach the server by using cURL:

在另一个终端中,让我们使用cURL到达服务器:

  • curl http://localhost:8000

    卷曲http:// localhost:8000

The console will show this:

控制台将显示以下内容:


   
   
Output
id,name,email 1,Sammy Shark,shark@ocean.com

If we go to http://localhost:8000 in our browser, a CSV file will be downloaded. Its file name will be oceanpals.csv.

如果在浏览器中访问http://localhost:8000 ,将下载CSV文件。 它的文件名将是oceanpals.csv

Exit the running server with CTRL+C to return to the standard terminal prompt.

使用CTRL+C退出正在运行的服务器,以返回到标准终端提示符。

Having returned JSON and CSV, we’ve covered two cases that are popular for APIs. Let’s move on to how we return data for websites people view in a browser.

返回JSON和CSV后,我们已经介绍了两种API流行的情况。 让我们继续介绍如何为人们在浏览器中查看的网站返回数据。

提供HTML (Serving HTML)

HTML, HyperText Markup Language, is the most common format to use when we want users to interact with our server via a web browser. It was created to structure web content. Web browsers are built to display HTML content, as well as any styles we add with CSS, another front-end web technology that allows us to change the aesthetics of our websites.

HTML,即超文本标记语言 ,是当我们希望用户通过Web浏览器与我们的服务器进行交互时最常用的格式。 创建它是为了构造Web内容。 构造Web浏览器的目的是显示HTML内容以及CSS所添加的任何样式, CSS是另一种前端Web技术,它使我们能够改变网站的美感。

Let’s reopen html.js with our text editor:

让我们用文本编辑器重新打开html.js

  • nano html.js

    纳米html.js

Modify the requestListener() function to return the appropriate Content-Type header for an HTML response:

修改requestListener()函数以为HTML响应返回适当的Content-Type标头:

first-servers/html.js
第一服务器/html.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "text/html");
};
...

Now, let’s return HTML content to the user. Add the highlighted lines to html.js so it looks like this:

现在,让我们将HTML内容返回给用户。 将突出显示的行添加到html.js ,如下所示:

first-servers/html.js
第一服务器/html.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "text/html");
    res.writeHead(200);
    res.end(`<html><body><h1>This is HTML</h1></body></html>`);
};
...

We first add the HTTP status code. We then call response.end() with a string argument that contains valid HTML. When we access our server in the browser, we will see an HTML page with one header tag containing This is HTML.

我们首先添加HTTP状态代码。 然后,我们使用包含有效HTML的字符串参数调用response.end() 。 当我们在浏览器中访问服务器时,我们将看到一个HTML页面,其中包含一个包含This is HTML标头标记。

Let’s save and exit by pressing CTRL+X. Now, let’s run the server with the node command:

让我们按CTRL+X保存并退出。 现在,让我们使用node命令运行服务器:

  • node html.js

    节点html.js

We will see Server is running on http://localhost:8000 when our program has started.

程序启动后,我们将看到Server is running on http://localhost:8000

Now go into the browser and visit http://localhost:8000. Our page will look like this:

现在进入浏览器并访问http://localhost:8000 。 我们的页面将如下所示:

Let’s quit the running server with CTRL+C and return to the standard terminal prompt.

让我们使用CTRL+C退出正在运行的服务器,然后返回到标准终端提示符。

It’s common for HTML to be written in a file, separate from the server-side code like our Node.js programs. Next, let’s see how we can return HTML responses from files.

HTML通常写在一个文件中,与服务器端代码(如我们的Node.js程序)分开。 接下来,让我们看看如何从文件返回HTML响应。

步骤3 —从文件提供HTML页面 (Step 3 — Serving an HTML Page From a File)

We can serve HTML as strings in Node.js to the user, but it’s preferable that we load HTML files and serve their content. This way, as the HTML file grows we don’t have to maintain long strings in our Node.js code, keeping it more concise and allowing us to work on each aspect of our website independently. This “separation of concerns” is common in many web development setups, so it’s good to know how to load HTML files to support it in Node.js

我们可以将HTML作为Node.js中的字符串提供给用户,但是最好加载HTML文件并提供其内容。 这样,随着HTML文件的增长,我们不必在Node.js代码中维护长字符串,从而使其更加简洁并允许我们独立处理网站的各个方面。 这种“关注点分离”在许多Web开发设置中都很常见,因此很高兴知道如何在Node.js中加载HTML文件以支持它。

To serve HTML files, we load the HTML file with the fs module and use its data when writing our HTTP response.

为了提供HTML文件,我们使用fs模块加载HTML文件,并在编写HTTP响应时使用其数据。

First, we’ll create an HTML file that the web server will return. Create a new HTML file:

首先,我们将创建Web服务器将返回HTML文件。 创建一个新HTML文件:

  • touch index.html

    触摸index.html

Now open index.html in a text editor:

现在,在文本编辑器中打开index.html

  • nano index.html

    纳米index.html

Our web page will be minimal. It will have an orange background and will display some greeting text in the center. Add this code to the file:

我们的网页将很小。 它将具有橙色背景,并在中间显示一些问候语。 将此代码添加到文件中:

first-servers/index.html
first-servers / index.html
<!DOCTYPE html>

<head>
    <title>My Website</title>
    <style>
        *,
        html {
            margin: 0;
            padding: 0;
            border: 0;
        }

        html {
            width: 100%;
            height: 100%;
        }

        body {
            width: 100%;
            height: 100%;
            position: relative;
            background-color: rgb(236, 152, 42);
        }

        .center {
            width: 100%;
            height: 50%;
            margin: 0;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-family: "Trebuchet MS", Helvetica, sans-serif;
            text-align: center;
        }

        h1 {
            font-size: 144px;
        }

        p {
            font-size: 64px;
        }
    </style>
</head>

<body>
    <div class="center">
        <h1>Hello Again!</h1>
        <p>This is served from a file</p>
    </div>
</body>

</html>

This single webpage shows two lines of text: Hello Again! and This is served from a file. The lines appear in the center of the page, one above each other. The first line of text is displayed in a heading, meaning it would be large. The second line of text will appear slightly smaller. All the text will appear white and the webpage has an orange background.

这个网页显示两行文字: Hello Again! 并且This is served from a file 。 这些线出现在页面的中央,彼此之间。 文本的第一行显示在标题中,这意味着它会很大。 文本的第二行将显得稍小。 所有文本将显示为白色,网页背景为橙色。

While it’s not the scope of this article or series, if you are interested in learning more about HTML, CSS, and other front-end web technologies, you can take a look at Mozilla’s Getting Started with the Web guide.

虽然这不在本文或系列文章的讨论范围之内,但是如果您想了解有关HTML,CSS和其他前端Web技术的更多信息,则可以阅读Mozilla的Web入门指南。

That’s all we need for the HTML, so save and exit the file with CTRL+X. We can now move on to the server code.

这就是HTML所需的全部内容,因此请使用CTRL+X保存并退出文件。 现在,我们可以继续进行服务器代码。

For this exercise, we’ll work on htmlFile.js. Open it with the text editor:

在本练习中,我们将使用htmlFile.js 。 用文本编辑器打开它:

  • nano htmlFile.js

    纳米htmlFile.js

As we have to read a file, let’s begin by importing the fs module:

由于必须读取文件,因此我们首先导入fs模块:

first-servers/htmlFile.js
第一台服务器/htmlFile.js
const http = require("http");
const fs = require('fs').promises;
...

This module contains a readFile() function that we’ll use to load the HTML file in place. We import the promise variant in keeping with modern JavaScript best practices. We use promises as its syntactically more succinct than callbacks, which we would have to use if we assigned fs to just require('fs'). To learn more about asynchronous programming best practices, you can read our How To Write Asynchronous Code in Node.js guide.

该模块包含一个readFile()函数,我们将使用该函数将HTML文件加载到位。 我们导入了promise变量,以符合现代JavaScript最佳实践。 我们在语法上使用promise作为其语法要比回调更简洁,如果将fs分配给require('fs') 。 要了解有关异步编程最佳实践的更多信息,您可以阅读我们的《 如何在Node.js中编写异步代码》指南

We want our HTML file to be read when a user requests our system. Let’s begin by modifying requestListener() to read the file:

我们希望在用户请求我们的系统时读取HTML文件。 让我们首先修改requestListener()来读取文件:

first-servers/htmlFile.js
第一服务器/htmlFile.js
...
const requestListener = function (req, res) {
    fs.readFile(__dirname + "/index.html")
};
...

We use the fs.readFile() method to load the file. Its argument has __dirname + "/index.html". The special variable __dirname has the absolute path of where the Node.js code is being run. We then append /index.html so we can load the HTML file we created earlier.

我们使用fs.readFile()方法加载文件。 其参数具有__dirname + "/index.html" 。 特殊变量__dirname具有运行Node.js代码的绝对路径。 然后,我们附加/index.html以便可以加载之前创建HTML文件。

Now let’s return the HTML page once it’s loaded:

现在,让我们在加载后返回HTML页面:

first-servers/htmlFile.js
第一服务器/htmlFile.js
...
const requestListener = function (req, res) {
    fs.readFile(__dirname + "/index.html")
        .then(contents => {
            res.setHeader("Content-Type", "text/html");
            res.writeHead(200);
            res.end(contents);
        })
};
...

If the fs.readFile() promise successfully resolves, it will return its data. We use the then() method to handle this case. The contents parameter contains the HTML file’s data.

如果fs.readFile()承诺成功解析,它将返回其数据。 我们使用then()方法处理这种情况。 contents参数包含HTML文件的数据。

We first set the Content-Type header to text/html to tell the client that we are returning HTML data. We then write the status code to indicate the request was successful. We finally send the client the HTML page we loaded, with the data in the contents variable.

我们首先将Content-Type标头设置为text/html以告知客户端我们正在返回HTML数据。 然后,我们编写状态代码以指示请求成功。 最后,我们向客户端发送我们加载HTML页面,其中包含contents变量中的数据。

The fs.readFile() method can fail at times, so we should handle this case when we get an error. Add this to the requestListener() function:

fs.readFile()方法有时可能会失败,因此当遇到错误时,我们应该处理这种情况。 将此添加到requestListener()函数中:

first-servers/htmlFile.js
第一服务器/htmlFile.js
...
const requestListener = function (req, res) {
    fs.readFile(__dirname + "/index.html")
        .then(contents => {
            res.setHeader("Content-Type", "text/html");
            res.writeHead(200);
            res.end(contents);
        })
        .catch(err => {
            res.writeHead(500);
            res.end(err);
            return;
        });
};
...

Save the file and exit nano with CTRL+X.

保存文件并使用CTRL+X退出nano

When a promise encounters an error, it is rejected. We handle that case with the catch() method. It accepts the error that fs.readFile() returns, sets the status code to 500 signifying that an internal error was encountered, and returns the error to the user.

当一个承诺遇到错误时,它将被拒绝。 我们用catch()方法处理这种情况。 它接受fs.readFile()返回的错误,将状态代码设置为500表示遇到内部错误,然后将错误返回给用户。

Run our server with the node command:

使用node命令运行我们的服务器:

  • node htmlFile.js

    节点htmlFile.js

In the web browser, visit http://localhost:8000. You will see this page:

在Web浏览器中,访问http://localhost:8000 。 您将看到此页面:

You have now returned an HTML page from the server to the user. You can quit the running server with CTRL+C. You will see the terminal prompt return when you do.

现在,您已经从服务器返回了HTML页面给用户。 您可以使用CTRL+C退出正在运行的服务器。 这样做时,您将看到终端提示返回。

When writing code like this in production, you may not want to load an HTML page every time you get an HTTP request. While this HTML page is roughly 800 bytes in size, more complex websites can be megabytes in size. Large files can take a while to load. If your site is expecting a lot of traffic, it may be best to load HTML files at startup and save their contents. After they are loaded, you can set up the server and make it listen to requests on an address.

在生产环境中编写此类代码时,您可能不想每次收到HTTP请求时都加载HTML页面。 尽管此HTML页面的大小约为800字节,但更复杂的网站的大小可能为兆字节。 大文件可能需要一段时间才能加载。 如果您的网站流量很大,最好在启动时加载HTML文件并保存其内容。 加载它们之后,您可以设置服务器并使其监听地址上的请求。

To demonstrate this method, let’s see how we can rework our server to be more efficient and scalable.

为了演示这种方法,让我们看看如何重新设计服务器以提高效率和可伸缩性。

有效地提供HTML (Serving HTML Efficiently)

Instead of loading the HTML for every request, in this step we will load it once at the beginning. The request will return the data we loaded at startup.

在此步骤中,我们不会在每个步骤中都加载HTML,而是在开始时加载一次。 该请求将返回我们在启动时加载的数据。

In the terminal, re-open the Node.js script with a text editor:

在终端中,使用文本编辑器重新打开Node.js脚本:

  • nano htmlFile.js

    纳米htmlFile.js

Let’s begin by adding a new variable before we create the requestListener() function:

让我们先创建一个新变量,然后再创建requestListener()函数:

first-servers/htmlFile.js
第一台服务器/htmlFile.js
...
let indexFile;

const requestListener = function (req, res) {
...

When we run this program, this variable will hold the HTML file’s contents.

当我们运行该程序时,此变量将保存HTML文件的内容。

Now, let’s readjust the requestListener() function. Instead of loading the file, it will now return the contents of indexFile:

现在,让我们重新调整requestListener()函数。 现在,它不再返回文件,而是返回indexFile的内容:

first-servers/htmlFile.js
第一台服务器/htmlFile.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "text/html");
    res.writeHead(200);
    res.end(indexFile);
};
...

Next, we shift the file reading logic from the requestListener() function to our server startup. Make the following changes as we create the server:

接下来,我们将文件读取逻辑从requestListener()函数转移到服务器启动。 在创建服务器时进行以下更改:

first-servers/htmlFile.js
第一台服务器/htmlFile.js
...

const server = http.createServer(requestListener);

fs.readFile(__dirname + "/index.html")
    .then(contents => {
        indexFile = contents;
        server.listen(port, host, () => {
            console.log(`Server is running on http://${host}:${port}`);
        });
    })
    .catch(err => {
        console.error(`Could not read index.html file: ${err}`);
        process.exit(1);
    });

Save the file and exit nano with CTRL+X.

保存文件并使用CTRL+X退出nano

The code that reads the file is similar to what we wrote in our first attempt. However, when we successfully read the file we now save the contents to our global indexFile variable. We then start the server with the listen() method. The key thing is that the file is loaded before the server is run. This way, the requestListener() function will be sure to return an HTML page, as indexFile is no longer an empty variable.

读取文件的代码类似于我们第一次尝试编写的代码。 但是,当我们成功读取文件时,现在将内容保存到全局indexFile变量中。 然后,我们使用listen()方法启动服务器。 关键是要在服务器运行之前加载文件。 这样,由于indexFile不再是一个空变量,因此requestListener()函数将确保返回HTML页面。

Our error handler has changed as well. If the file can’t be loaded, we capture the error and print it to our console. We then exit the Node.js program with the exit() function without starting the server. This way we can see why the file reading failed, address the problem, and then start the server again.

我们的错误处理程序也已更改。 如果无法加载文件,我们将捕获错误并将其打印到控制台。 然后,我们使用exit()函数退出Node.js程序,而无需启动服务器。 通过这种方式,我们可以了解文件读取失败的原因,解决该问题,然后再次启动服务器。

We’ve now created different web servers that return various types of data to a user. So far, we have not used any request data to determine what should be returned. We’ll need to use request data when setting up different routes or paths in a Node.js server, so next let’s see how they work together.

现在,我们创建了不同的Web服务器,这些服务器将各种类型的数据返回给用户。 到目前为止,我们尚未使用任何请求数据来确定应返回的内容。 在Node.js服务器中设置不同的路由或路径时,我们将需要使用请求数据,因此接下来让我们看看它们如何协同工作。

第4步-使用HTTP请求对象管理路由 (Step 4 — Managing Routes Using an HTTP Request Object)

Most websites we visit or APIs we use usually have more than one endpoint so we can access various resources. A good example would be a book management system, one that might be used in a library. It would not only need to manage book data, but it would also manage author data for cataloguing and searching convenience.

我们访问的大多数网站或我们使用的API通常都具有多个端点,因此我们可以访问各种资源。 图书管理系统就是一个很好的例子,可以在图书馆中使用。 它不仅需要管理书籍数据,而且还需要管理作者数据以进行分类和搜索。

Even though the data for books and authors are related, they are two different objects. In these cases, software developers usually code each object on different endpoints as a way to indicate to the API user what kind of data they are interacting with.

即使书籍和作者的数据相关,它们也是两个不同的对象。 在这些情况下,软件开发人员通常会将每个对象编码在不同的端点上,以向API用户指示与之交互的数据类型。

Let’s create a new server for a small library, which will return two different types of data. If the user goes to our server’s address at /books, they will receive a list of books in JSON. If they go to /authors, they will receive a list of author information in JSON.

让我们为一个小型库创建一个新服务器,该服务器将返回两种不同类型的数据。 如果用户通过/books转到我们服务器的地址,他们将收到JSON形式的书籍列表。 如果他们转到/authors ,他们将收到JSON中的作者信息列表。

So far, we have been returning the same response to every request we get. Let’s illustrate this quickly.

到目前为止,我们对收到的每个请求都返回相同的响应。 让我们快速说明一下。

Re-run our JSON response example:

重新运行我们的JSON响应示例:

  • node json.js

    节点json.js

In another terminal, let’s do a cURL request like before:

在另一个终端中,让我们像之前一样进行cURL请求:

  • curl http://localhost:8000

    卷曲http:// localhost:8000

You will see:

你会看见:


   
   
Output
{"message": "This is a JSON response"}

Now let’s try another curl command:

现在让我们尝试另一个curl命令:

  • curl http://localhost:8000/todos

    卷曲http:// localhost:8000 / todos

After pressing Enter, you will see the same result:

Enter ,您将看到相同的结果:


   
   
Output
{"message": "This is a JSON response"}

We have not built any special logic in our requestListener() function to handle a request whose URL contains /todos, so Node.js returns the same JSON message by default.

我们没有在requestListener()函数中构建任何特殊逻辑来处理URL包含/todos的请求,因此Node.js默认情况下返回相同的JSON消息。

As we want to build a miniature library management server, we’ll now separate the kind of data that’s returned based on the endpoint the user accesses.

当我们要构建一个微型库管理服务器时,我们现在将根据用户访问的端点来分离返回的数据类型。

First, exit the running server with CTRL+C.

首先,使用CTRL+C退出正在运行的服务器。

Now open routes.js in your text editor:

现在,在文本编辑器中打开routes.js

  • nano routes.js

    纳米routes.js

Let’s begin by storing our JSON data in variables before the requestListener() function:

首先,将JSON数据存储在requestListener()函数之前的变量中:

first-servers/routes.js
第一服务器/routes.js
...
const books = JSON.stringify([
    { title: "The Alchemist", author: "Paulo Coelho", year: 1988 },
    { title: "The Prophet", author: "Kahlil Gibran", year: 1923 }
]);

const authors = JSON.stringify([
    { name: "Paulo Coelho", countryOfBirth: "Brazil", yearOfBirth: 1947 },
    { name: "Kahlil Gibran", countryOfBirth: "Lebanon", yearOfBirth: 1883 }
]);
...

The books variable is a string that contains JSON for an array of book objects. Each book has a title or name, an author, and the year it was published.

books变量是一个字符串,其中包含用于book对象数组的JSON。 每本书都有标题或名称,作者以及出版年份。

The authors variable is a string that contains the JSON for an array of author objects. Each author has a name, a country of birth, and their year of birth.

authors变量是一个字符串,其中包含作者对象数组的JSON。 每个作者都有一个姓名,出生国家和出生年份。

Now that we have the data our responses will return, let’s start modifying the requestListener() function to return them to the correct routes.

现在我们有了响应将返回的数据,让我们开始修改requestListener()函数以将它们返回到正确的路由。

First, we’ll ensure that every response from our server has the correct Content-Type header:

首先,我们将确保来自服务器的每个响应都具有正确的Content-Type标头:

first-servers/routes.js
第一服务器/routes.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
}
...

Now, we want to return the right JSON depending on the URL path the user visits. Let’s create a switch statement on the request’s URL:

现在,我们要根据用户访问的URL路径返回正确的JSON。 让我们在请求的URL上创建一个switch语句

first-servers/routes.js
第一服务器/routes.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    switch (req.url) {}
}
...

To get the URL path from a request object, we need to access its url property. We can now add cases to the switch statement to return the appropriate JSON.

要从请求对象获取URL路径,我们需要访问其url属性。 现在,我们可以将个案添加到switch语句中以返回适当的JSON。

JavaScript’s switch statement provides a way to control what code is run depending on the value of an object or JavaScript expression (for example, the result of mathematical operations). If you need a lesson or reminder on how to use them, take a look at our guide on How To Use the Switch Statement in JavaScript.

JavaScript的switch语句提供了一种方法来控制根据对象或JavaScript表达式的值(例如,数学运算的结果)运行哪些代码。 如果您需要有关如何使用它们的课程或提醒,请查看我们的有关如何在JavaScript中使用Switch语句的指南。

Let’s continue by adding a case for when the user wants to get our list of books:

让我们继续添加一个case ,说明用户何时想要获取我们的图书清单:

first-servers/routes.js
第一服务器/routes.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    switch (req.url) {
        case "/books":
            res.writeHead(200);
            res.end(books);
            break
    }
}
...

We set our status code to 200 to indicate the request is fine and return the JSON containing the list of our books. Now let’s add another case for our authors:

我们将状态代码设置为200以指示请求正常,然后返回包含我们的图书清单的JSON。 现在让我们为作者添加另一个case

first-servers/routes.js
第一服务器/routes.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    switch (req.url) {
        case "/books":
            res.writeHead(200);
            res.end(books);
            break
        case "/authors":
            res.writeHead(200);
            res.end(authors);
            break
    }
}
...

Like before, the status code will be 200 as the request is fine. This time we return the JSON containing the list of our authors.

与之前一样,请求的状态码为200 。 这次,我们返回包含作者列表的JSON。

We want to return an error if the user tries to go to any other path. Let’s add the default case to do this:

如果用户尝试转到任何其他路径,我们想返回一个错误。 让我们添加默认大小写来执行此操作:

routes.js
routes.js
...
const requestListener = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    switch (req.url) {
        case "/books":
            res.writeHead(200);
            res.end(books);
            break
        case "/authors":
            res.writeHead(200);
            res.end(authors);
            break
        default:
            res.writeHead(404);
            res.end(JSON.stringify({error:"Resource not found"}));
    }
}
...

We use the default keyword in a switch statement to capture all other scenarios not captured by our previous cases. We set the status code to 404 to indicate that the URL they were looking for was not found. We then set a JSON object that contains an error message.

我们在switch语句中使用default关键字来捕获以前案例未捕获的所有其他方案。 我们将状态代码设置为404以指示未找到他们要查找的URL。 然后,我们设置一个包含错误消息的JSON对象。

Let’s test our server to see if it behaves as we expect. In another terminal, let’s first run a command to see if we get back our list of books:

让我们测试我们的服务器,看看它是否表现出预期的效果。 在另一个终端中,让我们首先运行一个命令,看看是否可以获取图书清单:

  • curl http://localhost:8000/books

    卷曲http:// localhost:8000 / books

Press Enter to see the following output:

Enter以查看以下输出:


   
   
Output
[{"title":"The Alchemist","author":"Paulo Coelho","year":1988},{"title":"The Prophet","author":"Kahlil Gibran","year":1923}]

So far so good. Let’s try the same for /authors. Type the following command in the terminal:

到目前为止,一切都很好。 让我们为/authors尝试相同的方法。 在终端中键入以下命令:

  • curl http://localhost:8000/authors

    卷曲http:// localhost:8000 / authors

You will see the following output when the command is complete:

命令完成后,您将看到以下输出:


   
   
Output
[{"name":"Paulo Coelho","countryOfBirth":"Brazil","yearOfBirth":1947},{"name":"Kahlil Gibran","countryOfBirth":"Lebanon","yearOfBirth":1883}]

Last, let’s try an erroneous URL to ensure that requestListener() returns the error response:

最后,让我们尝试一个错误的URL,以确保requestListener()返回错误响应:

  • curl http://localhost:8000/notreal

    卷曲http:// localhost:8000 / notreal

Entering that command will display this message:

输入该命令将显示以下消息:


   
   
Output
{"error":"Resource not found"}

You can exit the running server with CTRL+C.

您可以使用CTRL+C退出正在运行的服务器。

We’ve now created different avenues for users to get different data. We also added a default response that returns an HTTP error if the user enters a URL that we don’t support.

现在,我们为用户创建了不同的途径来获取不同的数据。 我们还添加了一个默认响应,如果用户输入了我们不支持的URL,它将返回一个HTTP错误。

结论 (Conclusion)

In this tutorial, you’ve made a series of Node.js HTTP servers. You first returned a basic textual response. You then went on to return various types of data from our server: JSON, CSV, and HTML. From there you were able to combine file loading with HTTP responses to return an HTML page from the server to the user, and to create an API that used information about the user’s request to determine what data should be sent in its response.

在本教程中,您已经制作了一系列Node.js HTTP服务器。 您首先返回了基本的文字回复。 然后,您继续从我们的服务器返回各种类型的数据:JSON,CSV和HTML。 从那里,您可以将文件加载与HTTP响应相结合,以将HTML页面从服务器返回给用户,并创建一个API,该API使用有关用户请求的信息来确定应在响应中发送哪些数据。

You’re now equipped to create web servers that can handle a variety of requests and responses. With this knowledge, you can make a server that returns many HTML pages to the user at different endpoints. You could also create your own API.

现在,您可以创建可处理各种请求和响应的Web服务器。 有了这些知识,您就可以使服务器在不同的端点向用户返回许多HTML页面。 您也可以创建自己的API。

To learn about more HTTP web servers in Node.js, you can read the Node.js documentation on the http module. If you’d like to continue learning Node.js, you can return to the How To Code in Node.js series page.

要了解Node.js中更多的HTTP Web服务器,您可以阅读http模块上的Node.js文档 。 如果您想继续学习Node.js,可以返回“ 如何在Node.js中进行编码”系列页面

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-a-web-server-in-node-js-with-the-http-module

node.js 创建服务器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值