0

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?

2
  • make sure "../vendor/angular.js" exists. this could be the reason Commented Jul 9, 2014 at 13:09
  • 1
    you're missing app.listen(3000); in app.js. Then you can connect to localhost:3000 Commented Jul 10, 2014 at 15:38

4 Answers 4

3

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks Ben. I added that to my app.js file, but it is still not working. See my code edits above.
2

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>

1 Comment

Thanks for your help Gpx, but it is still not working. I made some changes to the code above. Any ideas?
1

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"
  }
}

1 Comment

Awesome Mick that worked great! So I was missing Angular routing, and listening on a port.
0

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.

2 Comments

Hey Ashok, thanks for trying to help but it is still not working. See my code edits above.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.