我正在尝试获取请求,但是它在app.js
res.json
行上一直失败。
app.js
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.json({ error: err.message });
});
模型
const fs = require("fs");
const fileName = "./seatData.json";
const file = require(fileName);
const Seat = function(seat) {
this.seat = seat.seat;
this.seatNumber = seat.seatNumber;
this.price = seat.price;
this.available = seat.available;
this.disabilityAccessible = seat.disabilityAccessible;
};
Seat.findSeat = seatNumber => {
return file.find(obj => obj.seatNumber === seatNumber);
};
Seat.getSeatByNumber = function(seatNumber, result) {
this.seat = this.findSeat(seatNumber);
if (Object.keys(this.seat).length > 0) {
result(null, this.seat);
} else {
result({ error: true, message: "Seat not found" });
}
};
Seat.bookSeat = function(seatNumber, result) {
this.seat = this.findSeat(seatNumber);
if (this.seat === undefined || Object.keys(this.seat).length === 0) {
result({ error: true, message: "Seat not found" });
}
const newSeatData = file.map(row => {
if (row.seatNumber === seatNumber) {
row.available = false;
this.seat = row;
}
return row;
});
fs.writeFile("./seatData.json", newSeatData, "utf-8", function(err) {
if (err) {
result({ error: true, message: "failed to update booking" });
}
});
result(null, this.seat);
};
module.exports = Seat;
路线
router.get(
"/bookSeat/:seatNumber",
[
check("seatNumber")
.exists(true)
.withMessage("Must pass seatNumber")
.matches(/^[0-9][a-z]$/i)
.withMessage("must start with a number(0-9) and end with a letter")
],
actions.update_seat
);
控制器
exports.update_seat = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(422).json({ error: true, message: errors.array() });
}
console.log(errors);
Seat.bookSeat(req.params.seatNumber, (err, seat) => {
if (err) res.json(err);
else res.json(seat);
});
};
我正在尝试致电bookSeat
https://codesandbox.io/s/elucidate-api-fokd8
答案 0 :(得分:1)
发生错误后,您仍然可以继续执行:
if (!errors.isEmpty()) {
res.status(422).json({ error: true, message: errors.array() });
return; // <<!!
}