node.js 创建服务器_Node.js HTTP软件包–创建HTTP服务器

node.js 创建服务器

An HTTP server caters to client requests and sends appropriate response. For example, JournalDev is also running on HTTP server. If you have landed here directly, I would suggest you to go through earlier posts about NodeJS IO Package and NodeJS Modules because we will use that knowledge here to create a simple HTTP server Node.js application.

HTTP服务器可满足客户端请求并发送适当的响应。 例如,JournalDev也正在HTTP服务器上运行。 如果您直接登陆这里,我建议您阅读有关NodeJS IO包NodeJS模块的早期文章,因为我们将在这里使用该知识来创建一个简单的HTTP服务器Node.js应用程序。

In this post, we are going to discuss about Node JS Platform “HTTP” module to develop HTTP server.

在本文中,我们将讨论有关Node JS Platform“ HTTP”模块以开发HTTP服务器的信息。

  • Introduction to Node JS HTTP Module

    Node JS HTTP模块简介
  • Node JS Simple HTTP Server

    节点JS简单HTTP服务器
  • How Node JS HTTP Server handles Client Requests

    Node JS HTTP Server如何处理客户端请求
  • Node JS HTTP Server Routings

    节点JS HTTP服务器路由

Node JS HTTP模块简介 (Introduction to Node JS HTTP Module)

Implementing an HTTP server is a tough task in Java or any other language frameworks, that’s why we have so many HTTP servers for different platforms such as Apache, Tomcat etc. However, we can develop simple HTTP server by using Node JS Platform very easily. We don’t need to write too much code to develop, up and running a basic HTTP Server.

在Java或任何其他语言框架中,实现HTTP服务器是一项艰巨的任务,这就是为什么我们拥有如此多的HTTP服务器(例如Apache,Tomcat等)的原因。但是,我们可以很容易地使用Node JS Platform开发简单的HTTP服务器。 我们不需要编写太多代码来开发,启动和运行基本的HTTP Server。

Like some Node modules for example “npm”, “fs” etc., Node JS “http” module is also part of basic Node JS Platform. We don’t need to do anything to setup Node JS HTTP module.

与某些Node模块(例如“ npm”,“ fs”等)一样,Node JS“ http”模块也是基本Node JS平台的一部分。 我们无需执行任何操作即可设置Node JS HTTP模块。

We just need to import “http” module and starting writing some code to develop HTTP server.

我们只需要导入“ http”模块并开始编写一些代码来开发HTTP服务器。

To import a “http” module:

导入“ http”模块:

var http = require("http");

This require() call imports Node JS HTTP module into cache. Once it’s done, then we can use NODE JS HTTP API to develop HTTP Server.

此require()调用将Node JS HTTP模块导入缓存。 完成后,我们可以使用NODE JS HTTP API开发HTTP Server。

节点JS简单HTTP服务器 (Node JS Simple HTTP Server)

Here we will learn how to create a simple HTTP server step by step.

在这里,我们将逐步学习如何创建一个简单的HTTP服务器。

  • Create a simple Node JS Project, refer Node JS Basic Examples With Node REPL (CLI) and Node IDE for detailed steps.
    node.js-http-server-project

    创建一个简单的Node JS项目,请参阅带有Node REPL(CLI)和Node IDE的Node JS基本示例以获取详细步骤。
  • Create package.json file with below contents.

    package.json

    {
      "name": "http-server",
      "version": "1.0.0",
      "description": "Simple HTTP Sever",
      "main": "http-server",
      "author": "JournalDEV",
      "engines":{
      	"node":"*"
      	}
    }

    使用以下内容创建package.json文件。

    package.json

  • Create a JavaScript file with the following content;

    http-server.js

    /**
     * JournalDEV  
     * Simple HTTP Server Example
     */
    var http = require("http");
    var httpserver = http.createServer();
    httpserver.listen(8001);

    With just few lines of above code, we are able to create a simple HTTP server. Below is the explanation of different parts of the code.

    • First line, require() call loads http module into cache to use Node JS HTTP API.
    • Second line, using HTTP API we are create a Server.
    • Third line, HTTP Server listen at port number: 8001

    Below image shows the project structure for now.

    http-server.js

    /**
     * JournalDEV  
     * Simple HTTP Server Example
     */
    var http = require("http");
    var httpserver = http.createServer();
    httpserver.listen(8001);

    只需上述几行代码,我们就可以创建一个简单的HTTP服务器。 下面是代码不同部分的说明。

    • 第一行,require()调用将http模块加载到缓存中以使用Node JS HTTP API。
    • 第二行,使用HTTP API创建服务器。
    • 第三行,HTTP Server侦听端口号:8001

    下图显示了目前的项目结构。

  • Open command prompt at ${ECLIPSE_WORKSPACE}/http-server project and run “node http-server.js” command.
    node.js-http-server

    If we observe here, command is waiting for client requests that mean our simple Node JS HTTP Server is up and running successfully.

    ${ECLIPSE_WORKSPACE}/http-server项目中打开命令提示符,然后运行“ node http-server.js ”命令。

    如果在这里观察到,命令正在等待客户端请求,这意味着我们简单的Node JS HTTP Server已启动并成功运行。

However, it cannot handle any requests with this simple HTTP Server. To handle or provide services to Client requests, we need to add some Routings. Please refer next section to extend this Basic HTTP Server program to handle client requests.

但是,它无法使用此简单的HTTP Server处理任何请求。 要处理或向客户请求提供服务,我们需要添加一些路由。 请参考下一部分以扩展此基本HTTP Server程序以处理客户端请求。

Node JS HTTP Server如何处理客户端请求 (How Node JS HTTP Server handle Client Requests)

Now we are going to add some code to receive and handle HTTP Client request.

现在,我们将添加一些代码来接收和处理HTTP客户端请求。

Open http-server.js file in Eclipse IDE and add a JavaScript function to represent request and response objects.

在Eclipse IDE中打开http-server.js文件,并添加一个JavaScript函数来表示请求和响应对象。

/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var httpserver = http.createServer(
			function(request,response){
				
			}
		);
httpserver.listen(8001);

Here anonymous Function takes request and response as parameters. When an HTTP Client sends a request at port number 8001, this anonymous function will receive that request.

在这里,匿名函数将请求和响应作为参数。 当HTTP客户端在端口号8001发送请求时,该匿名函数将接收该请求。

Let’s add some code to send response to the client requests.

让我们添加一些代码以发送对客户端请求的响应。

http-server.js

http-server.js

/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var httpserver = http.createServer(
		function(request,response){
			console.log("Received a Client Request");
			response.write("Hi, Dear JournalDEV User.")
		}
	);
httpserver.listen(8001);

Here when HTTP server receives a Client request, it prints a log message at server console and send a response message to the Client.
Just start the server again in the command prompt, if the earlier server is running then you need to close and start it again.

在这里,当HTTP服务器接收到客户端请求时,它将在服务器控制台上打印一条日志消息,并将响应消息发送到客户端。
只需在命令提示符下再次启动服务器,如果较早的服务器正在运行,则需要关闭并重新启动它。

Now open a browser and go to URL https://localhost:8001/ and you will get below response.

现在打开浏览器并转到URL https://localhost:8001/ ,您将获得以下响应。

At the same time, you will observe server logs in the command prompt as shown below.

同时,您将在命令提示符下观察服务器日志,如下所示。

节点JS HTTP服务器路由 (Node JS HTTP Server Routings)

So far we have developed a simple Node JS HTTP Server that just receives HTTP client request and send some response to the server. That means it handles only one kind of request: “/” when client hits this url: “https://localhost:8001”

到目前为止,我们已经开发了一个简单的Node JS HTTP Server,它仅接收HTTP客户端请求并将一些响应发送到服务器。 这意味着它仅处理一种请求:当客户端访问此URL时,“ /”:“ https:// localhost:8001”

It’s not enough to run some real-time applications with this basic HTTP Server. To handle different kinds of Client Requests, we should add “Routings” to our HTTP Server.

用此基本的HTTP Server运行某些实时应用程序还不够。 要处理各种类型的客户端请求,我们应该将“路由”添加到HTTP服务器。

Create a new JavaScript file “http-server-simple-routing.js” with following content.

使用以下内容创建一个新JavaScript文件“ http-server-simple-routing.js”。

http-server-simple-routing.js

http-server-simple-routing.js

/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var url = require('url');

var httpserver = http.createServer(
function(request,response){
	var clientRequestPath = url.parse(request.url).pathname;
switch(clientRequestPath){
	     case '/':
		console.log("Received a Client Request: Switch Case");
		response.write("Hi, Dear JournalDEV User: Switch Case.");
	       break;
	default:
	       console.log("Received a Client Request: Switch Default");
		response.write("Hi, Dear JournalDEV User:S witch Default.");
		break;
}
	response.end();
  }
);
httpserver.listen(8001);

Here we are using another Node JS Platform Default module: “url”. That means we don’t need to install it manually, it will come with base Node JS Platform installation.

在这里,我们使用另一个Node JS Platform Default模块:“ url”。 这意味着我们不需要手动安装它,它将随基本Node JS Platform安装一起提供。

Anonymous function with two parameters: request and response. request object contains a property: url, which contains client requested url.

具有两个参数的匿名函数:请求和响应。 request对象包含一个属性:url,其中包含客户端请求的url。

Then we are calling url.parse(request.url).pathname to get client request url. Suppose if Client sends a request by using https://localhost:8001/ url, then here url.parse(request.url).pathname returns “/”.

然后,我们调用url.parse(request.url).pathname来获取客户端请求url。 假设如果客户端通过使用https:// localhost:8001 / url发送请求,则url.parse(request.url).pathname返回“ /”。

We are saving the output of url.parse(request.url).pathname value into a local variable: clientRequestPath. We are using switch() block with one case and default blocks. If user sends request using “/”, then server executes switch:case block and send respective response to the client.

我们将url.parse(request.url).pathname值的输出保存到本地变量:clientRequestPath中。 我们正在将switch()块与一种情况和默认块一起使用。 如果用户使用“ /”发送请求,则服务器执行switch:case块并将相应的响应发送给客户端。

If user sends different request, then then server executes switch:default block and send respective response to the client.

如果用户发送了不同的请求,则服务器将执行switch:default块并将相应的响应发送给客户端。

We are closing the Response object using response.end() call.

我们正在使用response.end()调用关闭Response对象。

Open the Command Prompt/Terminal and start the node http server “http-server-simple-routing.js” and send two different requests from client browser and observe the response.

打开命令提示符/终端,然后启动节点http服务器“ http-server-simple-routing.js”,并从客户端浏览器发送两个不同的请求,并观察响应。

Case 1: Client sends “/” request using https://localhost:8001/ url and you will see below response in browser.

案例1 :客户端使用https:// localhost:8001 / url发送“ /”请求,您将在浏览器中看到以下响应。

Case 2: Client sends “/index.htm” request using https://localhost:8001/index.htm url and gets below response.

情况2 :客户端使用https:// localhost:8001 / index.htm url发送“ /index.htm”请求,并获得以下响应。

Below image shows the server logs in these cases.

下图显示了在这些情况下的服务器日志。

Here we have gone through some Routings to provide services to Client requests. We will see some more complex routings in next post “Node JS: Socket IO Module”.

在这里,我们已经完成了一些路由来为客户请求提供服务。 在下一篇文章“ Node JS:套接字IO模块”中,我们将看到一些更复杂的路由。

To create a simple HTTP Server with simple Routings, we have written some amount of code using Node JS HTTP package. If we use Node JS Express module, then we can create similar kind of Web Servers very easily. We will see those examples in “Node JS: Express Module” in coming posts.

为了创建具有简单路由的简单HTTP服务器,我们已经使用Node JS HTTP包编写了一些代码。 如果我们使用Node JS Express模块​​,那么我们可以非常轻松地创建类似类型的Web服务器。 我们将在后续文章中的“ Node JS:Express Module”中看到这些示例。

翻译自: https://www.journaldev.com/7936/node-js-http-package-creating-http-server

node.js 创建服务器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值