Cloud9のNode.jsテンプレートでreq.read()した時にnullが入る
ドットインストールのNode.js入門をCloud9のNode.jsテンプレートで動かして学んでいたところ、フォームを作ってPOSTしたデータをイベントで受け取って表示するという内容で詰まりました。
server.js(一部省略)
function renderForm(posts,res){
var data = ejs.render(template,{
posts: posts
});
res.writeHead(200,{'Content-Type': 'text/html'});
res.write(data);
res.end();
}
server.on('request',function(req,res){
if(req.method === 'POST'){
req.data = "";
req.on("readable",function(){
req.data += req.read();
});
req.on("end",function(){
var query = qs.parse(req.data);
posts.push(query.name);
console.log(posts);
renderForm(posts,res);
});
}else{
renderForm(posts,res);
}
});
req.data += req.read();
した時の文字列にnull
が入ってきていて、postsを表示すると「hogenull」とか「abcdnull」に。原因を探していたところ記事がヒットしたので、req.data += req.read() || '';
を試したらいけました
Author And Source
この問題について(Cloud9のNode.jsテンプレートでreq.read()した時にnullが入る), 我々は、より多くの情報をここで見つけました https://qiita.com/toC/items/6bccfb300ff1714ffe6c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .