简体   繁体   中英

Heroku Node.js + Socket.io: After deploying to Heroku, I get a ERR_CONNECTION_REFUSED

This is the error message I am getting in the web console on my live node.js heroku app: polling-xhr.js:264 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=M2MDZUw net::ERR_CONNECTION_REFUSED

When I run my program locally, it all works fine without any problem. I have listed the server to listen to whatever is in the environment PORT or port 3000 if there's nothing there. Below is my relevant server.js code, and package.json code, as well as the client code used to connect to the server.

server.js

var express = require("express");
var socket = require("socket.io");

var app = express();
var server = app.listen(process.env.PORT || 3000)

package.json

{
  "name": "testProject",
  "version": "1.0.0",
  "description": "test project using node.js + sockets.io",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "sockets",
    "p5",
    "node"
  ],
  "author": "henry zhu",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2",
    "socket.io": "^2.0.4"
  }
}

Client-side code to connect to server:

var socket = io.connect("http://localhost:3000");

The version of socket.io I am using client side is 2.0.4.

When you connect like this

var socket = io.connect("http://localhost:3000");

on the client-side you are actually trying to connect to your own computer on port 3000. If you fire up the server on your computer they might even start communicating. However, you want to connect to the server you are hosting on Heroku. If the client is served on the same domain as the server you can simply do

var socket = io();

The socket will then connect to it's own domain on the port it's served on (usually 80). It works both locally and on Heroku. If you want to change port you can use:

var socket = io(':3000');

If the client is served by another server than the socket server you will have to supply the whole URL:

var socket = io('https://example.herokuapp.com');

Remember that when you use var server = app.listen(process.env.PORT || 3000) you are not running on port 3000 on Heroku. Heroku will set the PORT environment variable for you and to the outside world the port is 80.

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