[Error] Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200
[Error] XMLHttpRequest cannot load http://localhost/socket.io/?EIO=4&transport=polling&t=OZ3Fag1 due to access control checks.
[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200 (socket.io, line 0)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: [
'http://localhost:3000',
'http://localhost:8080',
'http://localhost:4200',
],
});
await app.listen(8000);
}
bootstrap();
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
@WebSocketGateway(80, { namespace: 'chat' })
export class ChatGateway {
@WebSocketServer()
server;
@SubscribeMessage('message')
handleMessage(@MessageBody() message: string): void {
this.server.emit('message', message);
}
}
'use client';
import Message from '@/components/messages/message';
import MessageInput from '@/components/messages/messageInput';
import styles from '@/style/page.module.scss';
import { useEffect, useState } from 'react';
import io, { Socket } from 'socket.io-client';
export default function Home() {
const [socket, setSocket] = useState<Socket>();
const [messages, setMessages] = useState<string[]>([]);
const send = (value: string) => {
socket?.emit('message', value);
};
useEffect(() => {
const newSocket = io('http://localhost:80');
setSocket(newSocket);
}, [setSocket]);
const messageListener = (message: string) => {
setMessages([...messages, message]);
};
useEffect(() => {
socket?.on('message', messageListener);
return () => {
socket?.off('message', messageListener);
};
}, [messageListener]);
return (
<div className={styles.container}>
<div className={styles.contamessage_wrapiner}>
<Message messages={messages} />
<MessageInput send={send} />
</div>
</div>
);
}