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 ModuleNode JS HTTP模块简介
  • Node JS Simple HTTP Server节点JS简单HTTP服务器
  • How Node JS HTTP Server handles Client RequestsNode 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项目,请参阅带有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.

    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 创建服务器

node.js 创建服务器_Node.js HTTP软件包–创建HTTP服务器相关推荐

  1. egret可以用php做后端吗,Egret引擎开发指南之创建项目_node.js

    Egret提供非常方便的创建工具,我们把创建后的文件总和称之为项目.在后面的操作中,我们对创建的项目进行操作,具体创建步骤如下: 需要注意的是Egret支持Windows和Mac OS X 两个平台. ...

  2. js ws 状态_node.js中ws模块创建服务端和客户端,网页WebSocket客户端

    首先下载websocket模块,命令行输入 npm install ws 1.node.js中ws模块创建服务端 // 加载node上websocket模块 ws; var ws = require( ...

  3. node.js fs模块_Node.js中的fs模块简介

    node.js fs模块 fs, short for File System, is one of the most basic and useful modules in Node. In this ...

  4. node 加密解密模块_NODE.JS加密模块CRYPTO常用方法介绍

    使用require('crypto')调用加密模块. 加密模块需要底层系统提供OpenSSL的支持.它提供了一种安全凭证的封装方式,可以用于HTTPS安全网络以及普通HTTP连接. 该模块还提供了一套 ...

  5. js 打印数组_Node.js系列二 - Node基础知识

    一. Node执行代码 1.1. JavaScript文件执行 如果我们编写一个js文件,里面存放JavaScript代码,如何来执行它呢? // 1.直接打印一段文字 console.log(&qu ...

  6. kewail node 短信_Node.js代码示例_Node.js短信短信 | 微米-中国领先的短信彩信接口平台服务商...

    Node.js短信接口一代码示例 请求 var http = require('http'); var querystring = require('querystring'); var postDa ...

  7. node mysql 模块 封装_node.js基于工厂方法的mysql模块封装

    有空写完再补说明,手上的事情比较多,以后边做边完善接口. app.js var config = require('./config'); function Query(strquery,option ...

  8. js 拉勾网效果_Node.js 中实践基于 Redis 的分布式锁实现

    在一些分布式环境下.多线程并发编程中,如果对同一资源进行读写操作,避免不了的一个就是资源竞争问题,通过引入分布式锁这一概念,可以解决数据一致性问题. 作者简介:五月君,Nodejs Developer ...

  9. nodejs没有net模块_Node.js实战16:用http模块创建web服务器

    Nodejs的http模块,是基于net.server,经过c++二次封装,也是nodejs的核心模块. 功能比net.server更强,可解析和操作更多细节内容,如值.content-length. ...

最新文章

  1. ThinkPHP 详细介绍
  2. Python list 数据类型:列表
  3. 高情商女神是怎样炼成的?直播EMUI9.0制胜法宝“陪伴实测”
  4. BZOJ-1192-鬼谷子的钱袋
  5. Java--Servlet,@ServletSecurity,role,username,password
  6. 35个Java代码性能优化总结
  7. cdev_init() / cedev_alloc() / cdev_del()
  8. 2014-07-24 .NET实现微信公众号的消息回复与自定义菜单
  9. 在 Vue 中是使用插槽
  10. 避免过度设计,一对多时才用父类、接口
  11. 5月份鸿蒙升级时间,事关所有华为手机用户,鸿蒙正式升级时间终于确定
  12. hamcrest的jar包_重新设计Hamcrest
  13. NUC970裸机IIC驱动
  14. 实验三+161+张丽霞
  15. 惠普打印机只打印一半_打印机打出来的字只有一半是什么原因
  16. OBS Studio显示器黑屏
  17. 实验室常见的PFA制品有哪些?这些特氟龙PFA产品你认得全吗?
  18. css加空格的方法,css如何加空格
  19. 山下英子与家政学员亲密接触 深度解读断舍离生活美学
  20. android10官方支持机型,Andorid10.0支持哪些手机?附安卓10支持机型介绍

热门文章

  1. excel批量导入数据
  2. 很累很失败,发奋学英语
  3. python中关于sklearn 0.18的错误—— cannot import name comb
  4. [转载] 深层复制构造函数和浅层复制构造函数区别
  5. FPGA开发设计必经之路:时序分析
  6. Choerodon 的微服务之路(二):Choerodon 的微服务网关
  7. 8、第六 -面向对象高级语法-异常处理
  8. RabbitMQ消息队列入门篇(环境配置+Java实例+基础概念)
  9. 阿里云API网关(6)用户指南(开放 API )
  10. 获取context path或者basePath