您的位置:首页 > Web前端 > Node.js

Node.js入门实例程序

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

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

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

读取请求,并返回响应: 在前面的步骤中创建的服务器将读取客户端发出的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 World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at ' target='_blank'>http://127.0.0.1:8081/');[/code] 上面的代码创建监听即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 ' target='_blank'>http://127.0.0.1:8081/');[/code] 现在执行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。

标签:Node js 入门 实例程序
本站文章除注明转载外,均为本站原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:易百教程 [http:/www.yiibai.com]
本文标题:Node.js入门实例程序
本文地址:http://www.yiibai.com/nodejs/nodejs_first_application.html
上一篇下一篇
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: