【发布时间】:2021-11-16 07:53:01
【问题描述】:
创建 CRUD 应用程序。我可以发送 GET 请求,但没有发送其他请求。
以下行导致错误。
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);
【问题讨论】:
-
您遇到的错误是什么?代码行是否执行但没有按预期工作,或者甚至没有达到?
-
您的标题似乎不正确。正在发送 post 请求,服务器正在接收它,并且正在发生错误。
-
@ChristianFritz 该行正在执行,但随后进入 catch 块
-
是的,@KevinB 你猜对了
-
Nikita,你说它进入了 catch 块,但在那个 catch 块中你不打印错误?为什么不?这将是调试它的明显方法。