1

I am trying to run a angular app thru node-express.

1 File Structure

AngularNode
    public
        /core.js
        /index.html
    project.json
    server.js

2 server.js

var express  = require('express');
var app = express();

app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

// listen (start app with node server.js) ======================================
app.listen(8000);
console.log("App listening on port 8000"); 

3 index.html

<html>
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>    
     <script src="./core.js"></script>
........

4 core.js

angular.module('MySystem',[])
.controller('AppController',['$scope',function($scope){
    $scope.Name ="Testing Text";
}]);

When I tried to run this app using node server.js this, index.html file is getting loaded properly, however this is not detecting or loading core.js file. and I am getting following errors

Uncaught SyntaxError: Unexpected token <           core.js:1
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381)   angular.js:38

Now, when I open index.html file directly from explorer, this is working OR when same code I move from core.js to inline html, under <head> with <script> block it is working.

I am not sure, why core.js not detecting or loading when I run thru node.

2 Answers 2

2

Got the Solution with few modifications:

1 Added line in server.js app.use(express.static(__dirname + '/public')); after line var app = express();

2 Case correction(Capital 'f') for function from res.sendfile('./public/index.html'); to res.sendFile('./public/index.html');

Now I can see core.js is detected and working fine.

Sign up to request clarification or add additional context in comments.

1 Comment

One more observation and fix: With the above code for res.sendFile('./public/index.html');, node console throws error TypeError: path must be absolute or specify root to res.sendFile to fix this modify as per ('./public/index.html',{"root": __dirname});
1

The app.get('*', function(req, res) { is a catch all rule for all get request and will also match the ./core.js request. So for the ./core.js your express app will also send the html file.

You should use express.static instead:

var express  = require('express');
var app = express();

app.use(express.static('./public'));

Comments

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.