当前位置:首页 > 其他问题 > node.js 创建静态 web服务 和路由

node.js 创建静态 web服务 和路由

王丛4年前 (2021-04-12)其他问题651

route.js代码如下所示。

 

const fs=require('fs');

const path=require('path');

const url=require('url');

 

//私有方法

let getFileMime  = function(extname){

    var data=fs.readFileSync('./data/mime.json');

    let mimeObj=JSON.parse(data.toString());

    return mimeObj[extname];

}

 

exports.static=function(request,response,staticPath){

    //获取地址

  let pathname=url.parse(request.url).pathname;

  pathname=pathname=='/'?'/index.html':pathname;

  //获取后缀名

  let extname=path.extname(pathname);

  //通过fs模块读取文件

  if(pathname!='/favicom.ico'){

    fs.readFile('./'+staticPath+pathname,(err,data)=>{

      if(err){

        response.writeHead(404,{'Content-Type': 'text/html;charset="utf-8"'});

        response.end("该页面不存在");

      }

      let mime=path.extname(extname);

      response.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});

      response.end(data);

    })

  }

}

 

 

 

       app.js代码如下所示。通过require引入我们自定义的route模块,然后调用static方法创建静态web服务。

 

const http = require('http');

const routes=require('./module/route');

 

 

http.createServer(function (request, response) {

 

  //创建静态web服务

  routes.static(request,response,'static');

  

}).listen(8081);

 

console.log('Server running at http://127.0.0.1:8081/');

 

路由

       路由指的是针对不同请求的URL,处理不同的业务逻辑。

 

路由时一个URI和一个特定的HTTP方法(get/post等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。

 

       比如说,http://域名//login,处理登录的业务逻辑,那么这个就是路由。路由的实现需要引入url模块。

 

       新建routetest.js,通过url获取请求路径pathname,然后通过if语句进行判断,执行相应的业务逻辑。提示:对于访问站点下的静态资源,其实我们都将相关方法封装到了route模块中。

 

const http = require('http');

const routes = require('./module/routes');
const path = require('path');
const url=require('url');



http.createServer(function (reqres) {   
    //创建静态web服务
    routes.static(req,res,'static');
    //路由
    let pathname=url.parse(req.url).pathname;
    let extname = path.extname(pathname);
    if(!extname){ //如果有请求地址有后缀名的话让静态web服务去处理 
        if(pathname=='/login'){
            res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            res.end("执行登录");
        }else if(pathname=='/register'){
            res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            res.end("执行注册");
        }else if(pathname=='/admin'){
            res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            res.end("处理后的业务逻辑");
        }else{
            res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
            res.end("404");
        }
    }


}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

 

 

 

 

 

       启动之后,发现127.0.0.1:8081/index.html显示页面不存在,我们写的这个127.0.0.1:8081/login等等可以正常运行,这是为啥呢?我们知道访问index.html的功能实际上该静态服务器本身是可以处理的(封装到route中了),显示页面不存在可以说明创建静态服务器还没有完成,直接跑到了下面这个判断pathname的过程中了。这又是为啥呢?因为route.js中读取文件的方法是个异步方法,所以我们需要把程序改成同步的。

 

       修改routes.js内容。注意我们将readFile改成了readFileSync!

 

const fs = require('fs');
const path = require('path');
const url = require('url');

//私有方法
let getFileMime = function (extname) {

    var data = fs.readFileSync('./data/mime.json'); //同步方法
    let mimeObj = JSON.parse(data.toString());
    return mimeObj[extname];

}

exports.static = function (reqresstaticPath) {

    //1、获取地址
    let pathname = url.parse(req.url).pathname;
    let extname = path.extname(pathname);

    if (extname) {  //如果有后缀名让静态web处理 否则路由处理
        //2、通过fs模块读取文件
        if (pathname != '/favicon.ico') {
            try {
                let data = fs.readFileSync('./' + staticPath + pathname);
                if (data) {
                    let mime = getFileMime(extname);
                    res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
                    res.end(data);
                }
            } catch (error) {
                console.log(error)
            }
        }
    }

}




 

打赏

扫描二维码推送至手机访问。

版权声明:本文由一段神奇的代码发布,如需转载请注明出处。

分享给朋友:

相关文章

mfc140u.dll 丢失

mfc140u.dll 丢失

mfc140u.dll 文件丢失怎么办,解决方法在这里点击下载 VC2017运行库 可以通过这个文件安装vc的运行库进行问题的解决。亲测有效...

node.js  封装   获取post  get

node.js 封装 获取post get

const http = require("http"); const app=require('./module/route'); const ejs = require("ejs"); //注册web服务 ht...

mongDB数据库操作

mongDB数据库操作

1、连接数据库 清屏: cls 查看所有数据库列表 show dbs 二、 创建数据库、查看、删除数据库 1、使用数据库、创建数据库 use itying 如果真的想把这个数据库创建成功,那么必须插入一个数据。 数据库中不能直接插入数据,只能往集合(collections)中插入数...

webpack  的一些配置理解

webpack 的一些配置理解

˂a name="自己根据视频敲的代码 已经上传到gitee 在这记录一下 为了自己理解 每一个代码都加上自己的理解注释 ,重点注重webpack 的版本问题" class="reference-link" href="#"˃自己根据视频敲的代码 已经上传到gitee 在这记录一下 为了自己理解 每...

[原创]应届生论文查重

[原创]应届生论文查重

万方免费查重(应届生免费一次):chsi.wanfangtech.net PaperDay(标准版永久免费,旗舰版每日限免):www.paperday.cn 论文狗(每日免费一次): www.lunwengo.net PaperYY(每日免费一次,11点多免费两次):www.paperyy....

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。