nodejs 简单路由实现

本文介绍了一个简单的Node.js路由实现方案,通过监听不同URL路径来响应相应的HTML页面,包括主页、登录页、列表页和注册页等。对于不存在的路径,则返回404错误页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nodejs 简单路由实现

配置:htmls 文件夹类包含 404.html、index.html、list.html、login.html、register.html

http.js与htmls文件夹同级;

__dirname当前执行环境的文件夹路径

path 模块:path.join()方法,将多个文件夹,文件拼接成一个路径,自动配置分隔符和系统差异。

// 根据用户不同请求,做出不同响应(响应 现有的 HTML 文件)

// 加载 http 模块
var http = require('http');
// 加载 fs 模块
var fs = require('fs');
// 加载 path 模块
var path = require('path');


// 创建 http 服务,并启动该服务
http.createServer(function (req, res) {

  // 通过 req.url 获取用户请求的路径,根据不同的请求路径服务器做出不同的响应
  if (req.url === '/' || req.url === '/index') {
    // 读取 index.html 文件
    fs.readFile(path.join(__dirname, 'htmls', 'index.html'),  function (err, data) {
      if (err) {
        throw err;
      }

      // 把读取到的 index.html 中的内容直接发送给浏览器
      res.end(data);
    });
  } else if (req.url === '/login') {
    // 读取 index.html 文件
    fs.readFile(path.join(__dirname, 'htmls', 'login.html'),  function (err, data) {
      if (err) {
        throw err;
      }

      // 把读取到的 index.html 中的内容直接发送给浏览器
      res.end(data);
    });
  } else if (req.url === '/list') {
   // 读取 index.html 文件
    fs.readFile(path.join(__dirname, 'htmls', 'list.html'),  function (err, data) {
      if (err) {
        throw err;
      }

      // 把读取到的 index.html 中的内容直接发送给浏览器
      res.end(data);
    });
  } else if (req.url === '/register') {
    // 读取 index.html 文件
    fs.readFile(path.join(__dirname, 'htmls', 'register.html'),  function (err, data) {
      if (err) {
        throw err;
      }

      // 把读取到的 index.html 中的内容直接发送给浏览器
      res.end(data);
    });
  } else {
    // 读取 index.html 文件
    fs.readFile(path.join(__dirname, 'htmls', '404.html'),  function (err, data) {
      if (err) {
        throw err;
      }

      // 把读取到的 index.html 中的内容直接发送给浏览器
      res.end(data);
    });
  }
  

}).listen(9090, function () {
  console.log('http://localhost:9090');
});

转载于:https://my.oschina.net/shuaihong/blog/1544503

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值