Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here is my current folder structure

css
   app.css
js
  app.js
node-modules
index.html
node-server.js
package.json

The node-server is hosting index.html, but I can't figure out how to get the app.js and app.css files to get loaded.

index.html loads them with:

<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>

Here is the error message:

Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server 
responded with a status of 404 (Not Found)

I know i need to require or load module or something, just can't figure out what.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

Reason Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.

Solution(Manual):

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

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

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

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

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

app.listen(8080);

Better Solution:

Directory Structure:

public
 css
   app.css
 js
  app.js
 index.html

CODE:

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

// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));

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

app.listen(8080);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...