Nikito4ka_ka
@Nikito4ka_ka

Как исправисть ошибку Cors (Next.js и Nest.js)?

Здраствуйте, изучаю next.js и поймал ошибку cors

[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)


На сервере nest.js core настроен вроде
server nest.js

main.js
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();


chat.getway
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);
  }
}



такое ощущение что next.js отправляет запросы сам себе на "localhost:3000", а не на "http://localhost:80",
как это можно исправить ?

в react.js можно было при локальном тесте использовать proxy, но я не уверен что в next.js так же.

вот код next.js (подключение к socket.io)
next.js
'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>
	);
}
  • Вопрос задан
  • 477 просмотров
Пригласить эксперта
Ответы на вопрос 1
alexrapro
@alexrapro
Frontend Developer
В файле next.config.js просто настрой прокси используя:

async rewrites() {
        return []
}
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы