I am able to store data in my mongoDB database using req.body in a POST request but I am not able to retrieve that data using req.body in a GET request. I can retrieve data if I pass a string but not req.body.. I have seen there are multiple posts on this issue in which body parser seems to solve the issue but I am still retrieving undefined even though I have body parser going.
Thanks in advance.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 2000;
// app.use(express.urlencoded({extended: true}));
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(express.json());
app.use(bodyParser.json());
app.use(express.static('public'));
const database = mongoose.connect('mongodb://localhost/users')
.then(() => console.log('connected to mongoDB!!'))
.catch((err) => console.error('unable to connect', err));
const userSchema = {
name: String,
email: String
}
const User = mongoose.model('User', userSchema);
app.post('/api/users',(req,res) => {
const user = new User({
name: req.body.name,
email: req.body.email
});
const create = user.save();
res.send('created a user account');
});
app.get('/api/users', async (req,res) => {
const find = await User
.find({ name: req.body.name});
console.log(find);
res.send(`your data is ${req.body.name}`);
})
app.listen(PORT, () => console.log(`listening on port ${PORT}`));