报错: Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘http://localhost:5001’) does not match the recipient window’s origin (‘http://localhost:5000’).

problem

本地2个服务 localhost:5000 localhost:5001,其中5001页面作为iframe嵌入到5000页面中
5000服务可以展示5001的页面,但是2个服务无法通过postmessage进行通信,控制台报错:
报错: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:5001') does not match the recipient window's origin ('http://localhost:5000').

reason

跨域导致

solution

通过nginx转发,使其2个服务同源,然后通过路由前缀区分
同源之后,2个服务postmessage可以正常通信

附上nginx配置

server {
    listen       9999;
    server_name  localhost;
    # http://localhost:9999/parent/
    location /parent {
        proxy_pass http://localhost:5000/;
    }
    # http://localhost:9999/child/
    location /child {
        proxy_pass http://localhost:5001/;
    }
}

效果
Snipaste_2024-05-05_12-33-39

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐