Node.js - 应用实例

Node.js - 应用实例 首页 / Node.js入门教程 / 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请求,客户端可以是浏览器或控制台,并返回响应。

    链接:https://www.learnfk.comhttps://www.learnfk.com/nodejs/nodejs-first-application.html

    来源:LearnFk无涯教程网

创建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'});
   
   //将响应正文作为“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://127.0.0.1:8081/,然后观察以下输出。

Node.js Sample

祝贺您,您的第一个HTTP服务器已启动并正在运行,它正在响应端口8081上的所有HTTP请求。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Android开发高手课 -〔张绍文〕

iOS开发高手课 -〔戴铭〕

即时消息技术剖析与实战 -〔袁武林〕

安全攻防技能30讲 -〔何为舟〕

.NET Core开发实战 -〔肖伟宇〕

Service Mesh实战 -〔马若飞〕

张汉东的Rust实战课 -〔张汉东〕

etcd实战课 -〔唐聪〕

云原生基础架构实战课 -〔潘野〕

好记忆不如烂笔头。留下您的足迹吧 :)