javascript - 如何在React中将表单数据传递到MongoDB?

标签 javascript mongodb reactjs express post

我想将表单中的输入值传递到我的 MongoDB 数据库。我的问题是我不知道如何去做。

我的想法是,在我的快速路线的发布请求中,当我实例化一个新的赏金时,我需要用每个表单输入的值替换 req.body ,但我不知道这是否完全正确,如果是的,我不知道如何实际让它查看另一个文件中表单的值。

这是我的表单组件:

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);

这是我的特快路线:

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;

最佳答案

所以,我自己想出了办法。

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

我们需要导入 body-parser 中间件,以便让它读取输入中的数据。然后我们需要在创建任何路由之前在 Express 路由文件中使用它,如下所示:

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

//routes go here...

urlencoded 方法只是从表单输入中获取数据并将它们放入请求正文中,因此我们不需要删除我之前提到的 req.body。

最后,在我的表单中,我需要指定我对表单执行的操作以及将数据发送到何处。由于我想做一个 POST,它看起来像这样:

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

关于javascript - 如何在React中将表单数据传递到MongoDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732600/

相关文章:

javascript - 如何更新作为参数接收的多个集合键?

node.js - 在开发中设置从 Angular 向 NodeJS 发送 API 请求的服务器端口

javascript - 使用 React Markdown 编辑器时出错

javascript - React 组件中的 Prop 发生了变化

javascript - 我想在 react 中创建一个倒计时 watch ,用户在其中输入输入,可能在几秒钟内输入,然后它下降到 0

javascript - 页面加载后运行多个脚本

javascript - 如何按特定顺序正确收集json数据

javascript - 在 node.js 中从数据库中获取非英文字符时出现编码问题

javascript - 调用父类中被重写的函数

mongodb - 为什么 mgo 不能正确解码我的结构?