I am making a blog as a learning exercise - see github project - from scratch in node.js. I have an html form that looks like this with input and a textarea fields. On submit, each is supposed to be parsed as title and 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 an index.js file I have my routes defined and some utility functions to help me parse the data out of the 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'
});
// the parseBody is defined below this function
// title and content should get logged to the console, but 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)); // I may be misunderstanding the usage of the 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 that it's because your parseBody() buffer is starting with a space and title is the first field in your form. So your buffer ends up being something like:
title=foo&content=bar
instead of
title=foo&content=bar
Change var body = " "; to var body = "";.