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

Categories

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

node.js + express + socket.io cannot load javascript files into index.html

I'm developing an application and the server is currently set up and working well.

This is the index.html that shows when you access the server:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
  </head>
  <body>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script type="text/javascript" src="./client.js"></script>
    <script type="text/javascript" src="./main.js"></script>
  </body>
</html>

However I get a 404 error "Failed to load resource: the server responded with a status of 404 (Not Found)" when importing those javascript files, which are in the same directory.

Here is my server code:

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

app.get('/', function(req, res){
  res.sendFile(__dirname+'/index.html'); // DO I NEED TO SEND THE OTHER FILES HERE ASWELL?
});

io.on('connection', function(socket){
  console.log('a user connected');

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });

});

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

Thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If the HTML file is located in the same path as the scripts are, then use relative path like src = "main.js". If it still doesn't work, maybe it's Express' fault.

Add the codes below into your app.js:

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

And the scripts can be accessed from the path relative to /scripts- e.g. main.js from http://yourdomain/script.js but not from http://yourdomain/scripts/main.js. Sorry for my English.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...