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

查看:125
本文介绍了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>

但是我收到404错误加载资源失败:服务器响应状态为404(没有找到)导入那些位于同一目录中的JavaScript文件时。

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。如果它仍然不起作用,也许是Express'错误。

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 main.js 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天全站免登陆