node.js http server and request client

Objective: Write a node http server and client. The server will provide post, get, put and delete services to create, read, update and delete (CRUD) rows in a mysql table students that stores students’ name and grade. The client will make requests to the server for post, get, put and delete operations. Besides the external modules for mysql and request, no other external modules should be used.
Prerequsites: Node js and mysql database should have been installed on your computer. The walk through assumes you are using linix or mac.

1. Create mysql table for the students table.

CREATE DATEBASE test;
USE test;
CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `grade` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

2. Create a folder, 2 js files (server.js and client.js), and install 2 node external modules.

mkdir serverapp
cd serverapp
touch server.js
touch client.js
sudo npm install mysql request

3. server.js, provide POST, GET, PUT and DELETE services.

//Import modules and declare global variables, update the mysql connecion to yours
var http = require('http'),
	url = require('url'),
	qs = require('querystring'),
	mysql = require('mysql'),
	pool = mysql.createPool({host:'localhost', user:'your_mysql_username', password:'your_mysql_password', database:'test'}),
	port = 3333,        
	postQuery = "INSERT INTO students(name, grade) VALUE (?, ?)",
	getQuery = "SELECT * FROM students WHERE id=?",
	putQuery = "UPDATE students SET grade=? WHERE id=?",
	deleteQuery = "DELETE FROM students WHERE id=?";

//Create the server listening to port 3333, all requests come through this first. 
//It parses the data and routes the request to appropriate functions
http.createServer(function (req, res) {
	console.log("There is an incoming request...");
    var urlParts = url.parse(req.url);
    	req.urlParts = urlParts,
		reqPath = urlParts.pathname;
 	if (reqPath !== '/api/student/') {
    	res.writeHead(400, {'Content-type':'text/plain'});
    	res.end("Bad request!");	
	} else {
 		parseData(req, res, function() {
		    switch(req.method) {
		        case "POST":
		            postReq(req, res);
		            break;
		        case "GET":
		            getReq(req, res);
		            break;
		        case "PUT":
		        	putReq(req, res);
		        	break;
		        case "DELETE":
		            deleteReq(req,res);
		            break;
		        default:
		            notFound(req,res);
		            break;
		    }	
		});
	};
}).listen(port);
console.log("Server running at http://localhost:" + port);

//Parse the incomning request data 
function parseData(req, res, cb) {
    var body = '';
	req.on('data', function (data) {
		body += data;
		if (body.length > 1e6) {
			req.connection.destroy();
		}
	});
	req.on('end', function () {
	    req.body = qs.parse(body);
	    console.log(req.body);
	    req.urlParams = qs.parse(req.urlParts.query);
	    cb(req, res);
	});   	
}

//A simple mysql resonse handler, write the result from myql query to response
function mysqlResponseHandler(err, result, req, res) {
  	if (err) {
  		console.log(err);
    	res.writeHead(400, {'Content-type':'text/plain'});
    	res.end(req.method + " failed!");
	} else {
		res.writeHead(200, {'Content-type':'application/json'});
   		res.end(JSON.stringify(result));
	}	
}

//Processing POST request
function postReq(req, res) {
	var	q = mysql.format(postQuery, [req.body.name, req.body.grade]);
  	pool.query(q, function (err, result) {
  		mysqlResponseHandler(err, result, req, res)
  	});
}

//Processing GET reqest
function getReq(req, res) {
    var q = mysql.format(getQuery, [req.urlParams.id]);
  	pool.query(q, function (err, result) {
  		mysqlResponseHandler(err, result, req, res);
  	});
}

//Processing PUT request
function putReq(req, res) {
	var q = mysql.format(putQuery, [req.body.grade, req.body.id]);
	pool.query(q, function (err, result) {
  		mysqlResponseHandler(err, result, req, res)
	});
}

//Processing DELETE request
function deleteReq(req, res) {
	var q = mysql.format(deleteQuery, [req.body.id]);
	pool.query(q, function (err, result) {
  		mysqlResponseHandler(err, result, req, res)
	});
}

//not found resonse
function notFound(req, res) {
    res.writeHead(404, {'Content-type':'text/plain'});
   	res.end("Resource not found!");	
}

4. client.js, request POST, GET, PUT and DELETE services.

var request = require('request');

//do POST request
function doPOST() {
	var postData = {
			url: 'http://localhost:3333/api/student/', 
			form: {'name': 'Amy', 'grade': 99}
		};
	request.post(postData, function (err, res, body) {
		console.log(res.body); 
	});
}

//do GET request, getting the student where the id=1
function doGET() {
	request.get('http://localhost:3333/api/student/?id=1', function (err, res, body) {
		console.log(res.body);
	})
}

//do PUT request, update the student's score to 90 where the id=1
function doPUT() {
	var putData = {
			url: 'http://localhost:3333/api/student/', 
			form: {'id': 1, 'grade': 90}
		}
	request.put(putData, function (err, res, body) {
		console.log(res.body);
	})
}

//do DELETE request, delete the student where the id=1
function doDELETE() {
	var delData = {
			url: 'http://localhost:3333/api/student/', 
			form: {'id': 1}
		}
	request.del(delData, function (err, res, body) {
		console.log(res.body);
	})
}

doPOST();
doGET();
doPUT();
//doDELETE();

5. Start ther server.

node server.js &

6. Run the client to make requests.

node client.js

Search within Codexpedia

Custom Search

Search the entire web

Custom Search