@fateseekers

Как настроить WebSocket в Express.js?

В теме о сокетах, я сыроват, поэтому с первых телодвижений упал в cors.

Вот код app.js

// .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:
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,
}))


Ошибка:
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.

Пытался гуглить, но везде лишь указывали на момент, что нужно использовать createServer().
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);


И после указывать прослушку для server

server.listen(port);

Что я собственно и сделал, но никаких результатов это не дало.

Также пробовал настраивать cors для WebSocket
const io = require('socket.io')(server, {
  cors: {
    origin: 'http://localhost:8080',
  }
});


Но к результату также не получилось прийти.
  • Вопрос задан
  • 56 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
01 дек. 2020, в 23:18
80000 руб./за проект
01 дек. 2020, в 22:41
60000 руб./за проект
01 дек. 2020, в 21:24
500 руб./за проект