Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am following the lessons on egghead.io trying to learn Angular. This lesson is about $http, and for some reason I can’t get a basic Expressjs/Angular app running.

Lesson link: https://egghead.io/lessons/angularjs-http

Here is my directory stucture:

app.js
public/
    index.html
    main.js
package.json
node_modules/
bower_components/

Here are my files:

public/index.html

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="utf-8">
  <title>Egghead Videos</title>
  <link rel="stylesheet" href="../vendor/foundation.min.css">
</head>
<body ng-app="app" ng-controller="AppCtrl as app">

<input type="text" ng-model="app.person.firstName" />
  <input type="text" ng-model="app.person.lastName" />
  <input type="button" ng-click="app.addPerson(app.person)" />

  <ul>
    <li ng-repeat="person in app.people">
        {{person.firstName}} {{person.lastName}}
    </li>
  </ul>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

var express = require('express');
var http = require('http');
var cors = require('cors');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cors());
app.set('port', 3000);

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/bower_components'));

var data = [
  {"firstName": "Jeff", "lastname": "Winger"},
  {"firstName": "Troy", "lastname": "Barnes"},
  {"firstName": "Britta", "lastname": "Perry"},
  {"firstName": "Abed", "lastname": "Nadir"}
];

app.get('/users', function(req, res) {
    res.send(data);
});
app.post('/users', function(req, res) {
    res.send(req.body);
});

public/main.js

var app = angular.module("app", []);

app.controller("AppCtrl", function($http) {
    var app = this;
    $http.get("http://localhost:3000/users")
      .success(function(data) {
        app.people = data;
      })

    app.addPerson = function(person) {
        $http.post("http://localhost:3000/users", person)
          .success(function(data) {
            app.people = data;
          })
    }
})

package.json

{
  "name": "users-app",
  "description": "users test app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "latest",
    "body-parser": "*",
    "cors": "*"
  }
}

So I made some changes from last time based on the comments, but it is still not working.

To run it I am typing "node app.js" in the command line. Is that correct, or should I be typing node “public/main.js” to run the app? I am a little confused about that part.

When I type "node app.js" nothing happens and the browser says it can’t connect at localhost. When I type "node public/main.js" it says "angular not defined".

Any ideas?

share|improve this question
    
make sure "../vendor/angular.js" exists. this could be the reason –  Mritunjay Jul 9 '14 at 13:09
1  
you're missing app.listen(3000); in app.js. Then you can connect to localhost:3000 –  jonnyynnoj Jul 10 '14 at 15:38

4 Answers 4

up vote 1 down vote accepted

The Egghead.io code had quite a few omissions. The http server was not listening on any port, bodyparser.json middleware was required and issues on the client.

The following will work for you.

>npm install

>node server

browse to //localhost:3000

File Structure:

server.js (I prefer instead of app.js for Node/Express server code)
public/index.html
      /js/app.js

package.json
node_modules/

SERVER.JS

/* ========================================================== 
External Modules/Packages Required
============================================================ */
var express = require('express');
var http = require('http');
var cors = require('cors');
var bodyParser = require('body-parser');
var logger = require('morgan');

/* ========================================================== 
Create a new application with Express
============================================================ */
var app = express();

/* ========================================================== 
serve the static index.html from the public folder
============================================================ */
app.use(express.static(__dirname + '/public')); 

/* ========================================================== 
Use Middleware
============================================================ */
//app.use(bodyParser.urlencoded({
//  extended: true
//}));

app.use(bodyParser.json({
  extended: true
}));

app.use(cors());
app.use(logger('dev'));

/* ========================================================== 
Port the server will listen on
============================================================ */
app.set('port', 3000);


var data = [
  {"firstName": "Jeff", "lastname": "Winger"},
  {"firstName": "Troy", "lastname": "Barnes"},
  {"firstName": "Britta", "lastname": "Perry"},
  {"firstName": "Abed", "lastname": "Nadir"}
];

app.get('/users', function(req, res) {
    res.send(data);
});

app.post('/users', function(req, res) {
    res.send(req.body);
});

/* ========================================================== 
Bind to a port and listen for connections on it 
============================================================ */
var server = app.listen(app.get('port'), function() {
    console.log('Listening on port %d', server.address().port);
    console.log("========LISTENING On Port 3000=========")
});

INDEX.HTML

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="utf-8">
  <title>Egghead.io</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>

<body ng-app="app" ng-controller="AppCtrl as app">

  <input type="text" ng-model="app.person.firstName" />
  <input type="text" ng-model="app.person.lastName" />
  <input type="button" ng-click="app.addPerson(app.person)" />

  <ul>
    <li ng-repeat="person in app.people">
        {{person.firstName}} {{person.lastName}} 
    </li>
  </ul>


  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.min.js"></script>
  <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

APP.JS (save under /public/js)

/*================================================
Module
================================================*/
var app = angular.module("app", ['ngRoute']);

/*================================================
Controller
================================================*/
app.controller("AppCtrl", function($http, $scope) {

    var app = this;

    $http.get("http://localhost:3000/users")
      .success(function(data, status, headers) {
        console.log("http status code= "+status);
        console.log("data from server= "+JSON.stringify(data));
        app.people = data;
      })

    app.addPerson = function(person) {

        $http.post("http://localhost:3000/users", app.person)          
          .success(function(data, status, headers) {
            console.log("http status code= "+status);
            console.log("data from server= "+JSON.stringify(data));
            app.people.push(data);
            console.log("new app.people= "+ app.people);
          })

          .error(function(data, status, headers, config) {
            console.log("Error with post" + status);
          })
    }
});

PACKAGE.JSON

{
  "name": "Angular-HTTP-Example",
  "version": "0.0.1",
  "description": "From Egghead Example",
  "main": "node server.js",
  "author": "Mick",
  "dependencies": {
    "express": "4.2.0",
    "morgan": "~1.0.1",
    "body-parser": "~1.0.2"
  }
}
share|improve this answer
    
Awesome Mick that worked great! So I was missing Angular routing, and listening on a port. –  Caleb Jul 15 '14 at 13:00

You need to move your client-side files to a folder (public in this example) and add the middleware to serve static files, then correct your paths.

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/bower_components'));
share|improve this answer
    
Hey thanks Ben. I added that to my app.js file, but it is still not working. See my code edits above. –  Caleb Jul 10 '14 at 15:28

You load Angular from ../vendor/angular.js

<script type="text/javascript" src="../vendor/angular.js"></script>

but looking at your folder structure it should be in bower_components.

Anyway you can simply load Angular from a CDN:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
share|improve this answer
    
Thanks for your help Gpx, but it is still not working. I made some changes to the code above. Any ideas? –  Caleb Jul 10 '14 at 15:28
    
Do you get any error in the browser console? –  Gpx Jul 11 '14 at 8:44

Check if you are also getting a 404 error for the angular.js library or add a appropriate source for the library, using a CDN or using bower and setting it as public dir.

share|improve this answer
    
Hey Ashok, thanks for trying to help but it is still not working. See my code edits above. –  Caleb Jul 10 '14 at 15:29
1  
If you are learning angular js only, you can put all your code inside a apache server or nginx server, and get rid of the hassle of setting up a node server just to serve static http files. –  Ashok Kumar Sahoo Jul 17 '14 at 9:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.