簡體   English   中英

表單元素不會使用 axios 將所有數據發送到 mongoDB。 (反應,Axios,快遞)

[英]Form element doesn't send all data to mongoDB by using axios. (React,Axios,Express)

我正在嘗試使用 Express.js 從 React 中的 HTML 表單元素向 MongoDB 發送數據。 但它只發送來自 Form 元素的最后一個輸入值。 實際上,它將最后一個輸入值顯示為控制台中的數據。 當我查看 MongoDB 時,我只能看到 id 和 createdAt、updatedAt。 沒有rest的數據。

這是我的 Form.jsx 文件;

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

const Form = () => {

    const [state, setState] = useState({
       fName:"",
       lName:"",
       age:"",
    });



    const handleOnChange = (event) =>{
        const value = event.target.value;
        setState({
            ...setState,
            [event.target.name]: value
        })

        console.log(state);
    }
    const postHandleClick = (event) =>{
        event.preventDefault();  
        
        axios
        .post("http://localhost:5000/", state)
        .then(res =>{
            console.log(res);
        })
        .catch((err)=>{
            console.log(err);
        });

    }
    return(
        <div className= "form-container">

            <form  action="http://localhost:5000/form" method="get">
                <button type="submit" className="btn btn-primary">Show Clients</button>
            </form>


            <form className="myForm" onSubmit={postHandleClick}>
                <div className="form-group">
                <label>First Name</label>
                <input type="text" className="form-control" name="fName" onChange={handleOnChange} value={state.fName} placeholder="Name"/>
                </div>
                <div className="form-group">
                  <label>Last Name</label>
                  <input type="text" className="form-control" name="lName" onChange={handleOnChange} value={state.lName} placeholder="Lastname "/>
                </div>

.
.  // there are many input and label elements
.

 <button type="submit" className="btn btn-primary">Submit</button>
            </form>

            
        </div>
    );
}


export default Form;


```

This is my index.js (in server folder)

```
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import router from "./routes/clients.js";
import cors from "cors";

//all these code for defining __dirname because of node 14 version
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

app.use(bodyParser.urlencoded({extended: true}));

app.use(cors());


app.use(express.static("../../client/public"));



app.get("/", (req, res) => {
    res.sendFile(__dirname + "../../client/public/index.html")
});

app.use(router);


const CONNECTION_URL = "mongodb+srv://admin-muhammet:37463746NBA@cluster0.zlysq.mongodb.net/dietManageDB";
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, {useNewUrlParser:true, useUnifiedTopology:true})
    .then(() => app.listen(5000, () => console.log(`Server running on port: ${PORT}`)))
    .catch((error) => console.log(error.message));
```

This is client.js (controller from server)

```
import Client from "../models/client.js";

export const createClientInfo =  (req, res) => {
    
    const newClientInfo = new Client(    
    {
        fName: req.body.fName,
        lName: req.body.lName,
        email: req.body.email,
        tel: req.body.telNumber,
        gender: req.body.gender,
        pregnancy: req.body.pregnancy,
        dob : {
            year: req.body.year, 
            month: req.body.month, 
            day: req.body.day,
        },
        currentWeight: req.body.weight,
        currentHeight: req.body.height,
        job: req.body.job,
        city: req.body.city,
        sporDuringDiet: req.body.sporDuringDiet,
        alcohol: req.body.alcohol,
        cigarette: req.body.cigarette,
        frequencySport:req.body.frequencySport,
        glassWater: req.body.glassWater,
        useSugar: req.body.useSugar,
        chronicIllness: req.body.chronicIllness,
        usingMedicine: req.body.usingMedicine,
        menopause: req.body.menopause,
        allergy: req.body.allergy,
        snack: {
            brkfstToNoon: {
                time: req.body.brkfstToNoonTime,
                food: req.body.brkfstToNoonFood,
            },
            noonToNight: {
                time: req.body.noonToNightTime,
                food: req.body.noonToNightFood
            },
            nightToSleep: {
                time: req.body.nightToSleepTime,
                food: req.body.nightToSleepFood,
            }
        },

    
    });

    newClientInfo.save();
    res.redirect("/form");
};


export const indexClientInfo = async(req, res) => {
    
    try {
        const client = await Client.find({});
        res.status(200).json(client);
    } catch (error) {
        res.status(404).json({message: error.message});
    }
    
}


export default {
    createClientInfo,
    indexClientInfo
};
```

this is the data from mongodb that form element sent

```
{
"_id": "6063c13015191b0b78643c5a",
"createdAt": "2021-03-31T00:24:16.152Z",
"updatedat": "2021-03-31T00:24:16.152Z",
"__v": 0
}
```

this is what the console shows; (First three objects I added, rest of the objects are created by form data. I want to add my form element send data as first 3 objects)

```
{data: Array(7), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "http://localhost:5000/", method: "post", data: "{"allergy":"no allergy"}", headers: {…}, transformRequest: Array(1), …}
data: Array(7)
0: {dob: {…}, snack: {…}, _id: "60607311264562474c006ff8", name: {…}, email: "muhammed@gmail.com", …}
1: {dob: {…}, snack: {…}, _id: "60622a2efc81265d2828f52e", name: {…}, email: "muhammed@gmail.com", …}
2: {dob: {…}, snack: {…}, _id: "60628b38a6f18b6e4088ae18", name: {…}, email: "muhammed@gmail.com", …}
3: {_id: "60631a99d4f4e15818c68c7e", createdAt: "2021-03-30T12:33:29.928Z", updatedat: "2021-03-30T12:33:29.928Z", __v: 0}
4: {_id: "60631abad4f4e15818c68c7f", createdAt: "2021-03-30T12:34:02.959Z", updatedat: "2021-03-30T12:34:02.959Z", __v: 0}
5: {_id: "6063c13015191b0b78643c5a", createdAt: "2021-03-31T00:24:16.152Z", updatedat: "2021-03-31T00:24:16.152Z", __v: 0}
6: {_id: "6063c1e615191b0b78643c5b", createdAt: "2021-03-31T00:27:18.180Z", updatedat: "2021-03-31T00:27:18.180Z", __v: 0}
length: 7
__proto__: Array(0)
headers: {content-length: "2794", content-type: "application/json; charset=utf-8"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
__proto__: Object
```

Thanks for help.

問題出在handleOnChange function 內的setState調用中,您在其中傳播setState function 而不是state

setState({
  ...setState, // {...setState} returns {}
  [event.target.name]: value,
})

應該

setState({
  ...state,
  [event.target.name]: value,
})

暫無
暫無

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

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