Permalink
Browse files

Added the code to process New Post form submits

  • Loading branch information...
croach committed Mar 7, 2013
1 parent 3fc360b commit 1101901ab753a4d5179278c654310f65f208fbda
Showing with 41 additions and 5 deletions.
  1. +1 −0 .gitignore
  2. +4 −0 README.md
  3. +36 −5 app.js
View
@@ -0,0 +1 @@
+node_modules
View
@@ -3,6 +3,10 @@ Node.js Blog Engine
This repository contains the source code for the Nettuts+ series on web development with Node.js.
+### part-03
+
+In this episode, we learned about events and added the backend code to process a New Post form submit.
+
### part-01
In this episode, the first route and view were added as well as some basic directory structure.
View
41 app.js
@@ -1,6 +1,7 @@
var http = require('http');
var url = require('url');
var fs = require('fs');
+var qs = require('querystring');
var newPostFormHTML = fs.readFileSync('views/post/new.html');
@@ -11,21 +12,51 @@ function renderNewPostForm(request, response) {
response.end(newPostFormHTML);
}
+function addNewPost(request, response) {
+ parseBody(request, function(body) {
+ console.log(body);
+ var post = {
+ title: body.title,
+ content: body.content
+ }
+ console.log('Title: ' + post.title);
+ console.log('Content: ' + post.content);
+ })
+ response.end();
+}
+
+// Utils
function render404(request, response) {
response.writeHead(404);
response.end('404 File not found');
}
+function parseBody(request, callback) {
+ var body = '';
+ request.on('data', function(chunk) {
+ body += chunk;
+ });
+ request.on('end', function() {
+ callback(qs.parse(body));
+ });
+}
+
+// Routes
+var newPostFormRegex = new RegExp('^/posts/new/?$');
+var newPostRegex = new RegExp('^/posts/?$');
+
+// Server
var server = http.createServer(function(request, response) {
- var newPostFormRegex = new RegExp('^/posts/new/?$');
var pathname = url.parse(request.url).pathname;
if (newPostFormRegex.test(pathname)) {
- renderNewPostForm(request, response);
+ renderNewPostForm(request, response);
+ } else if (newPostRegex.test(pathname)) {
+ addNewPost(request, response);
} else {
- render404(request, response);
- }
+ render404(request, response);
+ }
});
server.listen(8000);
-console.log('Listening on http://127.0.0.1:8000');
+console.log('Listening on http://127.0.0.1:8000');

0 comments on commit 1101901

Please sign in to comment.