Node.js HTML page error 404 while getting javascri

2019-07-29 22:39发布

问题:

Im working with node.js and I wanted my HTML file to GET javascript files.

This is the file i'm running with node.js called server.js:

var app = require('express')();
var http = require('http').Server(app);

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Very simple code made to host index.html. This HTML file has some script tags:

<script type="text/javascript" src="./A.js"></script>

<script type="text/javascript" src="./B.js"></script>

<script type="text/javascript" src="./C.js"></script>

And the problem is that when i run server.js and I go to the browser I get this errors on the console:

GET http://localhost:3000/A.js 
GET http://localhost:3000/B.js 
GET http://localhost:3000/C.js 404 (Not Found)

404 error not found

The files are all in the same directory and I don't understand why it doesn't get the scripts.

回答1:

Your server.js does not know how to handle anything besides requests for the root page. (Even http://localhost:3000/index.html will fail with a 404.)

Add the express.static middleware to serve files from a directory:

var express = require('express');
var app = express();
var http = require('http').Server(app);

express.static('public')

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Now any files in the public folder will be served as you intend. (Move your *.js files to a sub-folder named public)

See the HyperDev default project template for a good interactive example of this in action.



回答2:

Try looking at the Express1 Documentation for serving static files.

You're serving your index file with these lines:

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

You can serve js files the same way or by putting them in a public folder and adding app.use(express.static('public')).

Then you can reference them as public/A.js