Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running angular from node.js server

I have following files -

1) index.html

2) app.js (angular controllers here)

3) routes.js (I'm trying to load index.html from here - listening on localhost :3000)

4) index.css

5) node_modules folder

routes.js :

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(3000);

app.use("/node_modules", express.static('node_modules'));        
app.use("/public", express.static('public'));

    app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
    });

io.sockets.on('connection', function(socket){
    socket.on('send message', function(data){
        io.sockets.emit('new message', data);
    });
});

When I open index.html file normally by clicking on it from file explorer, it opens fine as expected.

enter image description here

But, when I run routes.js, to fetch the same index.html file, I get the raw HTML without angular effects. Why is this?

enter image description here

Thanks!

EDIT :

I can now access my index.css and app.js from localhost:3000/public/. I used app.use("/public", express.static('public')); in my routes.js.

But now I can only get css included in my page, but still looks like angular is not included. I couldn't see the tabs. Please look at above screenshot of index.html file with tabs.

How can I include angular? Isn't it included from the HTML itself?

enter image description here

index.html -

<html>
...
...
<link href="node_modules/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet"> 
<link href="public/index.css" rel="stylesheet"> 

<body>
...
...

<script src="node_modules/angular/angular.js"></script>
<script src="public/ui-bootstrap-tpls-0.13.1.js"></script>
<script src="node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script src="public/app.js"></script>

</body>
</html>

EDIT : I solved it by including

app.use("/node_modules", express.static('node_modules'));

in my routes.js file. So now express also uses that folder, so angular files in that folder are used to serve my index.html file. Now, running my localhost:3000/ gives me the expected result. Thanks!

like image 703
Nikhil Avatar asked Jul 31 '15 12:07

Nikhil


1 Answers

Looks like your static files (js/css) are not accessible through expressjs, you can check in a browser console if it's 404?

By the way did you add the directory where app.js stored as static in expressjs or is it located in the same directory as index.html?

Something like:

app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));

Alternatively you can add a route to your app.js:

app.get('/js/app.js', function(req, res){
  res.sendFile(__dirname + '/app.js');
});

but it's not recommended, just for the tests.

like image 103
teamnorge Avatar answered Sep 30 '22 00:09

teamnorge