Creating CRUD application. I am able to send GET requests, but other requests are not getting sent.
The below line is causing error.
await Book.create(req.body);
app.js
const express = require('express');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
const app = express();
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
routes/api/book.js
const express = require('express');
const router = express.Router();
// Load book model
const { Book } = require('../../models/Book');
// @route GET api/books/test
// @description tests books route
// @access Public
router.get('/test', (req, res) => {
res.send('Book route testing!');
});
// @route GET api/books
// @description get all books
// @access Public
router.get('/', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(404);
res.json({nobooksfound: 'No Books found'});
}
});
// @route GET api/books/:id
// @description get single book by id
// @access Public
router.get('/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id);
res.json(book);
} catch (error) {
res.status(404);
res.json({ nobookfound: 'No Book Found' });
}
});
// @route POST api/books
// @description add or save book
// @access Public
router.post('/', async (req, res) => {
try {
await Book.create(req.body);
res.json({msg: 'Book added successfully'});
} catch (error) {
res.status(400);
res.json({
error: 'Unable to add this book'
})
}
});
// @route PUT api/books/:id
// @description update book
// @access Public
router.put('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndUpdate(req.params.id, req.body);
res.json({
msg: 'Updated Successfully'
})
} catch (error) {
res.status(400);
res.json({
error: 'Unable to update the Database'
})
}
});
// @route PUT api/books/:id
// @description delete book
// @access Public
router.delete('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndRemove(req.params.id, req.body);
res.json({msg: 'Book entry deleted successfully'});
} catch (error) {
res.status(404);
res.json({error: 'No such book'})
}
});
module.exports = router;
models/Book.js
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
description: {
type: String
},
published_date: {
type: Date
},
publisher: {
type: String
},
updated_date: {
type: Date,
default: Date.now
}
});
module.exports = Book = mongoose.model('book', BookSchema);
CodePudding user response:
I think you forget to use express.json()
middleware. It is a method inbuilt in express to recognize the incoming Request Object as a JSON Object.
app.js
const express = require('express');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
const app = express();
connectDB();
app.use(express.json())
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
And try this method to add a new one.
routes/api/book.js
// @route POST api/books
// @description add or save book
// @access Public
router.post('/', async (req, res) => {
try {
const book = new Book({
title: req.body.title,
author: req.body.author,
description: req.body.description
})
const result = await book.save();
console.log(result);
res.status(200).send('success')
} catch (error) {
res.status(400);
res.json({
error: 'Unable to add this book'
})
}
});
Hope it works.. Thank you!
CodePudding user response:
You are telling it to await. But await what. You must create a Promise to wait for.
Somewhere in you model you are going to need to create a Promise.
//here is an example so you can see the flow. I know it's mysql and not mongo, but a promise is a promis
pullWhiteList: async (phone) => {
data = new Promise((resolve, reject) => {
sql = "SELECT c.name AS client_name, w.* FROM api_whitelist w INNER JOIN api_client c ON w.client_id = c.client_id WHERE phone LIKE ? ORDER BY phone ASC LIMIT 10;";
db.query(sql, [phone '%'], (err, res, fields) => {
if (err) {
resolve(err);
} else {
resolve(res);
}
});
})
return await data;
},
CodePudding user response:
Error is you have not used body-parser. Replace app.js code with the below one.
const express = require('express');
const bodyParser = require('body-parser');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})