【问题标题】:How to handle POST request in reactjs?reactjs如何处理POST请求?
【发布时间】:2020-01-06 14:45:02
【问题描述】:

我的 ReactJS 应用程序在 http://localhost:3000/ 中运行。我将以下表单数据作为 POST 请求接收到我的 React 页面

<form action="http://localhost:3000/" method="post">
  Employee Id: <input type="text" name="eid"><br>
  Department Id: <input type="text" name="did"><br>
  <input type="submit" value="Submit">
</form>

我的 react 应用应该能够处理这个 POST 请求并呈现如下的 UI

<h1>{eid}</h1>
<h1>{did}</h1>

我能够使用反应路由器处理 GET 请求,但难以处理 POST 请求。我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    如果你的 React 应用是静态的(不是服务器端渲染的),这是不可能的。 当您向您的反应应用程序发送一些 POST 请求时,nginx(或其他服务器)将不允许这种操作(您不能发布到静态文件) 即使你绕过了这个限制,react 脚本也不会从你的 POST 请求中获取任何数据,因为 nginx 会处理你的请求并只返回一个带有 react 脚本的 html 给你

    【讨论】:

      【解决方案2】:

      它不会像 php 那样工作。你需要有后端(节点或 php 来传递数据)甚至一些站点来接受请求。

      【讨论】:

        【解决方案3】:

        首先,您可能需要一些理论观点:

        https://pusher.com/tutorials/consume-restful-api-react

        https://www.robinwieruch.de/react-hooks-fetch-data


        • 你应该先保存数据
        • 您将它们保存到状态
        • 您将它们显示在渲染它的部分

        要从 api (GET) 下载数据 - 您不直接在表单中进行 - 您只使用 ComponentDidMountUseEffect .

          componentDidMount() {
            fetch(ApiURL)
              .then(res => res.json())
              .then(res => this.setState({ planets: res }))
              .catch(() => this.setState({ hasErrors: true }));
          }
        

          useEffect(async () => {
            const result = await axios(
              ApiURL,
            );
            setData(result.data);
          });
        

        要将数据发送到 api (POST)- 这很复杂 - 您需要有关 客户端-服务器 通信的信息

        直接来自 React 文档:

        fetch('https://mywebsite.com/endpoint/', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            firstParam: 'yourValue',
            secondParam: 'yourOtherValue',
          })
        })
        

        【讨论】:

        • 感谢您的回复。有一个名为example.com 的外部应用程序将通过POST 请求重定向到我的localhost:3000。我可以在 Node/Express 中处理 POST 请求。 React 页面中是否有类似的方式?
        • 是的,如果你通过从 React 中获取来发送它,你可以在后端站点的 node.js 中处理它,然后对这些数据进行任何处理(发送数据库、变异等)
        • 如何将这些 POST 输入从 react 转发到 node.js 服务器?
        • 来聊天 - chat.stackoverflow.com/rooms/205536/post-api 你可以吗?还是需要 20 次代表?
        猜你喜欢
        • 1970-01-01
        • 2019-02-02
        • 2010-12-08
        • 1970-01-01
        • 2012-10-30
        • 2015-06-17
        • 2013-03-03
        • 2016-09-20
        • 1970-01-01
        相关资源
        最近更新 更多