《了不起的 nodejs》中 TwitterWeb 案例 bug 解決

來源:互聯網
上載者:User

標籤:utf8   簡單的   eth   web用戶端   node   res   stdout   pos   log   

了不起的nodejs算是一本不錯的入門書,不過書中個別案例存在bug,按照書中源碼無法做出和書中相同效果,原本興奮的心情摻雜著些許失落。

現在我們看一下第七章HTTP,一個Twitter Web用戶端的例子。

先貼上書中源碼

1.建立server.js

 1 var qs = require(‘querystring‘); 2 require(‘http‘).createServer(function(req,res){ 3     var body =""; 4     req.on(‘data‘,function(chunk){ 5         body += chunk; 6     }); 7     req.on(‘end‘,function(){ 8         res.writeHead(200); 9         res.end(‘Done‘);10         console.log(‘\n got name \033[90m‘ + qs.parse(body).name + ‘\033[39m\n‘);11         12     });13 }).listen(3000);

2.建立client.js

 1 var http = require(‘http‘), 2         qs = require(‘querystring‘); 3  4 function send (theName){ 5     http.request({ 6         host: ‘127.0.0.1‘, 7         port: 3000, 8         url: ‘/‘, 9         method:‘POST‘10         },function(res){11             res.setEncoding(‘utf8‘);12             res.on(‘end‘,function(){13                 console.log(‘\n  \033[90m  request complete!\033[39m‘ );14                 process.stdout.write(‘\n your name: ‘);15             });16         }).end(qs.stringify({name: theName}));17 }18 19 process.stdout.write(‘\n your name: ‘);20 process.stdin.resume();21 process.stdin.setEncoding(‘utf8‘);22 process.stdin.on(‘data‘,function(name){23     send(name.replace(‘\n‘, ‘‘));24 })

很遺憾,最後出來的結果是這樣子

效果非常不理想

問題出在哪裡呢,和源碼一樣啊?

哈哈,其實只需要將 client.js 中發送使用者名稱的回呼函數修改一下就可以了。

 1 var http = require(‘http‘), 2         qs = require(‘querystring‘); 3  4 function send (theName){ 5     http.request({ 6         host: ‘127.0.0.1‘, 7         port: 3000, 8         url: ‘/‘, 9         method:‘POST‘10         },function(){11             // res.setEncoding(‘utf8‘);12             // res.on(‘end‘,function(){13                 console.log(‘\n  \033[90m  request complete!\033[39m‘ );14                 process.stdout.write(‘\n your name: ‘);15             // });16         }).end(qs.stringify({name: theName}));17 }18 19 process.stdout.write(‘\n your name: ‘);20 process.stdin.resume();21 process.stdin.setEncoding(‘utf8‘);22 process.stdin.on(‘data‘,function(name){23     send(name.replace(‘\n‘, ‘‘));24 })

最終結果就是這樣子

是不是很酷,雖然是一個很簡單的小例子,不過對於初學者來說還是很有成就感的!

《了不起的 nodejs》中 TwitterWeb 案例 bug 解決

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.