html5 - why isn't html form post data getting correctly parsed in node.js app? -
i making blog learning exercise - see github project - scratch in node.js. have html form looks input
, textarea
fields. on submit, each supposed parsed title
, content
, respectively.
<!doctype html> <html> <head> <title> post form </title> <link href="/css/master.css" rel="stylesheet" type="text/css" /> </head> <body> <h1> new post </h1> <form method="post" action="/posts" id="new_post" class="new_post"> <div class="field"> <label for="post_title">title</label><br> <input type="text" name="title" id="post_title" size="30" /> </div> <div class="field"> <label for="post_content">content</label><br> <textarea name="content" cols="40" rows="20" id="post_content"></textarea> </div> <div class="actions"> <input type="submit" value="create post" id="post_submit" /> </div> </form> <p><br> <a href="/home">back</a> </p> </body> </html>
in index.js file have routes defined , utility functions me parse data out of submitted information.
var http = require('http'), url = require('url'), fs = require('fs'), qs = require('querystring'); // html file cache var homehtml = fs.readfilesync('views/post/home.html'); var newhtml = fs.readfilesync('views/post/new.html'); var postshtml = fs.readfilesync('views/post/posts.html') // render functions ... function renderpostform(request, response) { response.writehead(200, { 'content-type': 'text/html; charset=utf-8' }); response.end(newhtml); } function addnewpost(request, response) { response.writehead(200, { 'content-type': 'text/html; charset=utf-8' }); // parsebody defined below function // title , content should logged console, title comes out title: undefined // content works fine parsebody(request, function(body) { var post = { title: body.title, content: body.content } console.log("title: " + post.title); console.log("content: " + post.content); }); response.end(postshtml); } // utils ... function parsebody(request, callback) { var body = " "; request.on('data', function(chunk) { body += chunk; }); request.on('end', function() { callback(qs.parse(body)); // may misunderstanding usage of parse function }); } // routes var homeregex = new regexp('^/?$'); var newregex = new regexp('^/posts/new/?$'); var postsregex = new regexp('^/posts/?$'); // server var server = http.createserver(function(request, response){ var pathname = url.parse(request.url).pathname; if (homeregex.test(pathname)) { renderhome(request, response); } else if (newregex.test(pathname)) { renderpostform(request, response); } else if (postsregex.test(pathname)) { addnewpost(request, response); } else { render404(request, response); } }); server.listen(3000);
i'm betting it's because parsebody()
buffer starting space , title
first field in form. buffer ends being like:
title=foo&content=bar
instead of
title=foo&content=bar
change var body = " ";
var body = "";
.
Comments
Post a Comment