开发手册 欢迎您!
软件开发者资料库

Node.js - 第一个应用程序

Node.js第一个应用程序 - 从简单和简单的步骤学习Node.js框架,从基本到高级概念,包括简介,环境设置,第一个应用程序,REPL终端,节点包管理器,节点回调概念,事件发射器,节点缓冲器模块,节点流,节点文件系统,全局对象,节点实用程序模块,节点Web模块,节点快速应用程序,节点RESTFul API,节点扩展应用程序,打包。

在创建实际的"Hello,World!"之前使用Node.js的应用程序,让我们看看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() 创建服务器实例的方法,然后使用与服务器实例关联的 listen 方法将其绑定到端口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 messageconsole.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 messageconsole.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 Sample

恭喜,您已经启动并运行了第一台HTTP服务器正在响应端口8081上的所有HTTP请求.