首页 > 解决方案 > 提交到新 URL 后如何访问表单数据

问题描述

我想通过单击提交按钮将表单详细信息提交到一个全新的 URL。这是在 React 应用程序中。我通过以下方式对表单进行了基本设置。

    let form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action",'localhost:3000/message/');
    form.setAttribute("onSubmit", this.handleSubmit);
    form.setAttribute("target", 'newWindow');

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "message");
    hiddenField.setAttribute("value", "Hi. Im Awesome");
    form.appendChild(hiddenField);
    document.body.appendChild(form);

    window.open('localhost:3000/message/', 'newWindow');
    form.submit();
handleSubmit(e) {
    e.preventDefault();
}

此时,当我提交时,会打开一个新选项卡,但该选项卡也会向表单数据localhost:3000/message发出网络请求。localhost:3000/message/

我想停止额外的网络调用,localhost:3000/message/并且我还希望能够直接在运行于 3000 的应用程序中访问表单数据。

这是可以实现的吗?

更新:正如@Jite 提到的, fetch 会清理这里的一些问题,所以我没有直接将数据作为表单发送,而是尝试通过 fetch api 发送它。

    window.open('localhost:3000/message/', 'newWindow');

    fetch('localhost:3000/message/', {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: 'Hi, I'm even more awesome!'
      })
    })

运行的应用程序的渲染方法以localhost:3000\以下方式设置 -

  //import { BrowserRouter as Router, Route } from "react-router-dom";

  render() {
    return (
        <Router>
          <Route
            path="/message"
            render={props =>     
              <h2>Any message for me ?</h2>
            }
          />
        </Router>
    );
  }

我仍然不知道如何访问发送到此 url 的消息。

标签: javascriptnode.jsreactjs

解决方案


我已经设法通过监听事件发送数据window.postMessage()并在新窗口中访问它来解决这个问题。message


推荐阅读