[英]Error: Can't set headers after they are sent. Posting data
我正在使用此 API 發布公寓數據,正在注冊數據,但我總是收到錯誤消息:“發送后無法設置標題。”
我該如何解決這個實現以避免這種情況? 我用所有堆棧補充了代碼以訪問這個 API。
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/apartment', (req, res) => {
Apartment.findAll({
attributes: [
'apartment_id',
'apartment_floor',
'apartment_size',
'apartment_block_id',
'apartment_block_name',
'apartment_parking_id',
],
})
.then((apartments) => {
// console.log(documents);
res.sendStatus(200).send(apartments);
})
.catch((err) => console.log('erro: ', err));
});
app.get('/apartment/:apartment', (req, res) => {
Apartment.findByPk(
{
attributes: [
'apartment_id',
'apartment_block_id',
'apartment_floor',
'apartment_size',
'apartment_block_name',
'apartment_parking_id',
],
where: {
apartment_id: req.params.apartment_id,
apartment_block_id: req.params.apartment_block_id,
},
},
)
.then((documents) => {
res.sendStatus(200).send(documents);
})
.catch((err) => console.log("erro - API GET '/document: ", err));
});
app.post('/apartment', (req, res) => {
if (!req.body) {
return res.sendStatus(400).send({
message: 'Content can not be empty!',
});
} else {
Apartment.create({
apartment_id: req.body.apartment_id,
apartment_block_id: req.body.apartment_block_id,
apartment_block_name: req.body.apartment_block_name,
apartment_floor: req.body.apartment_floor,
apartment_size: req.body.apartment_size,
apartment_parking_id: req.body.apartment_parking_id,
});
}
return res
.sendStatus(200)
.send({ message: ' [CREATED REGISTER] API POST: /apartment' });
});
app.listen(config.port, () =>
console.log(`Server listening on port ${config.port}!`),
);
嘗試在 res.... 之前添加return
return res.sendStatus(400).send({
message: 'Content can not be empty!',
});
你的代碼:
res.sendStatus(200).send(apartments);
相當於:
res.status(200).send('OK').send(apartments)
這意味着您嘗試發送兩次響應:
res
.status(200) // Set status code of response
.send('OK') // Send the response!
.send(apartments) // Error: Can't set headers after they are sent
嘗試設置status
並使用send
:
res
.status(200) // Set status code of response
.send(apartments) // Send the response
還要在所有res.status().send()
中添加return
以避免每個請求多次嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.