nodejs路由控制图文混排

nodejs通过路由升级,接口处返回文字和图片,进行图文混排。

思考:

当第一次请求localhost:8006/buny的时候,会加载buny.html的文档部分,当<img src="/shiwImg">的时候,会加载localhost:8006/showImg的方法读取图片。最后一期显示出来,图片和文字一起加载。主要就是通过控制路由。

routerImg.js

var http=require('http');
var url=require('url');
var router=require('../module/tuwen.js');
http.createServer(function(request,response){

    if(request.url !== '/favicon.ico'){//清除第二次访问
        console.log('访问');
        var pathname=url.parse(request.url).pathname;
        pathname=pathname.replace(/\//,'');//替换前面/
        console.log(pathname)
        router[pathname](request,response);
        // response.end("");//不写会没有协议尾部,但是写了会访问俩次
    }
}).listen(8006);
console.log('Server running at http://127.0.0.1:8006/')

 tuwen.js

var optfile = require('../module/optfile.js');
var imgFile=require('../module/image.js');
module.exports={
    buny:function(req,res){
        //闭包,回调这个函数,客户端打印程序
        function recall(data){
            res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
            res.write(data);
            res.end("");
        }
        optfile.readfile('../view/buny.html',recall)
    },
    showImg:function (req,res){
        res.writeHead(200,{'Content-Type':'image/jpeg'});
        imgFile.readImg('../imgs/vue.png',res);
    }
}

 optfile.js

var fs=require('fs');
module.exports={
    readfileSync:function(path){//同步读取
        var data = fs.readFileSync(path,'utf-8');
        console.log('同步方法执行完毕');
        // return data;
    },
    readfile:function(path,recall){ //异步执行
        fs.readFile(path,function(err,data){
            if(err){
                console.log(err);
            }else{
                console.log(data.toString());
                recall(data);
            }
        })
    },
}

buny.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
喜欢你
<img src="/showImg"/>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值