Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - nodejs/express include local js file

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...