Mikyas TADESSE
Mikyas TADESSE

Reputation: 159

Angular code not working with express

Am having a problem with angular. My angular code works fine when i run it alone but doesn't work when i access it on localhost with express. What happens is that it displays the html file alone. my server code is : *

var express = require('express'),
    app     = express();
app.get('/', function(req, res) {
    res.sendfile('./app/client/main.html');
});
app.listen(3000, function() {
    console.log('I\'m listening...');
})

my angular controller code is

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

app.controller('mainController', function($scope){

     $scope.posts = [];
     $scope.newPost = {created_by: '', text: '', create_at: ''};

      $scope.post = function(){
        $scope.newPost.created_at = Date.now();
        $scope.posts.push($scope.newPost);
        $scope.newPost = {created_by: '', text: '', created_at: ''};
  };
});

and the angularised html code is

<!--main.html-->
<!doctype html>
<html>
  <head>
    <title>Tiks</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    <script src="javascripts/tiks.js"></script>
  </head>
  <body ng-app="tiks">
    <div id='main' ng-controller="mainController">
     <form ng-Submit="post()">
        <input required type="text" placeholder="Your name" ng-model="newPost.created_by" /> 
        <textarea required maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
        <input class="button" type="submit" value="Chirp!" />
      </form>
      <div id="post-stream">
        <h4>Tiks Feed</h4>
              <div class='post' ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
            <p>{{post.created_by}} says {{post.text}} at {{post.created_at}}</p>
            </div>
        </div>
      </div>
    </div>
  </body>
</html>

please help

Upvotes: 1

Views: 101

Answers (1)

Felipe Sabino
Felipe Sabino

Reputation: 18225

Your HTML is asking for javascripts/tiks.js at the script tag, but your server has no route configured to serve it.

Try checking the requests being done, for example using Google Chrome Developer tools network tab, and you will probably see a 404 error when the .js file is requested.

You should use express.static to serve files from folder instead of defining specific resources individually as you are doing for ./app/client/main.html.

app.use('/', express.static(__dirname + '/app/client/'));

then you would have to access http://localhost/main.html to access it.

Upvotes: 2

Related Questions