簡體   English   中英

如何從 REACT FORM 獲取 POST 數據到 MongoDB

[英]how to FETCH POST data from REACT FORM to MongoDB

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


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;

暫無
暫無

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

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