Previously we have posted the article for Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module).
[1]

Also we have written about some initial concepts about Google DART in

Currently we are learning Google DART and tried some experiment for connecting the Client layer made with Google DART and  Node.js MongoDB based server.

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.

Architecture at a glance -

Dart Node Mongodb

So here are the steps -

Installation -

A> Download and install Node.js from here[2].

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  - https://127.0.0.1:1212/[3]api (Get Method)

 
app.get('/getdartusers', function (req, res) {
	res.header("Access-Control-Allow-Origin", "https://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  - https://127.0.0.1:1212/getangularusers[4] (Get Method)

 
// Launch server
app.listen(1212);

We have made the server to listen at 1212 port.

Now run node appmongodbdart.js from command shell.

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

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
}

// A get Request
void makeRequest(Event e) {
    var path = 'https://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
}

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}');
     }
}
<!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>
         <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="https://d1zflb13a857us.cloudfront.net/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.

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

COM_AUTOTWEET_VIEW_FEED_REFERENCES

  1. ^ Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module) (www.phloxblog.in)
  2. ^ here (nodejs.org)
  3. ^ https://127.0.0.1:1212/ (127.0.0.1)
  4. ^ https://127.0.0.1:1212/getangularusers (127.0.0.1)
  5. ^ Google+ (plus.google.com)
  6. ^ Twitter (twitter.com)

Read more

© 2024 Extly, CB - All rights reserved.