如何使用window.postMessage从后端向前端发送数据?

问题描述 投票:0回答:1

我想通过window.postMessage将从后端获得的数据发送到前端(下面的图像代码) 但我收到了这个错误: 无法在“DOMWindow”上执行“postMessage”:提供的目标源(“http://127.0.0.1:5173”)与收件人窗口的源(“http://localhost:8000”)不匹配。 我该如何修复它? 请帮我

我尝试过使用 window.opener.postMessage 但仍然收到其他错误:无法读取 null 的属性(读取 'postMessage')

javascript frontend backend postmessage
1个回答
0
投票

通常您会使用 HTTP 客户端在客户端和服务器之间传递请求和响应。授权令牌应该在 headers 对象中进行编码和传递,在 headers 对象中可以在任意一端接收和解码。

如果您需要按照您所描述的方式传递数据,您需要在后端调用 postMessage 并创建一个 eventListener 来接受客户端的消息。可能看起来像这样:

// Frontend

window.addEventListener("message", (event) => {
  if(event.origin !== "http://127.0.0.1:5173"){
    console.log("Invalid Origin")
  } else {
    console.log(event.data)
  }
}, false);


// Server

const popup = window.open();
popup.postMessage({token}, "http://localhost:8000");
© www.soinside.com 2019 - 2024. All rights reserved.