源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

nodeJS实现路由功能实例代码

  • 时间:2022-06-29 16:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:nodeJS实现路由功能实例代码
[b]前面的话[/b] 本文将使用NodeJS实现较复杂应用的路由功能 [b]结构[/b] 项目结构如下 [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100100_0_43844.png[/img] 代码如下 [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100100_1_1219.png[/img]  [b]功能 [/b] [b]【router.js】[/b]
// 加载所需模块
var http = require('http');
var url = require('url');
var fs = require('fs');

var host = '127.0.0.1';
var port = 8080;

http.createServer(function(req,res){
  var pathname = url.parse(req.url).pathname;
  console.log('Request for ' + pathname + ' received.');
    function showPaper(path,status){
      var content = fs.readFileSync(path);
      res.writeHead(status, { 'Content-Type': 'text/html;charset=utf-8' });
      res.write(content);
      res.end();
    }
    switch(pathname){
    //'首页'
    case '/':
    case '/home':
      showPaper('./view/home.html',200);
      break;
    //'about页'
    case '/about':
      showPaper('./view/about.html',200);  
      break;
    //'404页'
    default:
      showPaper('./view/404.html',404);
      break;              
  }  
}).listen(port, host);
【404.html】
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
404  
</body>
</html>

[b]【about.html】[/b]
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
about  
</body>
</html>
[b]【home.html】[/b]
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
home  
</body>
</html>
演示 [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100100_2_39978.png[/img] [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100101_3_63962.png[/img] [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100101_4_2572.png[/img] [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100101_5_27935.png[/img] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部