connecting mongo to react js code example
Example 1: how to sent react from data in mongodb
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>
);
}
Example 2: how to sent react from data in mongodb
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));
})
});