Nodejs教程
Nodejs Mysql
Nodejs MongoDB
Nodejs 对比

Node.js 第一个示例

Node.js第一个示例

可能存在基于控制台和基于Web的node.js应用程序。

Node.js基于控制台的示例

文件: console_example1.js
console.log('Hello lidihuo'); 
打开Node.js命令提示符并运行以下代码:
node console_example1.js
Node.js控制台示例1
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实例并调用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 message
console.log('Server running at http://127.0.0.1:8081/');
将step1和step2合并在一起在名为" main.js"的文件中。
文件: 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命令提示符。
Node.js第一个示例1
现在打开了命令提示符:
Node.js第一个示例2
设置路径: 在这里,我们保存了" main.js"
所以在命令提示符下键入 cd desktop 。之后,执行main.js以启动服务器,如下所示:
node main.js
Node.js第一个示例3
现在服务器已启动。
向Node.js服务器发出请求:
在任何浏览器中打开http://127.0.0.1:8081/。您将看到以下结果。
Node.js第一个示例5
现在,如果您将" main.js"文件中的任何更改,都需要再次运行" node main.js"命令。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4