运行中间件检索id出现错误
<p><span>最近有个项目给学校图书馆的书籍做个一个简单的API。有一组正在访问的书籍,按 id 显示书籍,显示所有书籍,添加书籍,更新书籍。</span><span>我更改了一些代码以合并中间件。</span></p>
<p><span>没有中间件,我可以通过 id 检索书籍,但是用中间件的时候出现了错误。</span></p>
<p>各位大佬求解答!</p>
<p> </p>
<p><strong><span>应用程序.js</span></strong></p>
<pre class=“language-java”><code>const express = require(‘express’);
const bookRouter = express.Router();
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
const Book = require(’./models/bookModel’);
const app = express();
const port = process.env.PORT || 8081;
const url = ‘mongodb://localhost/bookAPI’;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
mongoose.connect(url).then(() => console.log(“Connected to db”));
bookRouter.route(’/books’)
.post((req, res) => {
const book = new Book(req.body);
book.save();
return res.status(201).json(book);
})
.get((req, res) => {
const query = {}
if(req.query.genre) {
query.genre = req.query.genre;
}
Book.find((err, books) => {
if(err) {
return res.send(err);
}
return res.json(books);
});
});
bookRouter.use(’/books/:bookId’, (req, res, next) => {
Book.findById(req.params.bookId, (err, book) => {
if(err) {
return res.send(err);
}
if(book) {
req.book = book;
return next();
}
return res.sendStatus(404);
});
});
bookRouter.route(’/books/:bookId’)
.put((req, res) => {
const { book } = req;
book.title = req.body.title;
book.author = req.body.author;
book.genre = req.body.genre;
book.read = req.body.read;
book.save();
return res.json(book);
})
.get((req, res) => {
res.json(book);
});
app.use(’/api’, bookRouter);
app.get(’/’, (req, res) => {
res.send(“Hello World”);
});
app.listen(port, () => {
console.log(Listening on port: ${port}
);
});
</code></pre>
<p><strong><span>bookModel.js</span></strong></p>
<pre class=“language-java”><code>const mongoose = require(‘mongoose’);
const {Schema} = mongoose;
const bookModel = new Schema({
title: {type:String},
author: {type:String},
genre: {type:String},
read: {type:Boolean, default: false},
});
module.exports = mongoose.model(“Book”, bookModel);</code></pre>
<p>报错</p>
<pre class=“language-markup”><code>ReferenceError: book is not defined
at D:\Desktop\lab10\app.js:63:14
at Layer.handle [as handle_request] (D:\Desktop\lab10\node_modules\express\lib\router\layer.js:95 :5)
在下一个 (D:\Desktop\lab10\node_modules\express\lib\router\route.js:137:13)
在下一个 (D:\Desktop\lab10\node_modules\express\lib\router\route.js :131:14)
在 Route.dispatch (D:\Desktop\lab10\node_modules\express\lib\router\route.js:112:3)
在 Layer.handle [as handle_request] (D:\Desktop\lab10\node_modules \express\lib\router\layer.js:95:5)
在 D:\Desktop\lab10\node_modules\express\lib\router\index.js:281:22
在参数 (D:\Desktop\lab10\node_modules\ express\lib\router\index.js:360:14)
在参数 (D:\Desktop\lab10\node_modules\express\lib\router\index.js:371:14)
在 Function.process_params (D:\Desktop\lab10\node_modules\express\lib\router\index.js: 416:3)</code></pre>