在创建实际的" 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无涯教程网
无涯教程使用 require 指令加载http模块并将返回的HTTP存储到http变量中,如下所示-
var http=require("http");
无涯教程使用创建的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端口等待请求。
让无涯教程将步骤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/,然后观察以下输出。
祝贺您,您的第一个HTTP服务器已启动并正在运行,它正在响应端口8081上的所有HTTP请求。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)