入门实例程序

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

[list]
[*][b]导入需要模块:[/b] 我们使用require指令加载Node.js模块。

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

[*][b]读取请求,并返回响应:[/b] 在前面的步骤中创建的服务器将读取客户端发出的HTTP请求,它可以从一个浏览器或控制台并返回响应。
[/list]
[b]创建Node.js应用 步骤 1 - 导入所需的模块[/b]
我们使用require指令来加载HTTP模块和存储返回HTTP,例如HTTP变量,如下所示:

[quote]var http = require("http");[/quote]
[b]步骤 2: 创建服务[/b]
在接下来的步骤中,我们使用HTTP创建实例,并调用http.createServer()方法来创建服务器实例,然后使用服务器实例监听相关联的方法,把它绑定在端口8081。 通过它使用参数的请求和响应函数。编写示例实现返回 "Hello World".

[quote]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/');[/quote]
上面的代码创建监听即HTTP服务器。在本地计算机上的8081端口等到请求。

[b]步骤 3: 测试请求和响应[/b]
让我们把步骤1和2写到一个名为main.js的文件,并开始启动HTTP服务器,如下所示:

[quote]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/');[/quote]
现在执行main.js来启动服务器,如下:

[img]http://www.yiibai.com/uploads/allimg/150329/0S3052139-0.jpg[/img]

$ node main.js
[b]验证输出。服务器已经启动[/b]

Server running at http://127.0.0.1:8081/
发出Node.js服务器的一个请求
在任何浏览器中打开地址:http://127.0.0.1:8081/,看看下面的结果。

First Application
恭喜,第一个HTTP服务器运行并响应所有的HTTP请求在端口8081。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值