Avi Kenjale
Avi Kenjale

Reputation: 2784

Nodejs Express not loading script files

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.

Upvotes: 1

Views: 3482

Answers (2)

Avi Kenjale
Avi Kenjale

Reputation: 2784

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.

Upvotes: 2

t.niese
t.niese

Reputation: 40882

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'));

Upvotes: 1

Related Questions