Reputation: 1274
I want to send POST request to mongodb using fetch API. GET request was implemented successfully using fetch API but POST request wasn't.
In the console log, POST request returns weird response as bellow:
{n: 1, opTime: {…}, electionId: "7fffffff0000000000000001", ok: 1}
electionId:"7fffffff0000000000000001"
n:1
ok:1
opTime:{ts: "6490526445679411201", t: 1}
__proto__:Object
I have never run into this response and I don't know what it means...
My code is as below.
server.js
app.post('/recipe', (req, res) => {
console.log(req.body); // this console.log returns empty object : {}
db.collection('recipe').insertOne(req.body, (err, result) => {
if (err) return console.log(err);
console.log('saved to database')
res.json(result);
});
});
index.js
class App extends Component {
constructor(props){
super(props);
this.state={
results: [],
name: '',
ingredients: '',
descriptions: '',
modal: false
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const { name, ingredients, descriptions } = this.state;
fetch('/recipe', {
method: 'POST',
body: JSON.stringify({
name,
ingredients,
descriptions
}),
headers: { 'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'}
})
.then( res => res.json())
.then( res => console.log(res)); //this console.log returns strange response
}
render() {
const { name, ingredients, descriptions } = this.state;
return (
<div className="App">
<h1>Recipe List</h1>
<form onSubmit={this.handleSubmit}>
<input
value={name}
type="text"
onChange={e => this.setState({ name: e.target.value })}
placeholder="name" />
<input
value={ingredients}
type="text"
onChange={e => this.setState({ ingredients: e.target.value })}
placeholder="ingredients" />
<input
value={descriptions}
type="text"
onChange={e => this.setState({ descriptions: e.target.value })}
placeholder="descriptions" />
<input type="submit" onClick={this.toggle}/>
</form>
</div>
)
}
}
export default App;
Thank you for your help in advance,
Upvotes: 1
Views: 1790
Reputation: 387
mongoDB insertOne returns information of success or not. if you want to get inserted data, try this.
db.collection('recipe').insertOne(req.body,(err, result)=>{
if (err) return console.log(err);
console.log('saved to database');
res.json(result.ops[0]);
});
Upvotes: 2