【问题标题】:How to insert data from a React form to mysql?如何将 React 表单中的数据插入 mysql?
【发布时间】:2021-09-15 04:59:01
【问题描述】:

我正在尝试开发我的第一个 React 应用程序。后端工作正常。无论如何,我不知道如何将输入的数据以反应形式插入到我的数据库中。我尝试使用 axios,但我遇到了很多问题。这是我的代码: 后端:

router.post('/insert',(req,res) =>{


    jsondata = req.body;
    description = jsondata['description'];
    distance = jsondata['distance'];
    hours = jsondata['hours'];
    minutes = jsondata['minutes'];
    seconds = jsondata['seconds'];


    conn.query('INSERT INTO run (description, distance, hours, minutes, seconds) VALUES (?,?,?,?,?)', [description,distance,hours,minutes,seconds], (err) =>{
        if(err)
        res.send(err)
        if(!err)
        res.send("Insert succeded.")
        
    })
})

前端:

import React, {useEffect, useState} from 'react';
import {Link} from 'react-router-dom';
function Insert(){

    return(

        <div>
            <form>
                <p>Insert the details of your run</p>
                <input type="text" id="description" placeholder="Insert a description of your run"></input>
                <input type="text" id="description" placeholder="Insert a description of your run"></input>
                <input type="number" id="description" placeholder="Insert the distance of your run"></input>
                <input type="number" id="description" placeholder="Insert the hours of your run"></input>
                <input type="number" id="description" placeholder="Insert the minutes of your run"></input>
                <input type="number" id="description" placeholder="Insert the seconds of your run"></input>
                <button id="btn">Submit</button>
            </form>
        </div>

    );


}

export default Insert;

非常感谢您的帮助!

【问题讨论】:

  • 继续用Axios试试,正是你需要的。

标签: javascript html node.js reactjs express


【解决方案1】:

在你需要放置方法来处理它们的变化的输入上,你可以将值存储在 useState 中,例如:

const [name, setName] = useState('');

...

<input type="text" value={name} onChange={setName} />

然后,通过添加这样的方法调用来处理提交表单

<form onSubmit={handleOnSubmit}>

您将在哪里收集输入数据并使用 axios 发送,例如:

 handleOnSubmit(e) {
        e.preventDefault()

        const data = {
          name: name
          // other fields...

        }

        axios.post('http://your-url.com', data)
            .then((res) => {
                console.log(res.data)
            }).catch((error) => {
                console.log(error)
            });
    }

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多