I am having an issue with using Express' req.body (using MongoDB in this app)
This is not an error with the routes - GET method works fine, and POST method works if I don't hava Validation requirement. The issue happens when I use the POST route's req.body. I have been at this for hours.. please help
Here is my server.js
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const groups = require('./routes/api/groups')
// Middleware
app.use(express.urlencoded({extended: true}));
// DB config
const dbURL = require("./config/keys").mongoURI;
// Connect to mongoDB
mongoose.connect(dbURL, {useNewUrlParser: true, useUnifiedTopology: true})
.then(console.log("MongoDB connected..."))
.catch(err => console.log(err))
// Use Routes ** THIS LEADS TO THE SECOND CODE **
app.use('/api/groups', groups)
const port = process.env.PORT || 3500
app.listen(port, ()=> console.log(`Server is listening at port ${port}`))
group.js to handle all group routes
const express = require('express');
const router = express.Router();
const Group = require('../../models/Group')
router.get('/', (req, res) => {
Group.find()
// sort by date descending
.sort({ date: -1})
.then(groups => res.json(groups))
})
router.post('/', (req, res) => {
console.log(req.body)
const newGroup = new Group({
name: req.body.name,
})
newGroup.save( err => {
if (err) {
console.error(err)
} else {
console.log("saved!")
}
})
})
The Group Schema
const mongoose = require("mongoose");
let groupSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
},{
timestamps: true
})
module.exports = mongoose.model("group", groupSchema)
I used Postman to send a POST request:
{
"name": "Hello!"
}
and I receive this on console: from console.log(req.body) - second set of codes in router.post:
{ '{\n\t"name": "Hello!"\n}': '' }
I thought that express' middleware (which now includes body-parser) is supposed to remove whitespace. The validation error is a result of its inability to access the "name" key.
I appreciate your time and help!
Attach body-parser correctly:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true})); // content-type: application/x-www-form-urlencoded
app.use(bodyParser.json()); // content-type: application/json