在运行某些测试时,我当前收到“ ReferenceError:未定义记录器”错误。当我的端点位于我的app.js中时,没有发生这些错误。它们仅在我将端点移到路由器文件中时才开始发生。
我的所有端点都可以在邮递员中工作,并且可以检索数据,但是由于某些原因,我的所有测试均失败。路由器文件中是否缺少某些内容?
const express = require("express");
const uuid = require("uuid/v4");
const logger = require("../logger");
const { bookmarks } = require("../store");
const BookmarksService = require("../bookmarks-service");
const bookmarkRouter = express.Router();
const bodyParser = express.json();
bookmarkRouter
.route("/bookmarks")
.get((req, res, next) => {
const knexInstance = req.app.get("db");
BookmarksService.getAllBookmarks(knexInstance)
.then(bookmarks => {
res.json(bookmarks);
})
.catch(next);
})
.post(bodyParser, (req, res) => {
//implementation
for (const field of ["title", "url", "rating"]) {
if (!req.body[field]) {
logger.error(`${field} is required`);
return res.status(400).send(`${field} is required`);
}
}
const { title, url, rating, desc } = req.body;
if (!title) {
logger.error("Title is required");
return res.status(400).send("Invalid data");
}
if (!url) {
logger.error("Url is required");
return res.status(400).send("Invalid data");
}
if (!desc) {
logger.error("Desc is required");
return res.status(400).send("Invalid data");
}
const id = uuid();
const bookmark = {
id,
title,
url,
rating,
desc
};
bookmarks.push(bookmark);
logger.info(`Bookmark with bookmark ${id} created`);
res
.status(201)
.location(`http://localhost.8000/bookmark/${id}`)
.json(bookmark);
});
bookmarkRouter
.route("/bookmarks/:id")
.get((req, res, next) => {
//implementation
const { id } = req.params;
const bookmark = bookmarks.find(b => b.id == id);
const knexInstance = req.app.get("db");
BookmarksService.getById(knexInstance, id)
.then(bookmark => {
if (!bookmark) {
logger.error(`Bookmark with id ${id} not found`);
return res.status(404).send({
error: { message: `Bookmark doesn't exist` }
});
}
res.json(bookmark);
})
.catch(next);
})
.delete((req, res) => {
//implementation
const { id } = req.params;
const bookmarkIndex = bookmarks.findIndex(li => li.id == id);
if (bookmarkIndex === -1) {
logger.error(`Bookmark with id ${id} not found.`);
return res.status(400).send("Not found");
}
bookmarks.splice(bookmarkIndex, 1);
logger.info(`Bookmark with id ${id} deleted`);
res.status(204).end();
});
module.exports = bookmarkRouter;