Node.js 第一个应用

Node.js 第一个应用

在使用Node.js创建一个真正的“Hello, World!”应用程序之前,让我们先看一下Node.js应用程序的组件。Node.js应用程序由以下三个重要组件组成:

  • 导入所需模块 - 我们使用 require 指令加载Node.js模块。

  • 创建服务器 - 一个监听客户端请求的服务器,类似于Apache HTTP服务器。

  • 读取请求并返回响应 - 在前面的步骤中创建的服务器将读取客户端发送的HTTP请求(可以是浏览器或控制台),并返回响应。

创建Node.js应用程序

步骤1 – 导入所需模块

我们使用 require 指令加载http模块,并将返回的HTTP实例存储在http变量中,如下所示 –

var http = require("http");

步骤2 – 创建服务器

我们使用已创建的http实例并调用 http.createServer() 方法创建一个服务器实例,然后使用 listen 方法将其绑定到端口8081。将其传递一个具有参数request和response的函数。编写示例实现,始终返回”Hello World”。

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

以上代码足以创建一个HTTP服务器,它监听本地机器上8081端口上的请求。

步骤3 – 测试请求和响应

让我们将步骤1和2放在一个名为 main.js 的文件中,并按照下面的示例启动我们的HTTP服务器:

var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

现在执行main.js以以下方式启动服务器−

$ node main.js

验证输出。服务器已启动。

Server running at http://127.0.0.1:8081/

向Node.js服务器发出请求

在任何浏览器中打开http://127.0.0.1:8081/并观察以下结果。

Node.js 第一个应用

恭喜,您的第一个HTTP服务器已经成功运行,正在端口8081上响应所有的HTTP请求。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程