发布于 2015-07-05 12:30:00 | 738 次阅读 | 评论: 0 | 来源: 网络整理

在使用Node.js创建实际“Hello, World!”应用程序之前,让我们看看Node.js的应用程序的部分。Node.js应用程序由以下三个重要组成部分:

  1. 导入需要模块: 我们使用require指令加载Node.js模块。

  2. 创建服务器: 服务器将监听类似Apache HTTP Server客户端的请求。

  3. 读取请求,并返回响应: 在前面的步骤中创建的服务器将读取客户端发出的HTTP请求,它可以从一个浏览器或控制台并返回响应。

创建Node.js应用

步骤 1 - 导入所需的模块

我们使用require指令来加载HTTP模块和存储返回HTTP,例如HTTP变量,如下所示:


var http = require("http");

步骤 2: 创建服务

在接下来的步骤中,我们使用HTTP创建实例,并调用http.createServer()方法来创建服务器实例,然后使用服务器实例监听相关联的方法,把它绑定在端口8081。 通过它使用参数的请求和响应函数。编写示例实现返回 "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 Worldn');
}).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 Worldn');
}).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/,看看下面的结果。

恭喜,第一个HTTP服务器运行并响应所有的HTTP请求在端口8081。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务