Answer the question
In order to leave comments, you need to log in
How to solve Socket.io blocked CORS issue?
Good afternoon.
There is a problem when trying to connect a client to sockets:
Access to XMLHttpRequest at ' https://domen/socket.io/?token=eyJhbGciOiJIUzI1NiI... ' from origin ' localhost:7070 ' has been blocked by CORS policy: No 'Access- Control-Allow-Origin' header is present on the requested resource.
I've seen many similar situations, but they don't work. If anyone has already solved this problem.
sockets/index.ts
export class Socket {
private readonly _io;
public constructor(server: http.Server) {
this._io = require('socket.io')(server);
this._io.set('origins', '*:*');
this._io.origins('*:*');
this._io.adapter(redis({ host: process.env.REDIS_URL, port: 6379 }));
}
public initialize(): void {
sellerSocket(this._io);
courierSocket(this._io);
}
}
class Program {
public static readonly NODE_ENV: string = process.env.NODE_ENV || "development";
public static readonly PORT: string = process.env.PORT || "7070";
public static readonly HOST: string = process.env.HOST || "localhost";
public static async Main(): Promise<void> {
Logger.clear();
Logger.info(`NODE_ENV: ${this.NODE_ENV}`);
const connectionOptions = await getConnectionOptions(this.NODE_ENV);
await createConnection({ ...connectionOptions, name: "default" } as any);
await bootstrap();
const application: Application = container.get<Application>(TYPES.IApplication);
application.initialize();
const server = http.createServer(application.app);
const socket = new Socket(server);
socket.initialize();
server.listen(this.PORT, () => {
Logger.application(`Application ready`);
Logger.info(`http://${this.HOST}:${this.PORT}`);
Logger.info("Heap: " + (process.memoryUsage().heapTotal / (1024 * 1024)).toFixed(2) + " MB");
Logger.info("CPU Time: " + process.cpuUsage().user);
});
}
}
Program.Main();
const socket = io.connect(`${serverUrl}/sellers`, { query: { token: data.authorizationToken }, secure: false });
socket.on("ADD_ORDER", (data) => {
console.log(data);
createOrderBlock(data);
});
socket.on("ORDERS", (orders) => {
console.log(orders);
for (const data of orders) { createOrderBlock(data); }
})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question