Node.js入门实例程序
2016-04-13 13:46
645 查看
在使用Node.js创建实际“Hello, World!”应用程序之前,让我们看看Node.js的应用程序的部分。Node.js应用程序由以下三个重要组成部分:
导入需要模块: 我们使用require指令加载Node.js模块。
创建服务器: 服务器将监听类似Apache HTTP Server客户端的请求。
读取请求,并返回响应: 在前面的步骤中创建的服务器将读取客户端发出的HTTP请求,它可以从一个浏览器或控制台并返回响应。
导入需要模块: 我们使用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
上一篇下一篇
相关文章推荐
- Node.js教程
- nodejs pm2的简单应用
- NodeJS、NPM安装配置步骤(windows版本)
- 做为一个前端工程师,是往node方面转,还是往HTML5方面转
- nodejs 自启动脚本
- windows 下安装nodejs及其配置环境
- intern/dojo/node!leadfoot/Command封装
- LeetCode OJ 292.Nim Gam19. Remove Nth Node From End of List
- Node.js的cluster模块用于使用多核CPU
- 浅析nodejs的buffer类(转)
- Hadoop2,NameNode format 源码分析
- [C语言][LeetCode][24]Swap Nodes in Pairs
- leetcode 25 Reverse Nodes in k-Group
- 重启Hadoop集群时no namenode to stop的异常
- Node.js学习笔记:setImmediate与process.nextTick
- NodeJS TroubleShooting--Alert Undefined!
- NodeJS 中模块module查找过程
- 19. Remove Nth Node From End of List
- java解析XML Node与Element的区别
- node学习之express(1)