如何在React中将表单数据传递给MongoDB? [英] How to pass form data to MongoDB in React?

查看:44
本文介绍了如何在React中将表单数据传递给MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将输入的值以表格的形式传递给我的MongoDB数据库.我的问题是我不确定该怎么做.

I want to pass the values of the inputs in a form to my MongoDB database. My issue is I am not sure how to go about doing that.

我的想法是,当我实例化新的赏金时,在快递路线中的发帖请求中,我需要用每个表单输入的值替换req.body,但是我不知道这是否正确以及是否正确是的,我不知道如何真正获取它来查看另一个文件中的表单的值.

My thinking was that in the post request in my express route when I am instantiating a new Bounty I need to replace req.body with the values of each form input, but I don't know if that is exactly right and if it is, I don't know how to actually get it to look at the values of the form that is in another file.

这是我的表单组件:

import React, {Component} from "react";
import {connect} from "react-redux";
import {addBounty, displayBounties} from "./redux";

class BountyForm extends Component {
    constructor(){
        super();
        this.state = {
            input: {
                firstName: "",
                lastName: "",
                living: "",
                amount: "",
                type: ""
            }
        }
    }

    componentDidMount = () => {
        this.props.displayBounties();
    }

    handleChange = event => {
        const {name, value} = event.target;
        this.setState(prevState => {
            return {
                input: {
                    ...prevState.input,
                    [name]: value
                }
            }
        })
    }

    render(){
        return(
            <div>
                <form>
                    <input type="text" placeholder="First Name" name="firstName" value={this.state.input.fName} onChange={this.handleChange}/>
                    <input type="text" placeholder="Last Name" name="lastName" value={this.state.input.lName} onChange={this.handleChange}/>
                    <input type="text" placeholder="Living?" name="living" value={this.state.input.living} onChange={this.handleChange}/>
                    <input type="text" placeholder="Bounty Amount" name="amount" value={this.state.input.amount} onChange={this.handleChange}/>
                    <input type="text" placeholder="Jedi or Sith?" name="type" value={this.state.input.type} onChange={this.handleChange}/>
                    <button>Submit</button>
                </form>
            </div>
        )
    }
}

export default connect(state => state, {addBounty, displayBounties})(BountyForm);

这是我的Express路线:

Here are my Express routes:

const express = require("express");
const bountyRouter = express.Router();
const Bounty = require("../models/bounty");


bountyRouter.route("/")
    .get((req, res) => {
        Bounty.find((err, bounties) => {
            if(err) return res.status(500).send(err);
            return res.send(bounties);
        })
    })
    .post((req, res) => {
        const newBounty = new Bounty(req.body);
        newBounty.save((err, savedBounty) => {
            if(err) return res.status(500).send(err);
            return res.status(201).send(savedBounty);
        })
        res.send(newBounty);
    });

bountyRouter.route("/:id")
    .get((req, res) => {
        Bounty.findById(req.params.id, (err, foundBounty) => {
            if(err) return res.status(500).send(err);
            return res.send(foundBounty);
        })
        res.send(foundBounty);
    })
    .put((req, res) => {
        Bounty.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, updatedBounty) => {
            if(err) return res.status(500).send(err);
            return res.status(201).send(updatedBounty);  
        })
    })
    .delete((req, res) => {
        Bounty.findByIdAndRemove(req.params.id, (err, deletedBounty) => {
            if(err) return res.status(500).send(err);
            return res.status(201).send(deletedBounty);
        })
        console.log("Deleted Bounty!");
    })

module.exports = bountyRouter;

这是我的Redux:

import {createStore, applyMiddleware} from "redux";
import axios from "axios";
import thunk from "redux-thunk";


export const displayBounties = () => {
    return dispatch => {
        axios.get("/bounty").then(response => {
            dispatch({
                type: "DISPLAY_BOUNTIES",
                bounties: response.data
            })
        }).catch(err => {
            console.log(err);
        })
    }
}

export const addBounty = (newBounty) => {
    return dispatch => {
        axios.post("/bounty", newBounty).then(response => {
            dispatch({
                type: "ADD_BOUNTY"
                // add: response.data
            })
        })
    }
}

const reducer = (prevState = {}, action) => {
    switch(action.type){
        case "DISPLAY_BOUNTIES":
            return {
                bounties: action.bounties
            }
            case "ADD_BOUNTY":
                return {

                }
        default:
            return prevState;
    }
}

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

推荐答案

所以,我自己弄清楚了.

So, I figured it out myself.

结果证明我错了,在实例化新的赏金时不需要更改req.body.

Turns out i was wrong, I do not need to change the req.body when instantiating a new Bounty.

我们需要导入 body-parser 中间件,以使其能够读取输入中的数据.然后,在进行任何路由之前,我们需要在Express路由文件中使用它,如下所示:

We need to import the body-parser middleware in order to get it to read the data in the inputs. Then we need to use it in the Express routes file before making any of the routes, like this:

bountyRouter.use(bodyParser.urlencoded({extended: true}))

//routes go here...

urlencoded 方法仅从表单输入中获取数据并将其放置在请求正文中,因此为什么我们不需要删除我提到的eariler的req.body.

The urlencoded method just gets the data from the form inputs and places them in the request body, hence why we don't need to remove the req.body that I mentioned eariler.

最后在表单中,我需要指定对表单执行的操作以及将数据发送到的位置.由于我想进行POST,因此如下所示:

And finally in my form, I need to specify what action I am doing to the form and where to send the data. Since I want to do a POST, it would look like this:

<form action="/bounty" method="post">
//rest of the form

这篇关于如何在React中将表单数据传递给MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆