gpt4 book ai didi

javascript - 表达错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client

转载 作者:行者123 更新时间:2023-12-02 23:06:22 26 4
gpt4 key购买 nike

我正在尝试执行 get 请求,但在 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
);

Controller

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

最佳答案

发生错误后,仍然继续执行:

 if (!errors.isEmpty()) {
res.status(422).json({ error: true, message: errors.array() });
return; // <<!!
}

关于javascript - 表达错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57578127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com