我正在做一个MEAN堆栈应用程序。为了在客户端和服务器之间进行通信,我使用了一些HTTP请求和Websocket。 在本地主机上,它可以正常工作。
但是,当我尝试将应用程序从localhost部署到特定服务器时,websocket不再起作用。但是,http请求可以正常工作。
我收到此错误:
Firefox无法在以下位置建立与服务器的连接 ws://138.250.31.29:3000 / socket.io /?userId = 5b7c030dca40486dabaafaaf&EIO = 3&transport = websocket&sid = oEcoYYbhD4ighJC0AAAB。
我没有成功获得有关此错误的更多信息。
为了建立连接,我在Node.JS上有两个文件:
APP.JS
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const favicon = require("serve-favicon");
const cors = require("cors");
require("./models/db");
require("./config/passport");
const passport = require("passport");
const apiRouter = require("./routes/index");
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
const app = express();
app.use(logger("dev"));
app.use(express.json({ limit: "1gb" }));
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(cors(corsOptions));
app.use("/api", apiRouter);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
// error handlers
// Catch unauthorised errors
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({ message: err.name + ": " + err.message });
}
});
module.exports = app;
万维网
!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require("../app");
const debug = require("debug")("sorfml:server");
const http = require("http");
const socketIO = require("socket.io");
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Bind the socket.IO with the http server
*/
const io = socketIO(server);
io.origins("*:*");
clientsList = {};
/**
* Socket connection
*/
io.on("connection", socket => {
console.log("Client connected " + socket.id);
socket.user_id = socket.handshake.query.userId;
clientsList[socket.handshake.query.userId] = socket;
socket.on("disconnect", () => {
delete clientsList[socket.user_id];
console.log("Client disconnected: " + socket.id);
});
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log("Listening on " + bind);
}
在客户端:
import * as io from "socket.io-client";
private socket;
this.socket = io("http://138.250.31.29:3000", { query: "userId=" + userId });
this.socket.on("sendNotification", data => {
// Do a function
});
this.socket.on("deleteNotificationFromAuthor", data => {
// Do a function
});
答案 0 :(得分:1)
您在客户端使用的是http而不是ws,
this.socket = io("ws://138.250.31.29:3000", { query: "userId=" + userId });
仅供参考:如果您不知道,http和ws端口可能与w3标准相同。您应该使用ws协议创建Web套接字连接
希望有帮助。