Node.js应用实例
在创建实际的" Hello,World!"之前使用Node.js的应用程序,让无涯教程看一下Node.js应用程序的组件,Node.js应用程序包含以下三个重要组件-
Import required modules - 无涯教程使用 require 指令加载Node.js模块。
Create server - 类似于Apache HTTP Server的服务器,它将监听客户端的请求。
Read request and return response- 在先前步骤中创建的服务器将读取客户端发出的HTTP请求,客户端可以是浏览器或控制台,并返回响应。
创建Node.js应用
步骤1- 加载模块
无涯教程使用 require 指令加载http模块并将返回的HTTP存储到http变量中,如下所示-
var http=require("http");
步骤2- 创建监听服务
http.createServer(function (request, response) { //Send the HTTP header //HTTP Status: 200 : OK //Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); //将响应正文作为“Hello World”发送 response.end('Hello World\n'); }).listen(8081); //控制台将打印消息 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'}); //发送消息 response.end('Hello World\n'); }).listen(8081); //控制台将打印消息 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/
发出请求

祝贺您,您的第一个HTTP服务器已启动并正在运行,它正在响应端口8081上的所有HTTP请求。
祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)
精选教程推荐
👇 以下精选教程可能对您有帮助,拓展您的技术视野
暂无学习笔记,成为第一个分享的人吧!
您的笔记将帮助成千上万的学习者