簡體   English   中英

如何使用React / Node.js / Express框架異步提交POST請求?

[英]How to asynchronously submit POST request using React/Node.js/Express framework?

我正在嘗試使用React的fetch存和Node.js的Express框架來建立異步POST請求。

提交表單后,我可以在服務器端看到node.js正在接收數據。

我的困難在於,在客戶端提交表單后,網頁表現得很長時間,並且瀏覽器在加載時顯示“ Waiting for localhost...

如果我在服務器端添加res.send('received POST data') ,我將重定向到localhost:9000/jobSearch ,其中顯示'received POST data'。

我想從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;

提交表單時,默認的HTML表單行為是重定向到新頁面。 在大多數情況下,Web應用程序都不會出現這種情況。 建議使用controlled component來實現此行為。 更多信息在這里

這背后的基本思想是使用表單提交句柄功能。 該函數將通過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>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM