search

Home  >  Q&A  >  body text

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


jquery找不到,socket.io.js倒是找到了。。。。
这是index.html引入部分

PHP中文网PHP中文网2780 days ago499

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:53:25

    I understand your question and there are two questions

    1. Why can you find /socket.io/socket.io.js? This is because if the Socket.io service is listening on your http service, it will automatically provide the http://localhost:<port>/socket.io/socket.io.js route (actually intercepting all the routes starting with /socket.io request, and the requested socket.io.js will be parsed to socket.io-client/socket.io.js, so you can see that the js obtained by your front end is actually a file in the socket.io-client module, not a file in the socket.io module). You don't need to copy to an external static file directory or provide this service manually.

    2. Why can’t you find your own /js/jquery-2.0.3.min.js? Because this static file service does not have a module to provide it to you, so you need to provide it manually. Just slightly modify your index.js code above, and the result is As follows:

    //改动一下, 提出express
    var 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端口,改成8888
    http.listen(8888, function() {
        console.log('listening on *:8888');
    });
    
    • Note: It is best not to listen directly on the 80 port. You can listen on other ports and then hang a nginx as a reverse proxy. This method may be more relaxed. Directly monitoring on the 80 port is too violent! Personal opinion, hope it helps you.

    reply
    0
  • Cancelreply