Browsing:

Tag: angularjs

Nodejs and the MEAN stack for the .NET developer part 2

In the previous article we’ve set up the web application skeleton with Express for the reMember application and we wrote a first test to see if we can actually save an object to the database with Mongoose.

In an Express generated app, ‘app.js’ is the starting point of the application. (Like Global.asax or WebApiConfig in an ASP.NET MVC app).

Since the goal of this article is to write an api, we can clean it up a little.

  • We will not be using jade at this time, so we can clean out references to the view.
  • We can also clean out the ‘user’ lines because we are not going to use these.
  • We will comment out the routes as well and create a new default route to an index.html file
var express = require('express');

//!!don't need this:
//var routes = require('./routes');
//var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);

//!!don't need this, we're going to serve plain html:
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);

//!!change this as well to reflect our new folderstructure:
app.use(express.static(path.join(__dirname, '../public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

//!!don't need this (yet)
//app.get('/', routes.index);
//app.get('/users', user.list);

//!!add a default route
app.all('/', function(req, res) {
  res.sendfile('index.html', { root: "../public" });
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Now create an index.html file in /public:

<html>
<head>
<title>Still empty</title>
</head>
<body>
<h1>Still empty..</h1>
<p>But we're getting there..</p>
</body>
</html>

And start up the server with node app.js
You should now be able to browse to localhost:3000 and see the index.html.

Debugging

But what if you don’t and you see something like this:

/home/jacqueline/apps/reMember/server/app.js:37
});
^
SyntaxError: Unexpected token }
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
jacqueline@linuxlab:~/apps/reMember/server$ 

Then you probably forgot to close a curly brace or a quote. Stop node (ctrl+c), correct the changes and start again.
But wait, there’s an easier method.
With nodemon it is possible to debug changes on the fly.
Install it globally with npm install -g nodemon.

Now start app.js with nodemon app.js

Everytime you change and save a file the node server is automatically restarted. It crashed when something is from and it starts running as soon as you correct your mistakes:

nodemon

Take a look at http://localhost:3000 now:

stillempty

So that works.

Are we going to write that API or what?

Yes we are.
Delete all the files in the routes folder.
Create new file called api.js


//!!the C# equivalent would be: 
//using mongoose; 
//using member;

var mongoose = require('mongoose');
var Member = require('../models/Member');


//!! /members GET  (in ASP.NET MVC: public IEnumerable Get())

exports.members = function(req,res) {
  Member.find({}, function(err, data) {
      res.send(data);
    });
};

I’ve written the C#/.NET equivalents in the comments for convenience.

The Mongoose ‘find’ method signature is written in their API. For example:

// executes immediately, passing results to callback
MyModel.find({}, function (err, docs) {});

The result of the query will be put in ‘docs’, which is always the 2nd parameter.

The Mongoose API docs are a very good read and helped me enormously to understand how it works.

Mapping the mongoose functions to a route in app.js

We now need to map the exports.members function to the route /members.
This happens in app.js.

var express = require('express');
var http = require('http');
var path = require('path');

//!!add the Mongoose module:
var mongoose = require('mongoose');

var Member = require('./models/Member');

//!!add the path to the api.js file:
var api = require('./routes/api');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, '../public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

//!!connect to mongo:
mongoose.connect('mongodb://localhost:27017/local');

//!! map the /members route to the api.members function:

app.get('/members', api.members);

//default route
app.all('/', function(req, res) {
  res.sendfile('index.html', { root: "../public" });
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Restart node (or don’t of you’re running nodemon) and browse to http://localhost:3000/members.

grimm

I’ve added some Grimm characters.

Tip: use Postman to test the API.

The github repo for reMember is here.

Next time we’ll start building the frontend with Angularjs. (The ‘A’ in the MEAN stack).


ASP.NET Web API, Angularjs and MongoDb part 5

This is the sequel to this.

You can find the finished application here: https://github.com/jacqinthebox/AddressBook

angular

When I was creating this I was really confused about ‘the double MVC’ setup. The one that comes with ASP.NET and the one that comes with Angularjs.

It felt like what I was doing was bloathed and wrong.

I decided to start again from scratch, but this time with Node as the backend.

node


Getting started with ASP.NET API with MongoLab and Angularjs part 4

In my previous blogpost we created a Web API with a Mongodb backend. Now we’ll create a client application that consumes the API with a JavaScript framework.
That is obviously the way to go nowadays.

There is a plethora of Javascript frameworks to use and Angular.js is in fact the first one that I’ve tried, because it gets a lot of traction lately.

What are we creating?

Let’s try to make a single page application (SPA) where people can enter and lookup their contacts. Instead of the classic addressbooks, it is possible to enter Facebook pages, Twitter accounts and so on.
To make sure it looks nice we will be using Twitter Bootstrap.

Getting ready for Angular

First get the Angular.js and Twitter Bootstrap through the Nuget Package Manager Console:

Install-Package angularjs
Install-Package bootstrap

Then, create a folder named ‘app’ with the following subfolders:
-app
—css
—fonts
—img
—js
—lib

Then drag the css and angular etc to this new folder structure, like so:

2013-11-02 12_02_23-AddressBook - Microsoft Visual Studio

In case you are wondering why I am doing this. When I first started to look at Angular, I used Angular-seed as a boilerplate. I think that is a good startingpoint for organizing code.
Further, the Web API has nothing to do with the client code I’m going to write. I will not be using ASP.NET MVC routing and views with Razor, instead I will be using the routing and the controllers from the Angular framework. So that explains the separate ‘app’ folder in the project.

We need to configure the AddressBook application to start in the app folder though:

2013-11-03 09_45_19-AddressBook - Microsoft Visual Studio

I’ve also changed to port to 8000 so it’s easier to remember.

A little bit of Angular background info

This is a good introduction to Angular by Dan Wahlin. Be sure to check it out.

Angular uses modules to specify how a web application should be bootstrapped.
Modules break an application up into functional sections. For example, services, directives, controllers and filters that are specific to a particular application can be added to the application module.
Ehm.. What does that even mean!?
Well, controllers for front-end development serve a very similar purpose as controllers we know from ASP.NET MVC. Controllers present data to the views, via a scope. And Angular services are singletons objects or functions that carry out specific tasks common to web apps. A typical task for a service would be fetching data from a server.

At Thruzero I found a very good explanation of the Angular architecture:
Angular architecture

Getting started

In /app/js create a javascript file named app.js.
I will be adding all the javascript in there because this app is very trivial. Later I will break it up in several files (javascript files for controllers, for services etc.).

Let’s first declare the module:

//app/js/app.js:
var addressbookModule = angular.module('addressbookModule',[])

The ‘[ ]’ array thing is very important, because later we can inject other modules into this array.

Next we can add a controller to the addressbookModule. The first argument is the controller name,’WelcomeController’ and the second argument is a function, in which we pass in a $scope.
The scope is the ‘glue’ between the controller and the view. We can give the scope properties in the controller which will be presented to the view.

//app/js/app.js:
var addressbookModule = angular.module('addressbookModule',[])

addressbookModule.controller('WelcomeController', function ($scope) {
    $scope.title = "Welcome to your AddressBook";
 });

Finally, this is the view (/app/index.html):





    AddressBook





{{title}}

This is the result:

2013-11-02 13_32_13-Mozilla Firefox

What we just did:

  • We wired up Angularjs in our application by adding angular.js to our html file
  • We created a module named AddressBookModule as an Angular module.
  • Now we can chain Angular functionality to this module (routing, services, controllers etc).
  • We added a Controller.

It took a while for me to grasp all this. If you’re coming from a C# world the whole Javascript syntax is already confusing enough. All these ‘function() { }’ curly braces, hooks and semicolons confuse me. And if you forget to put a }); well then it just doesn’t work.
You can have anonymous functions with 30 miles of arguments!

The solution is: practice, practice, practice. Make stupid mistakes and blog about it.

Next time we’ll add some CRUD.