I am using Node.js and mongoose now I got stuck here : The idea is to create a tour , I tested it with postman ,but I can't get anything from req.body . I have tried body-parser,but dosen't work neighter ,what is going on?
package.json
{
"name": "user-tour",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.1.0",
"morgan": "^1.10.0"
}
}
Tour SChema
const mongoose = require('mongoose');
const tourSchema = new mongoose.Schema({
name : {
type: String,
required :[true,"A tour must have a name"],
},
rating :{
type:Number,
default : 4.5
},
price : {
type : Number,
required:[true,"A tour must have aprice"]
}
});
const Tour = mongoose.model('Tour',tourSchema);
TourController: here ,I use req.body .And it suppose to get information from the client ,however ,it didn't get anything .Says,the name ,prcie etc are empty ..I have no idea what was going on .. Please help!!
exports.createTour = async(req, res) => {
try {
const newTour = await Tour.create(req.body);
res.status(201).json({
status:"success",
data:{
newTour
}
})
} catch (error) {
res.status(400).json({
status:'fail',
message : error.message
});
}
};
app.js:
const express = require('express');
const path = require('path');
const app = express();
const morgan = require('morgan');
const tourRoute = require('./routes/tourRouts');
const userRoute = require('./routes/userRoutes');
app.use(morgan('dev'));
app.use('/api/v1/tours',tourRoute);
app.use('/api/v1/users',userRoute);
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;
Server.js
const app = require('./app');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();
const port = process.env.PORT ||3000;
mongoose.connect(process.env.MONGO_URL,{ useNewUrlParser: true ,useUnifiedTopology: true})
.then(()=>console.log("connecting mongoDB"))
.catch(err => console.error("error :",err));
app.listen(port,()=>{
console.log('Backend server is running!');
});
I am follwing MVC rule by the way ..
CodePudding user response:
in app.js, following changes will do the job.
const express = require('express');
const path = require('path');
const app = express();
var bodyParser = require('body-parser'); //added
const morgan = require('morgan');
const tourRoute = require('./routes/tourRouts');
const userRoute = require('./routes/userRoutes');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(morgan('dev'));
app.use('/api/v1/tours',tourRoute);
app.use('/api/v1/users',userRoute);
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;