node.js + express + socket.io 无法将 javascript 文件加载到 index.html [英] node.js + express + socket.io cannot load javascript files into index.html

查看:25
本文介绍了node.js + express + socket.io 无法将 javascript 文件加载到 index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,服务器目前已设置好并且运行良好.

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

这是访问服务器时显示的index.html:

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>

但是,在导入位于同一目录中的那些 javascript 文件时,我收到 404 错误无法加载资源:服务器响应状态为 404(未找到)".

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.

这是我的服务器代码:

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

谢谢!

推荐答案

如果 HTML 文件与脚本位于同一路径,则使用相对路径,如 src = "main.js".如果还是不行,可能是快递的问题.

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.

将以下代码添加到您的 app.js 中:

Add the codes below into your app.js:

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

并且可以从相对于 /scripts 的路径访问脚本 - eg main.js from http://yourdomain/script.js 但不是来自 http://yourdomain/scripts/main.js.对不起我的英语.

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.

这篇关于node.js + express + socket.io 无法将 javascript 文件加载到 index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆