Node.js 第一个示例基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
Node.js第一个示例
可能存在基于控制台和基于Web的node.js应用程序。
Node.js基于控制台的示例
文件: console_example1.js
console.log('Hello lidihuo');
打开Node.js命令提示符并运行以下代码:
node console_example1.js
console.log()函数在控制台上显示消息。
基于Node.js Web的示例
node.js Web应用程序包含以下三个部分:
导入所需的模块: " require"指令用于加载Node.js模块。
创建服务器: 您必须建立一个服务器,该服务器将侦听类似于Apache HTTP Server的客户端请求。
读取请求并返回响应: 在第二步中创建的服务器将读取客户端(可以是浏览器或控制台)发出的HTTP请求并返回响应。
如何创建node.js Web应用程序
请按照以下步骤操作:
导入所需的模块: 第一步是使用?require?指令以加载http模块并将返回的HTTP实例存储到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 http://127.0.0.1:8081/');
文件: main.js
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 http://127.0.0.1:8081/');
如何启动服务器:
转到"开始"菜单,然后单击Node.js命令提示符。
现在打开了命令提示符:
设置路径: 在这里,我们保存了" main.js"
所以在命令提示符下键入 cd desktop 。之后,执行main.js以启动服务器,如下所示:
node main.js
现在服务器已启动。
向Node.js服务器发出请求:
在任何浏览器中打开http://127.0.0.1:8081/。您将看到以下结果。
现在,如果您将" main.js"文件中的任何更改,都需要再次运行" node main.js"命令。