如何使用Node.js构建一个简单的Web服务器
介绍: Node.js是一个开源的、跨平台的运行时环境,用于在浏览器之外执行JavaScript代码。需要记住的是, Node.js不是一个框架,也不是一种编程语言。 Node.js主要用于服务器端编程。在本文中,我们将讨论如何使用Node.js创建一个Web服务器。
使用NodeJS创建Web服务器: 有两种主要的方式如下。
- 使用内置模块http
- 使用第三方模块express
使用http模块: HTTP和HTTPS是两个内置模块,用于创建一个简单的服务器。HTTPS模块通过这个模块的安全层特性来提供通信的加密功能,而HTTP模块不提供数据的加密功能。
项目结构: 它将如下所示。
index.js
// Importing the http module
const http = require("http")
// Creating server
const server = http.createServer((req, res) => {
// Sending the response
res.write("This is the response from the server")
res.end();
})
// Server listening to port 3000
server.listen((3000), () => {
console.log("Server is Running");
})
使用以下命令运行 index.js 文件:
node index.js
输出: 现在打开你的浏览器,前往 http://localhost:3000/ ,你将看到以下输出:
使用express模块 :express.js是node.js中最强大的框架之一,它在http模块的上层工作。使用express.js服务器的主要优势是通过客户端过滤传入请求。
安装模块: 使用以下命令安装所需模块。
npm install express
项目结构: 它将如下所示。
index.js
// Importing express module
const express = require("express")
const app = express()
// Handling GET / request
app.use("/", (req, res, next) => {
res.send("This is the express server")
})
// Handling GET /hello request
app.get("/hello", (req, res, next) => {
res.send("This is the hello response");
})
// Server setup
app.listen(3000, () => {
console.log("Server is Running")
})
运行下面的命令来执行 index.js 文件:
node index.js
输出: 现在打开你的浏览器并访问 http://localhost:3000/ ,你将看到下面的输出: