我有一个我正在处理的 node.js API,它在 URL 中有一些参数变量。
我需要完成的任务之一是,当特定 id 无效时(如在 sqlite 数据库中不存在 id 号),它返回 404
典型的网址设置是localhost/api/employees/:id/timesheets
我需要做的是当:id
sqlite 数据库中不存在它时,返回 404 但是无论我现在做什么,它都会返回 201。
请从时间表端点在下面找到我的代码,让我知道我哪里出错了,非常感谢。简而言之,假设员工 200 不存在(所以localhost/api/employees/200/timesheets
- 我希望在该时间表端点上显示 404,但目前它给出了 200 而不是 404。请注意,目前没有任何方法按照要求提供 404在下面的代码中
谢谢
const express = require('express');
const timesheetsRouter = express.Router({mergeParams: true});
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database(process.env.TEST_DATABASE || './database.sqlite');
timesheetsRouter.param('id', (req, res, next, id) => {
req.id = id;
console.log('doing name validations on ' + id);
db.get('Select * from Timesheet where employee_id = $id', {$id: id}, (error, timesheet) => {
if (error) {
next(error);
} else if (timesheet) {
req.timesheet = timesheet;
next();
} else {
res.sendStatus(404);
}
});
});
timesheetsRouter.get('/', (req, res, next) => {
db.all(`select * from Timesheet where employee_id = $id`, {$id: req.params.id}, (error, rows) => {
//console.log('executed sql');
//console.log(rows);
if (!rows) {
console.log('triggered');
//console.log('this is error ' + error);
res.sendStatus(404);
//next();
} else {
console.log(rows + ' This is rows');
res.status(200).json({timesheets: rows});
}
});
});
const validateTimesheet = (req, res, next) => {
//console.log('this is menu ' + req.body);
if (!req.body.timesheet.hours || !req.body.timesheet.rate || !req.body.timesheet.date) {
return res.sendStatus(400);
}
next();
}
timesheetsRouter.post('/', validateTimesheet, (req, res, next) => {
//console.log('this is mmenu post body ' + req.body.menu.title);
db.run(`INSERT INTO Timesheet(hours, rate, date, employee_id) VALUES ($hours, $rate, $date, $employee_id)`,
{ $hours: req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date: req.body.timesheet.date, $employee_id:req.params.id}, function (error) {
if (error) {
('error with sql ' + console.log(error));
return res.sendStatus(500);
}
db.get(`SELECT * FROM Timesheet WHERE id = ${this.lastID}`, (err, row) => {
if (err) {
//console.log(err);
return res.sendStatus(500);
} else {
res.status(201).json({timesheet: row});
}
});
})
})
timesheetsRouter.put('/:id', validateTimesheet, (req, res, next) => {
const timesheetToUpdate = req.body.employee;
//console.log(artistToUpdate);
//console.log("this is params " + req.params.id);
db.run(`UPDATE Timesheet SET hours=$hours, rate=$rate, date=$date where id=${req.params.id}`,
{$hours:req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date:req.body.timesheet.date}), function (error, row) {
console.log(row);
if (error) {
console.log('this is error ' + error);
return res.status(404).send();
}
}
db.get(`SELECT * from Timesheet where id = $id`, {$id: req.params.id}, (error, row) => {
if(!row) {
return res.sendStatus(500);
}
//console.log(row);
res.status(200).send({timesheet: row});
})
});
module.exports = timesheetsRouter;