简体   繁体   中英

node.js app can't find socket.io

I installed socket.io in the app directory (along with express) and in the index.html file I link to it this way:

<script src="http://localhost:8080/node_modules/socket.io/lib/socket.io.js"></script>

I get a 404 on this request. I double-checked the link and it's fine. the node.js app runs on port 8080 and I have no idea why it doesn't work

UPDATE: Apparently it is something to with Express. When not using it I don't have that problem and socket.io works fine. This is he setup of my server file:

var express = require('express'),
    http = require('http');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

app.listen(8000);

and this is the front-end:

<script src="/socket.io/socket.io.js"></script>
<script src="js/vendor/jquery-1.8.3.min.js"></script>
<script>
  var socket = io.connect('http://localhost:8000');

Also, I switched the jQuery from google CDN to local and it doesn't find it too

Make sure you've made socket.io listening to external connections in your back-end. Basically socket.io has inside method of providing your socket.io.js file, so you should place your require ('socket.io').listen(app) before defining any routes to your app.

The correct url is :

<script src="/socket.io/socket.io.js"></script>

as randunel said.

So, your configuration should look like this :

UPDATED for express 3.x :

var express = require('express'),
    http = require('http');

var app = express();
var server = http.createServer(app).listen(8000);

require('socket.io').listen(server);  // Your app passed to socket.io

Server-side

<script src="http://localhost:8000/socket.io/socket.io.js"></script>

Don't use that whole path, it does not correspond to your project's directory structure. Just use

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

By the way, make sure that socket.io is also listening on 8080, not just the other services in your project.

尝试把你的JS文件中http://localhost:8080/javascripts/socket.io.js ,基本上你的JavaScript目录public文件夹中。

The way is the one from randunel.

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

If you link the file directly, you can get a "Welcome to socket.io" message instead of the file. There's also a CDN socket.io.js file available to link, but it's outdated and will not work fine on new projects, so it's not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM