nodeJS实现路由功能实例代码

2019/6/27 20:55:17

本文主要是介绍nodeJS实现路由功能实例代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前面的话

本文将使用NodeJS实现较复杂应用的路由功能

结构

项目结构如下

代码如下

 功能

【router.js】

// 加载所需模块
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>

【about.html】

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
about  
</body>
</html>

【home.html】

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
home  
</body>
</html>

演示

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。



这篇关于nodeJS实现路由功能实例代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程