7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cloud9のNode.jsテンプレートでreq.read()した時にnullが入る

Last updated at Posted at 2016-10-12

ドットインストールの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() || '';を試したらいけました :thumbsup:

情報元:nodejsのreadableイベントは最後にnullが来るかも

7
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?