Vishal Vishal - 3 months ago 15
AngularJS Question

Why my files in public folder gets 404

I have a file structure like this:

ng
|---- controllers
| |----homeController.js
|---- modules.js
node-modules
|---- some modules here...
public
|---- css
| |---main.css
|---- js
| |---main.js
views
|---- index.html.ejs
package.json
server.js


Here is my server.js

var express = require('express');
var morgan = require('morgan');
var ejs = require('ejs');

var app = express();

app.use(morgan('dev'));

app.use(express.static(__dirname + 'public'));
app.set('view-engine', ejs)

app.get('/', function(req, res) {
res.render('index.html.ejs');
});

var server = app.listen(process.env.PORT || 3000, function() {
console.log('server is listening on Port: %d', server.address().port);
});


Now, In my index.html.ejs file:

<!DOCTYPE html>
<html lang="en">

<head>
<title>Mailer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/main.css">
</head>

<body ng-app="addressBookApp">

<h1>Sample Angular App </h1>

<script src="js/main.js"></script>
<script src="ng/modules.js"></script>
<script src="ng/controllers/homeController.js"></script>
</body>

</html>


How can I resolve ng folder so that I can reference my angular module and controllers?

Also, As if I run this server then I get error:

Why any files in public folder is not loaded?
I get 404 for main.js and main.css

Answer

If you want to serve files in ng directory you should make it public too:

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

Now, you can load the files that are in the ng directory:

http://localhost:3000/ng/controllers/homeController.js

By the way it's better to create a folder called app and put everything inside ng in this directory.

Comments