Tengo dos aplicaciones: CRA ejecutándose en el puerto 3000 y Next ejecutándose en el 3005.
En la próxima aplicación, tengo un detector de eventos de mensaje simple:
useEffect(() => { const handleMessage = (event: MessageEvent<{}>) => console.log('Message event: ', event); window.addEventListener('message', handleMessage); return () => { window.removeEventListener('message', handleMessage); }; }, []); Y configuré encabezados en next.config.js :
const securityHeaders = [ { key: 'Access-Control-Allow-Credentials', value: 'true' }, { key: 'Access-Control-Allow-Origin', value: '*' }, { key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT', }, { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version', }, ]; const nextConfig = { async headers() { return [ { // Apply these headers to all routes in your application. source: '/:path*', headers: securityHeaders, }, ]; }, }; module.exports = nextConfig; En la aplicación React, estoy llamando a postMessage a través de una etiqueta iframe como esta:
export const Frame = () => { const frameRef = useRef<HTMLIFrameElement>(null); const handleFrameLoad = () => { frameRef?.current?.contentWindow?.postMessage('TEST'); }; return ( <iframe src="http://localhost:3005" ref={frameRef} onLoad={handleFrameLoad} sandbox="allow-same-origin allow-scripts" /> ); };Y sigo recibiendo el error a continuación en la consola de CRA.
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3005').
¿Hay algo más que pueda hacer para permitir la comunicación posterior al mensaje entre dos puertos locales diferentes en NextJS?