您的位置:首页技术文章
文章详情页

node.js - node项目找不到文件,index.js输出index.html

【字号: 日期:2023-10-10 14:11:03浏览:89作者:猪猪

问题描述

node.js - node项目找不到文件,index.js输出index.html

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’);});io.on(’connection’, function(socket){ console.log(’a user connected’);});http.listen(80, function() { console.log(’listening on *:80’);});

这是index.js源码,然后访问localhost

node.js - node项目找不到文件,index.js输出index.htmljquery找不到,socket.io.js倒是找到了。。。。这是index.html引入部分

node.js - node项目找不到文件,index.js输出index.html

问题解答

回答1:

我理解你的疑问有两个问题

为什么能找到/socket.io/socket.io.js, 这是因为如果Socket.io服务监听在你的http服务上,它会自动提供http://localhost:<port>/socket.io/socket.io.js这条路由(其实是拦截了所有/socket.io开头的请求, 并且请求的socket.io.js会被解析到socket.io-client/socket.io.js,所以你可以看看你前端获取到的js,其实是socket.io-client模块里面的文件,并不是socket.io模块里面的)。你不需要复制到对外的静态文件目录,或者手工提供该服务。

为什么你自己的/js/jquery-2.0.3.min.js却找不到,因为这个静态文件服务,没有模块给你提供,所以你需要自己手动提供,在你上面的index.js代码稍微改造一下,结果如下:

//改动一下, 提出expressvar express = require(’express’)var app = express();var http = require(’http’).Server(app);var io = require(’socket.io’)(http);//提供静态文件服务,这样就能找到你的`jquery-2.0.3.min.js`文件app.use(express.static(__dirname));app.get(’/’, function(req, res){ res.sendFile(__dirname + ’/index.html’);});io.on(’connection’, function(socket){ console.log(’a user connected’);});// 最好不要直接监听在80端口,改成8888http.listen(8888, function() { console.log(’listening on *:8888’);});

备注:最好不要直接监听在80端口,你可以监听在其他端口,然后挂一个nginx做为反向代理,这样的处理方式可能更加缓和一点。 直接监听在80端口太暴力了!个人意见,希望对你有帮助。

标签: HTML