1

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?

albert
  • 848
  • 2
  • 7
  • 29

2 Answers2

2

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));
}
Saurabh Mistry
  • 8,903
  • 4
  • 33
  • 51
1

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.
skovmand
  • 4,022
  • 5
  • 20
  • 27