chapter5 node.js简单应用开发

在前文中,我们了解了npm的基本使用与常用操作,那么,它如何应用到开发中呢?本文将结合npm,构建一个简单的nodejs应用,使读者对node.js应用开发有一个基本的了解:

初始准备

首先准备好项目文件夹,在文件夹路径启动终端输入命令:

npm init

这样会生成一个package.json文件,用于项目基础信息的构建,由于init是问答式的创建方式,下面我们来了解一下问答的问题分别是什么意思:

  • package name: 用于指定包名/项目名
  • version: (1.0.0):项目版本号,默认为1.0.0
  • description: 项目描述,默认是留空的
  • entry point: (index.js):项目的入口文件
  • test command: 项目测试命令定义(如果你需要测试)
  • keywords: 项目关键词,如果需要上架npm市场则填写
  • author: 作者信息
  • license: (ISC) 开源许可证
    在这里我们只需了解一下,实际上,开发中需要频繁的变动package.json信息,无需关注初始文件,这里我们修改生成的package.json,在script部分添加一个start命令的定义,用于启动后续编写的服务器:
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "nodetest.js",//入口文件
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"node nodetest.js"//nodetest.js替换为你项目的入口文件
  },
  "author": "ylab",
  "license": "MIT"
}

node应用编写

接着我们来编写对应的node应用:

const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
  // 设置HTTP响应的状态码和头信息
  res.writeHead(200, {
    // 设置内容类型为 HTML,并指定字符集为 UTF-8,这样中文不会乱码
    'Content-Type': 'text/html; charset=utf-8' 
  });
  // 发送响应体
  res.end('<h1>Hello, World!</h1><p>这是我的第一个 Node.js 应用。</p>');
});
// 监听端口
const PORT = 4090;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

当然,我们还可以通过req.url属性的监听实现一个简单的路由系统:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
    res.end('欢迎来到主页!');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
    res.end(`sucess!当前路径为${req.url}.`);
  }else if(req.url === '/403'){
    res.writeHead(403, { 'Content-Type': 'text/plain;charset=utf-8' });
    res.end('服务器错误!!!');
  }
   else {
    res.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' });
    res.end('页面走丢了......');
  }
});

const PORT = 4090;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

node请求类型

同其他web框架一样,node也可以接收不同类型的请求,其中最常用的请求类型为GET/POST,我们可以通过method属性来判断请求类型:

var http = require('http');
var server = http.createServer(function(req, res) {
    if (req.method === 'POST') {
        res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
        res.end('<h1>这是一个post请求</h1>');
    }
    if(req.method === 'GET'){
    res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
    res.end('<h2>这是一个GET请求</h2>')
    }
}).listen(8089);
console.log("localhost:8089")

使用API测试工具进行请求发送,可以得到正常的响应返回。
在WEB开发中,POST请求一般用于数据的提交,因此可以带有值,node.js 中可以使用 URL 构造函数解析请求的 URL。
URL 对象是 Node.js 中用于解析和操作 URL 的一种标准工具。它提供了方便的接口来访问和修改 URL 的各个组成部分,如协议、主机名、路径、查询参数等。修改代码为下:

var http = require('http');
var server = http.createServer(function(req, res) {
    if (req.method === 'POST') {
    res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
	const urlpat=(req.url,`http://${req.headers.host}`)
	res.end(util.inspect({
	href: myUrl.href, 
	origin: myUrl.origin,
	 protocol: myUrl.protocol,
	  host: myUrl.host, 
	  hostname: myUrl.hostname,
	  port: myUrl.port, 
	  pathname: myUrl.pathname,
	   search: myUrl.search, 
	   searchParams: Object.fromEntries(myUrl.searchParams) // 将 searchParams 转为普通对象
	})
	)
    }
    if(req.method === 'GET'){
    res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
    res.end('<h2>这是一个GET请求</h2>')
    }
}).listen(8089);
console.log("localhost:8089")

这样,我们就实现了一个简单的nodejs应用,能够接收不同的请求并且进行处理,但我们可以看到这些返回仍然过于局限,因此,我们可以集成node的fs模块来进行文件读取,从而实现页面返回:

实现静态页面返回

首先创建一个返回的页面index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <h1>index</h1>
    <div>这是一个首页</div>
</body>
</html>

然后创建一个page.js:

var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   // 从文件系统中读取请求的文件内容
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP 状态码: 404 : NOT FOUND
         // Content Type: text/html
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{            
         // HTTP 状态码: 200 : OK
         // Content Type: text/html
         response.writeHead(200, {'Content-Type': 'text/html'});    
         // 响应文件内容
         response.write(data.toString());        
      }
      //  发送响应数据
      response.end();
   });  

}).listen(8080);
// 控制台输出以下信息
console.log('Server running at http://127.0.0.1:8080/');

执行node pages.js命令,在浏览器输入 http://127.0.0.1:8080/index.html 可以看到index.html被成功的返回。
到这里,不妨思考一下,这样的请求方式是否过于繁琐,是否有复用的方式避免这样的重复书写?

posted @ 2025-07-30 23:15  fhyxz1  阅读(8)  评论(0)    收藏  举报