【问题标题】:Passing form data to express传递表单数据来表达
【发布时间】:2020-05-16 21:18:18
【问题描述】:

很难传递一些数据来表达。我正在尝试发送从表单中收集的一些数据。表单值正在正确更新。但是当我到达终点时,我不知道如何注销我正在传递的内容。任何指针将不胜感激。

快递:

app.post('/something-to-post', cors(corsOptionsDelegate), (req, res)=> {
 //how do I log what I am passing from the form 
  console.log('full name:', req.data);
});

反应

import React, {useState} from "react";
import axios from "axios";

const Form = () => {
  const [fullName, setFullName] = useState('');

  function handleInputChange(event) {
    setFullName(event.target.value); // updates state properly
  }

  function post(event){
    event.preventDefault();
    console.log('full name:', fullName); // logs out correctly
    axios.post('http://localhost:9000/something-to-post', {name: fullName})
      .then(response => {
        // todo
      })
      .catch(error => {
        // todo
      })
   }
}

return (
  <form onSubmit={post}>
    <input type="text" value={fullName} onChange={handleInputChange}/>
    <button type="submit">Submit</button>
  </form>
  )
 };

export default Form;

【问题讨论】:

    标签: reactjs forms express post axios


    【解决方案1】:

    你可以像下面的代码那样做:

    前端:

    import React, {useState} from "react";
    import axios from "axios";
    
    const Form  = () => {
      const [fullName, setFullName] = useState('');
    
      function handleInputChange(event) {
        setFullName(event.target.value); // updates state properly
      }
    
      function post(event){
        event.preventDefault();
        console.log('full name:', fullName); // logs out correctly
        axios.post('http://localhost:9000/something-to-post', {name: fullName})
          .then(response => {
            console.log(response.data);
          })
          .catch(error => {
            console.log(error.data)
          })
       }
      return ( 
        <form onSubmit={post}>
        <input type="text" value={fullName} onChange={handleInputChange}/>
        <button type="submit">Submit</button>
      </form>
       );
    }
    
    export default Form;
    

    后端:

    const express = require('express');
    const cors = require('cors');
    
    const app = express();
    
    app.use(cors());
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    app.post('/something-to-post', (req, res) => {
      console.log(req.body);
      console.log(req.body.name);
      const response = {
        success: true,
        code: 200,
        message: 'Data from backend',
        data: req.body
      }
      res.status(200).send(response);
    })
    
    app.listen(9000, () => {
      console.log('Server is up');
    })
    
    

    希望对你有帮助。

    【讨论】:

    • 我需要安装和使用 npm i body-parser for req.body.name 才能为我工作。
    • 如果你使用的是最新版本的 express,那么你不应该安装 body parser。你可以使用快递。上面的代码是您不需要安装 body-parser 的示例。
    【解决方案2】:

    因此,您需要通过跟踪状态中的数据的反应方式来执行此操作。

    首先添加一个函数来更新数据handleInputChange。然后在输入中添加一个名称属性,您需要更新哪个值。检查以下内容并阅读更多关于React forms

    import React from "react";
    import axios from "axios";
    
    const Form = () => {
      // Set initial state 
      const [values, setValues] = React.useState({fullName: ''})
    
      // Add a function to update the value of your input fields
      handleInputChange(event) {
         const target = event.target;
         const value = target.type === 'checkbox' ? target.checked : target.value;
         const name = target.name;
    
         setValues({ ...values, [name]: value })
      }
    
      function post(event){
        event.preventDefault();
        let name = document.getElementById('full-name').value;
    
        let data = {
          name: values.fullName, // get the value of the input field from the state
        };
    
        axios.post('http://localhost:9000/something-to-post', data)
          .then(response => {
            // todo
          })
          .catch(error => {
            // todo
          })
       }
    }
    
    return (
      <form onSubmit={post}>
        <input id="fullName" name="fullName" type="text" value={values.fullName} onChange={(evt)=>this.handleInputChange(evt)} />
        <button type="submit">Submit</button>
      </form>
      )
     };
    
    export default Form;
    

    【讨论】:

    • 我更新了代码以使用状态并添加了一个处理程序来处理输入更改,表单工作正常。在快递中,我不知道如何注销我从表单中捕获的内容
    • 您需要安装body-parser并使用它。在此处阅读更多信息expressjs.com/en/resources/middleware/body-parser.html
    • 我的解决方案有帮助吗?
    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2011-05-24
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多