创建Node.js网络服务器步骤

97 阅读2分钟

创建Node.js网络服务器

你好。在本教程中,我们将创建一个简单的node.js网络服务器并处理HTTP请求。node.js框架通常用于创建基于服务器的应用程序,并进一步用于向用户显示内容。

1.1.简介

1.1 设置Node.js

要在Windows上设置Node.js,你需要从这个链接下载安装程序。点击你的平台的安装程序(也包括NPM包管理器),运行安装程序,开始Node.js设置向导。按照向导的步骤操作,完成后点击 "完成"。如果一切顺利,你可以导航到命令提示符来验证安装是否成功,如图1所示。

Node.js Web Server - npm installation

图1: 验证node和npm的安装

2.创建Node.js网络服务器

为了设置应用程序,我们将需要导航到我们的项目所在的路径。对于编程的东西,我正在使用Visual Studio Code作为我的首选IDE。你可以自由选择你喜欢的IDE。

2.1 设置依赖性

导航到项目目录,运行npm init -y ,创建一个package.json 文件。这个文件保存着与项目有关的元数据,用于管理项目的依赖性、脚本、版本等。在该文件中添加以下代码,我们将指定所需的依赖性。

{
  "name": "webserver",
  "version": "1.0.0",
  "description": "nodejs and webserver",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "webserver"
  ],
  "author": "c-danatl",
  "license": "MIT",
  "dependencies": {
    "nodemon": "^2.0.9"
  }
}

要下载依赖项,请导航到包含该文件的目录路径,并使用npm install 命令。如果一切顺利,依赖项将被加载到node_modules 文件夹中,你就可以进行下一步了。

2.2 创建索引控制器

创建一个控制器文件,使用require(…) 功能导入 HTTP 模块。这个模块将被用来创建网络服务器,并指定带有请求和响应参数的回调函数。

// importing node.js core module
const http = require('http');

// application endpoints -
// Index - http://localhost:5001/

const server = http.createServer(function (req, resp) {
    // handling incoming requests here

    // setting response header
    resp.writeHead(200, { 'Content-Type': 'text/html' });
    // setting response content
    resp.write('<html><body><p>Welcome to javacodegeeks</p></body></html>');
    resp.end;

    // todo - similarly you can create other endpoints.
});

// start app
// listen for any incoming requests
const PORT = process.env.PORT || 5001;
server.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3.运行应用程序

要运行该应用程序,请导航到项目目录并输入以下命令,如图2所示。如果一切顺利,应用程序将在端口号5001 上成功启动。

Node.js Web Server - starting the app

图 2: 启动应用程序

4.项目演示

当应用程序启动后,打开你选择的浏览器并点击以下网址 -http://localhost:5001 。如图3所示,索引页将显示给用户。

Node.js Web Server - index page

图 3: 索引页

本教程到此结束,我希望这篇文章能为你提供你想要的东西。祝你学习愉快,不要忘记分享!

5.总结

在本教程中,我们学习了如何用简单的步骤创建一个node.js网络服务器。