简体   繁体   中英

Using Websocket with express and Nodejs not working

I have this code which I am using for my express server. The server works when I access the routes over http however when I try to connect to it over wss it doesnt work. What am I doing wrong?

const morgan = require("morgan");
const cors = require("cors");
const passport = require("passport");
const localStrategy = require("./auth/local");
const jwtStrategy = require("./auth/jwt");
const expressValidator = require("express-validator");
const config = require("./config");

const app = express();

const http = require("http").Server(app);
const io = require("socket.io")(http);

app.use(cors());
app.use(express.json());
app.use(expressValidator());
app.use(morgan("common"));
app.use(passport.initialize());

passport.use(localStrategy);
passport.use(jwtStrategy);

require("./routes")(app);

io.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});
io.on("connection", (socket) => {
  console.log("a user connected", socket);
});

http.listen(config.port);

module.exports = app;

Try using ws: in place of wss: for a quick fix.

wss: is the TLS-secured version of ws: , analogous to https: and http: . In fact, websocket connections to a server begin their lives as http / https connections. They're then "upgraded" to websocket connections by the websocket protocol.

So, to get wss: to work on that server of yours, start by getting https: working for the express webserver part. It's the https server behind express that will also handle the connections to be upgraded.

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