Node.js 如何创建一个显示Hello World的简单服务器

Node.js 如何创建一个显示Hello World的简单服务器

服务器是一种为其他程序或设备(称为客户端)提供功能的计算机硬件或软件。这种架构称为客户端-服务器模型。Node是一个开源的、跨平台的运行时环境,允许开发人员使用JavaScript创建各种服务器端工具和应用程序。

在下面的示例中,我们将在Node.js中创建一个简单的服务器,使用express服务器返回Hello World。

创建NodeJS应用: 使用以下命令初始化NodeJS应用:

npm init

模块安装: 使用以下命令安装 express 模块,它是NodeJS的一个Web框架。

npm install express

实现: 创建一个 app.js 文件,并在其中写入以下代码。

app.js

// Require would make available the 
// express package to be used in 
// our code 
const express = require("express"); 
  
// Creates an express object 
const app = express(); 
  
// It listens to HTTP get request.  
// Here it listens to the root i.e '/' 
app.get("/", (req, res) => { 
  
  // Using send function we send 
  // response to the client 
  // Here we are sending html 
  res.send("<h1> Hello World </h1>"); 
}); 
  
// It configures the system to listen 
// to port 3000. Any number can be  
// given instead of 3000, the only 
// condition is that no other server 
// should be running at that port 
app.listen(3000, () => { 
  
  // Print in the console when the 
  // servers starts to listen on 3000 
  console.log("Listening to port 3000"); 
});

运行应用程序的步骤: 使用以下命令运行 app.js 文件。

node app.js

输出: 现在打开浏览器并转到 http://localhost:3000/ ,您将看到以下输出:

Node.js 如何创建一个显示Hello World的简单服务器

所以这就是你可以设置服务器并完成任务的方式。如果你想返回其他内容,那么在 res.send() 的 app.get() 函数中传递该参数,而不是“Hello World”。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程