React POST requests with Express/Node and MongoDB

允我心安 提交于 2021-02-07 10:29:59

问题


I'm writing program that uses React as front-end, and an Express/Node API for the backend which then does CRUD operations in a MongoDB database. Right now, I'm using the native JS fetch() API to perform GET/POST operations on my front end. The GET requests work just fine, but my POST requests seem to not be working. On my front end, I have a form and a handler for form submission like so:

handleSubmit(){
    let databody = {
        "name": this.state.nameIn,
        "quote": this.state.quoteIn
    }

    return fetch('http://localhost:5002/stored', {
        method: 'POST',
        body: JSON.stringify(databody),
        headers: {
            'Content-Type': 'application/json'
        },
    })
    .then(res => res.json())
    .then(data => console.log(data)); 
}


render(){
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name
                    <input type="text" name="name" value={this.nameIn} onChange={this.handleNameChange}/>
                </label>
                <label>
                    quote
                    <input type="text" name="quote" value={this.quoteIn} onChange={this.handleQuoteChange}/>
                </label>
                <input type="submit" value="Add to DB" />
            </form> 
        </div>
    );
}

Then on my Express API, which is on port 5002, I have:

app.post('/stored', (req, res) => {
    console.log(req.body);
    db.collection('quotes').insertOne(req.body, (err, data) => {
        if(err) return console.log(err);
        res.send(('saved to db: ' + data));
    })
});

However, when the form is submitted, the request shows up on the Express API with an empty body. The console.log shows that req.body is just an { } I'm wondering what I did wrong?


回答1:


use body-parser

in your express code add :

global.bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: true,
  limit: '50mb',
  parameterLimit: 100000
}))
app.use(bodyParser.json({
  limit: '50mb',
  parameterLimit: 100000
}))


app.post('/stored', (req, res) => {
    console.log(req.body);
    db.collection('quotes').insertOne(req.body, (err, data) => {
        if(err) return console.log(err);
        res.send(('saved to db: ' + data));
    })
});

in your froontend :

handleSubmit:function(e){
   e.preventDefault();
    let databody = {
        "name": this.state.nameIn,
        "quote": this.state.quoteIn
    }

    fetch('http://localhost:5002/stored', {
            method: 'POST',
            body: JSON.stringify(databody),
            headers: {
                'Content-Type': 'application/json'
            },
        })
        .then(res => res.json())
        .then(data => console.log(data));
}



回答2:


If you use express 4.16 or later you can just use express.json(), it will attempt to parse the JSON of the request body and save it to req.body, but only if the header "Content-Type: application/json" is sent along with the request:

const app = express();
app.use(express.json()); // Parses request body if type is json. Saves to req.body.


来源:https://stackoverflow.com/questions/50617351/react-post-requests-with-express-node-and-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!