【问题标题】:how to FETCH POST data from REACT FORM to MongoDB如何从 REACT FORM 获取 POST 数据到 MongoDB
【发布时间】:2021-08-07 17:27:51
【问题描述】:

我想从 REACT FORM 获取 POST 数据到 mongodb 集群,

如何按名称提取输入值并将其放入 post 方法?

因为我使用了 req.body.NAME ...但它不起作用



class Formulaire extends Component {

    constructor(props) {
        super(props)

    }

    addProduct = () => {

        fetch('http://localhost:2904/addproduct' , {
            method : 'POST',

            body : JSON.stringify({
                image :req.body.image ,
                name :req.body.name,
                price : req.body.price
            }),

            headers : {
                'Content-type' : 'application/json'
            }
        })
}

    render() {
        return (

            <div className = "formualire">

                <form onSubmit = {this.addProduct}>

                    <input type="text"       name="image" /> <br/>
                    <input type="text"       name="name"  /> <br/>
                    <input type="number"     name="price" /> <br/>

                    <button type="submit">Post</button>


                </form>

            </div>
        );
    }
}

【问题讨论】:

  • 理想情况下,您应该拥有一个服务,该服务接受 post 调用,然后在 mongo 服务中加载数据。您能否更准确地了解您遇到问题的步骤?此外,在您的代码 sn-p 中,您想要其值的每个输入都应该是受控组件。在您尝试继续之前,最好参考 react js 文档,这将有很大帮助。
  • 没关系,我得到了我使用的解决方案 import { useForm } from "react-hook-form";检索输入值而不是使用 req.body.inputname 这在 Reactjs 中基本上是错误的,谢谢你照顾我的问题

标签: node.js reactjs mongodb express mongoose


【解决方案1】:

import React from 'react'
import { useForm } from "react-hook-form";
import { withRouter } from 'react-router-dom';


function Formulaire(props) {

    const { register, handleSubmit } = useForm();

    const addProduct = (data) => {

        fetch('http://localhost:2904/addproduct', {
            method: 'POST',

            body: JSON.stringify({
                image: data.image,
                name: data.name,
                price: parseInt(data.price)
            }),

            headers: {
                'Content-type': 'application/json'
            }

        })
            
    }

    const aa =(data) => {
        console.log(parseInt(data.price))
    }




    return (

        <div className="formualire">

            <form onSubmit={handleSubmit(addProduct)}>

                <input type="text" {...register('image', { required: true })} /> <br />
                <input type="text"  {...register('name', { required: true })} /> <br />
                <input type="number" {...register('price', { required: true })} /> <br />

                <input type="submit" />


            </form>

        </div>


    );
}


export default Formulaire;

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2018-03-18
    • 2019-12-15
    • 2019-09-29
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多