F
F
fateseekers2020-11-20 18:40:55
Socket.io
fateseekers, 2020-11-20 18:40:55

How to set up WebSocket in Express.js?

In the topic of sockets, I'm damp, so from the first gestures I fell into cors.

Here is app.js code

// .Env variables
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const path = require("path");
const methodOverride = require("method-override");
const app = express();
const port = process.env.PORT;
const logger = require("./middleware/logger");

app.use(logger.requestLog);
app.use(express.urlencoded({ extended: false, limit: "50mb" }));
app.use(express.json());

const routerUser = require("./routes/user");
const routerTasks = require("./routes/tasks");
const routerRegions = require("./routes/regions");
const routerStatus = require("./routes/status");
const routerClients = require("./routes/clients");
const routerOrders = require("./routes/orders");
const routerReports = require("./routes/reports");
const routerEvents = require("./routes/events");
const routerCategories = require("./routes/categories");
const routerProducts = require("./routes/products");
const routerBrands = require("./routes/brands");
const routerDepartments = require("./routes/departments");
const routerDocuments = require("./routes/documents");

app.use((req, res, next) => {
    const allowedOrigins = [
        "http://localhost:8081",
        "http://localhost:8080",
    ];
    const origin = req.headers.origin;
    if (allowedOrigins.includes(origin)) {
        res.setHeader("Access-Control-Allow-Origin", origin);
    }
    res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "Content-Type, Authorization, X-Requested-With"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);

    next();
});

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

app.use("/", express.static(path.join(__dirname, "build")));
app.use("/uploads", express.static(__dirname + "/uploads"));
app.use("/avatars", express.static(__dirname + "/static/avatars"));
app.use("/passports", express.static(__dirname + "/static/passports"));

app.use(methodOverride());

app.use("/user", routerUser);
app.use("/tasks", routerTasks);
app.use("/regions", routerRegions);
app.use("/status", routerStatus);
app.use("/clients", routerClients);
app.use("/orders", routerOrders);
app.use("/reports", routerReports);
app.use("/events", routerEvents);
app.use("/categories", routerCategories);
app.use("/products", routerProducts);
app.use("/brands", routerBrands);
app.use("/departments", routerDepartments);
app.use("/documents", routerDocuments);

app.get("*", (req, res) => {
    res.send();
});

// StartApp
const startApp = async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            poolSize: 8,
    });
    io.on("connection", (socket) => {
            console.log("a user connected");
    });
    
        server.listen(port);

        console.log("Successfully started at port:" + port);
    } catch (error) {
        console.log("[Error]", error);
        process.exit(404);
    }
};

// init
startApp();


vue code:
import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://localhost:8081',
    transports: ['websocket'],
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    },
    withCredentials: true,
}))


Error:
Access to XMLHttpRequest at ' localhost:8081/socket.io/?EIO=3&transport=polling&... ' from origin ' localhost:8080 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to google, but everywhere they only pointed out at the moment that you need to use createServer ().
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);


And after specifying the wiretap for the server

server.listen(port);

What I actually did, but it did not give any results.

Also tried configuring cors for WebSocket
const io = require('socket.io')(server, {
  cors: {
    origin: 'http://localhost:8080',
  }
});


But the result also failed to come.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question