node.js - nodejs如何封装触发事件?
阿神
阿神 2017-04-17 13:41:02
[Node.js讨论组]
function onRequest(req, res) {    
    var postData = "";   
    var pathname = url.parse(req.url).pathname;    
    
    req.setEncoding("utf8");    
    req.addListener("data", function(postDataChunk) {      
        postData += postDataChunk;      
        console.log("Received POST data chunk '" +  postDataChunk + "'.");    
    });    
    req.addListener("end", function() {      
        if (pathname.indexOf('/whywhy') > -1) {
            //发送请求后emit 'complete'
            sendRequestToOtherService(pathname);
            //下面这个监听如何封装后方在onRequest(req,res)外面,类似
            // 封装这部分
            OtherService.on('complete',function(msg) {
                var sendData = JSON.stringify(msg.iteminfo);
                res.writeHead(200, {"Content-Type": "text/plain"});
                res.end(sendData); 
            });
                
        } else {
            logwarn.info("Request for " + pathname );    
            res.setHeader('Content-Type', 'text/html');
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
        }
    });  
} 
//使上面那部分放到这里。。放到这里后res又undefined,如何把res也封装到里面。
 OtherService.on('complete',function(msg) {
                var sendData = JSON.stringify(msg.iteminfo);
                res.writeHead(200, {"Content-Type": "text/plain"});
                res.end(sendData); 
            });
http.createServer(onRequest).listen(8081);
阿神
阿神

闭关修行中......

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号