【问题标题】:How to asynchronously submit POST request using React/Node.js/Express framework?如何使用 React/Node.js/Express 框架异步提交 POST 请求?
【发布时间】:2020-01-10 07:58:34
【问题描述】:

我正在尝试使用带有 React 的 fetch 和带有 Node.js 的 Express 框架来设置异步 POST 请求。

提交表单后,我可以在服务器端看到 node.js 正在接收数据。

我的困难是,在客户端提交表单后,网页就像渲染了很长时间一样,并且浏览器在加载时显示Waiting for localhost...

如果我在服务器端添加res.send('received POST data'),我会被重定向到localhost:9000/jobSearch,它会显示“收到的POST 数据”。

我想从localhost:9000/jobSearch 检索数据并将其显示在客户端localhost:3000 上,而无需重新加载页面。我已经读过使用 axios 或 jQuery 可能会更容易,但是我想只使用带有 Node.js 的 React 和 Express 来做到这一点。我复制了几个例子,但我无法让我的实现工作。我错过了什么吗?

反应:

App.js

import React, { Component } from 'react';
import { FormControl, Button } from 'react-bootstrap'


class App extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            jobSearch: {
                jobTitle: '',
                location: ''
            }
        }
    }


    onSubmit = (e) => {
        e.preventDefault();
        const { jobTitle, location } = this.state;

        fetch('http://localhost:9000/jobSearch',{
            method: "POST",
            headers: {
                'Content-type': 'application/json'
            },
            body: JSON.stringify(this.state.jobSearch)
        }).then(res => res.json())
          .then((result) => {
              console.log('callback for the response')
        })
    }

    render() {
        return (
            <form method="POST" action="http://localhost:9000/jobSearch">
                <FormControl name="jobTitle"/>
                <FormControl name="location"/>
                <Button type="submit">Find Jobs</Button>
            </form>
        )
    }
}

export default App;

Node.js:

jobSearch.js

var express = require('express');
var router = express.Router();

router.post('/', function(req, res, next) {
    console.log('req.body here -> ', req.body)
});

module.exports = router;

【问题讨论】:

  • 去掉方法和动作,把onSubmit放到表单或者按钮组件上

标签: node.js reactjs express asynchronous fetch


【解决方案1】:

默认的 HTML 表单行为是在提交表单时重定向到新页面。在大多数情况下,这不是 Web 应用程序的预期行为。建议使用controlled component 来实现此行为。更多信息here.

这背后的基本思想是使用表单提交句柄函数。此函数将使用SyntheticEvent 调用。通过在 SyntheticEvent 上调用 preventDefault 可以防止默认的 html 表单行为。实现看起来像这样:

class Form extends React.Component {

  handleSubmit = (event) {
    event.preventDefault();
    // on submit logic
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        // form fields
      </form>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2013-10-05
    相关资源
    最近更新 更多