express 的中间件

本文探讨了Express框架中的两个关键中间件:static用于高效提供静态资源服务,包括配置静态目录、响应头和缓存;而bodyParser则专注于解析请求参数,确保数据正确处理。

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

static

static 中间件主要用来提供静态资源服务 ,可以设置静态资源的目录 设置响应头 及缓存等等配置,代码如下

function static(root,options = {}){
    let { dotfiles = "ignore" ,etag=true,lastModified,maxAge=0, setHeaders } = options;
    return function(req,req,next){
        let { pathname } = url.parse(req.url,true);
        let file = path.join(root,pathname);
        let parts = file.split(path.sep);
        let isDotFile = parts[parts.length-1][0]==".";
        if(isDotFile && dotfiles=="deny"){  //拒绝访问.文件
            res.setHeader("Content-Type","text/html");
            res.statusCode = 403;
            return res.end(http.STATUS_CODES[403]);
        }
        fs.stat(file,function(error,stat){
            if(error){
                next()
            }else{
                if(etag){
                    res.setHeader("ETag",stat.mtime.toLocaleDateString());
                }
                if(lastModified){
                    res.setHeader("Last-Modified",stat.mtime.toUTCString())
                }
                if(typeof setHeaders =='function'){
                    setHeaders(req,req,function(params){
                        console.log(params);
                    });
                }
                res.setHeader("Cache-Control",`max-age=${maxAge}`);
                res.setHeader("Content-Type",mime.getType(file)) 
                fs.createReadStream(file).pipe(res);
            }
        })
    }
};

bodyParser

bodyParser 中间件用来解析请求参数
json

function json(options){
    return function(req,res,next){
        let contentType = req.headers["content-type"];
        if(contentType=="application/json"){
            const buffer = [];
            req.on("data",function(data){
                buffer.push(data);
            });
            req.on("end",function(){
                let result = buffer.toString();
                req.body = JSON.parse(result);
                next()
            })
        }else{
            next();
        }
    }
}   

urlencoded

function urlencoded(options){
    let { extended } = options;
    return function(req,res,next){
        let contentType = req.headers["content-type"];
        console.log(contentType);
        if(contentType=="application/x-www-form-urlencoded"){
            const buffer = [];
            req.on("data",function(data){
                buffer.push(data);
            });
            req.on("end",function(){
                let result = buffer.toString();
                if(extended){
                    //qs 可以支持嵌套对象;
                    req.body = qs.parse(result);
                }else{
                    req.body = querystring.parse(result);
                }
                next();
            })
        }else{
            next();
        }
    }
}   

text

function text(options){
    return function(req,res,next){
        const contentType = type.parse(req.headers["content-type"]);
        const charset =  contentType.parameters.charset;
        const cType = contentType.type;
        if(cType=="text/plain"){
            const buffer = [];
            req.on("data",function(data){
                buffer.push(data);
            });
            req.on("end",function(){
                let r = Buffer.concat(buffer);
                if(charset=="gbk"){
                    req.body =  iconv.decode(r,charset);
                }else{
                    req.body = buffer.toString();
                }
                next()
            })
        }else{
            next();
        }
    }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值