POST requests with Google DART, Node.js and MongoDB

Previously we have posted the article for Handling GET requests with Google DART, Node.js and MongoDB. Current post is an extension of the above post – now this time it is a POST request handling. We have posted in an separate article because we have found some of the critical things (which we will explain here) – worth to mention in this separate post.

we have written about some initial concepts about Google DART in

To make this possible, we have selected –

1> DART for client side development

2> Cross Domain Communication in between DART and Node.js

3> Node.js for server side development

4> Rest based web service creation with express.js

5> Database – MongoDb

6> Node.js MongoDb Module Extention (mongojs)

We have tried to create a Proof of Concept with Javascript based web server – Node.js, where we have focused on dealing with NoSql (MongoDB) with javascript based framework Node.js and Google DART on client side.

The code can be found in Github.

Architecture at a glance –

Dart Node Mongodb

So here are the steps –

Installation –

A> Download and install Node.js from here.

B> To Develop the application we need to install mongojs module for Node.js

Command – npm install mongojs (should be connected to internet)

C> We need to install express.js for node.js

Command – npm install express  (should be connected to internet)

Configuration Code –

Now, we will try to describe the code portion –

 
var application_root = __dirname,
    express = require("express"),
    path = require("path");

Here we have initialised the express.js within javascript variables in respect of Node.js concept.

 
var app = express();

Here we have initialised the express web server in app variable.

 
var databaseUrl = "sampledb"; 
var collections = ["things"]
var db = require("mongojs").connect(databaseUrl, collections);

Here we have made the connection to the mongodb database using the Node.js mongojs module extension library.

 
// Config

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

Here we have made the configuration related to express.js

Rest Services Code –

 
app.get('/api', function (req, res) {
  res.send('Our Sample API is up...');
});

Here we have made our first REST based web service and tested whether the express.js is up.

Our sample api will be  – http://127.0.0.1:1212/api (Get Method)

 
app.get('/getdartusers', function (req, res) {
	res.header("Access-Control-Allow-Origin", "http://127.0.0.1:3030");
	res.header("Access-Control-Allow-Methods", "GET, POST");
        // The above 2 lines are required for Cross Domain Communication(Allowing the methods that come as Cross           // Domain Request
	db.things.find('', function(err, users) { // Query in MongoDB via Mongo JS Module
	if( err || !users) console.log("No users found");
	  else 
	{
		res.writeHead(200, {'Content-Type': 'application/json'}); // Sending data via json
		str='[';
		users.forEach( function(user) {
			str = str + '{ "name" : "' + user.username + '"},' +'\n';
		});
		str = str.trim();
		str = str.substring(0,str.length-1);
		str = str + ']';
		res.end( str);
                // Prepared the jSon Array here
	}
  });
});

Here we have created another REST api to get all username from user collection and so have done the mongojs query.

Our sample api will be  – http://127.0.0.1:1212/getangularusers (Get Method)

Now the critical part – handling POST Request

We have seen the request is coming in server with two parts – one is HTTP OPTIONS method and another is HTTP POST Method.

The code for these are given below –


app.all('/insertdartmongouser', function(req, res, next) {

  if (req.method === 'OPTIONS') {
      console.log('!OPTIONS');

      var headers = {}; // Header values inclusion - OPTIONS handling
      // IE8 does not allow domains to be specified, just the *
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Max-Age"] = '86400'; // 24 hours
      headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
      res.writeHead(200, headers);
      res.end();
  } else {
	next(); // If the http request method is not 'OPTIONS' then go to next handling - which is 'POST' here.
  }
});

and the POST method code in n ode.js –


app.post('/insertdartmongouser', function (req, res){
    console.log("POST: ");
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
    console.log("got method"+req.method);
    var alldata = '';
    req.on('data', function(chunk) { // Getting the body information in node.js request 'on data arrive' condition
	console.log("Received body data:"); // this is an asynchronous event in node.js post
	console.log(chunk.toString());
	alldata = chunk.toString();
	var jsonData = JSON.parse(alldata);
	console.log(jsonData.username);
	console.log(jsonData.password);
	console.log(jsonData.email);
	db.things.save({email: jsonData.email, password: jsonData.password, username: jsonData.username}, function(            err, saved) {  // Calling the mongojs function
	    if( err || !saved ) res.end( "User not saved"); 
	    else res.end( "User saved");
	});
   });
});

Here we have made a POST request to create an user via REST calling.

Our sample api will be – http://127.0.0.1:1212/insertdartmongouser(Post Method)

 
// Launch server
app.listen(1212);

We have made the server to listen at 1212 port.

Now run node appmongodbdart.js from command shell.

DART part –

Below is the code in DART source code –

// Importing Core DART libraries
import 'dart:html';
import 'dart:json' as json;
import 'package:web_ui/web_ui.dart';

var wordList; // Variables in DART

var saveUser;
var httpPostRequest;
@observable String serverResponse = '';

void main() { // Main Entrypoint of the Program
    wordList = query('#userList');  // Assigning variable to 'wordlist' DOM Element
    query('#getUsers').onClick.listen(makeRequest); // Register 'makeRequest' to an event listener
    query('#saveUser').onClick.listen(makePostRequest);
}

// A get Request
void makeRequest(Event e) {
    var path = 'http://127.0.0.1:1212/getdartusers'; // Asynchronous request path (Cross Domain Request)
    var httpRequest = new HttpRequest();
    httpRequest
        ..open('GET', path)
        ..onLoadEnd.listen((e) => requestComplete(httpRequest))
        ..send(''); // Preparing the http request and send to server
}

//A post request
void makePostRequest(Event e) {
  //var path = 'sample.json';
  e.preventDefault();
  print ('post request');
  var path1 = 'http://127.0.0.1:1212/insertdartmongouser';// URL for the REST Calling
  httpPostRequest = new HttpRequest();
  httpPostRequest.onReadyStateChange.listen(onData(e)); 

  httpPostRequest.open('POST', path1);
  httpPostRequest.send(userJsonData());
}

String userJsonData() {
  // Put date in the map.
  print ('userJsonData');

  var usernm = query('#usernameid');
  var passwd = query('#passwordid');
  var eml = query('#emailid');

  theData['username'] = usernm.value;
  theData['password'] = passwd.value;
  theData['email'] = eml.value;
  usernm.value='';
  passwd.value='';
  eml.value='';
  print("mydata="+json.stringify(theData));
  return json.stringify(theData);
}

void onData(Event e) {
  print ('onData');

  if (httpPostRequest.readyState == HttpRequest.DONE && httpPostRequest.status == 200) {
      // Data saved OK.
      serverResponse = httpPostRequest.responseText;
      print (serverResponse);
  } else if (httpPostRequest.readyState == HttpRequest.DONE &&
      httpPostRequest.status == 0) {
      // Status is 0...most likely the server isn't running.
      serverResponse = 'No server';
      print (serverResponse);
  }
}

requestComplete(HttpRequest request) {
    print(request.status);
    print(request.statusText);

    if (request.status == 200) {
        List samples = json.parse(request.responseText); // Parsing JSON and put in DART List
        wordList.children.clear();
        for (int i = 0; i < samples.length; i++) {
            var myObject = samples[i];
            wordList.children.add(new LIElement()..text = myObject['name']); // Adding data to DOM Element
           }
     } else {
           wordList.children.add(new LIElement()..text =
               'Request failed, status={$request.status}');
     }
}

References which are really helpful to write this solution –
https://gist.github.com/nilcolor/816580
http://stackoverflow.com/questions/17689986/jquery-ajax-sending-both-options-and-post-how-to-handle-with-express-js-node-j
http://blog.frankgrimm.net/2010/11/howto-access-http-message-body-post-data-in-node-js/

DART Code Reference and HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Users</title>
        <link rel="stylesheet" href="<<css file reference>>">
    </head>
    <body>
         <h1>All Users</h1>
         <button id="getUsers">Get Users</button>
         <div>
              <ul id="userList">
              </ul>
         </div>
         <div>
             <h1>Enter User :</h1>
             <form name="dartform" id="dartform" method="POST" action="http://127.0.0.1:1212/insertdartmongouser">
                  Name : <input type="text" name ="username" id="usernameid" value="" />
                  Password : <input type="text" name ="password" id="passwordid" value="" />
                  Email : <input type="text" name ="email" id="emailid" value="" />
                  <button id="saveUser" >Save</button>
             </form>
         </div>
         <script type="application/dart" src="users.dart"></script> <!--Dart file reference -->
         <!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
         <script src="packages/browser/dart.js"></script>
    </body>
</html>

We have used the dart asynchronous code to send the user data model from REST communication and sent to node server to get data in MongoDB.

Reader can download the complete source-code in GitHub.

Also if you find this article helpful, you can connect us in Google+ and Twitter.

Want to get updates? Subscribe here

Enter your email address:

Delivered by FeedBurner

2 thoughts on “POST requests with Google DART, Node.js and MongoDB

Leave a Reply

Your email address will not be published. Required fields are marked *