我有一個帶有簡單呼叫的 node/express api,它在第一次被呼叫時作業,但不是第二次。結果基本上是空的,所以它應該總是以“未找到帖子”作為回應,它在第一次被呼叫時就會這樣做。
export const getAllBlogs = async (req, res) => {
const posts = await Blog.find({});
if(posts == 0) res.send('No posts found');
res.send(posts);
};
我遺漏了什么會導致以下錯誤:錯誤 [ERR_HTTP_HEADERS_SENT]:在將標頭發送到客戶端后無法設定標頭
uj5u.com熱心網友回復:
res.send 被呼叫了兩次,這是錯誤的原因。你可以這樣改變它。if(posts == 0) { res.send('No posts found'); } else { res.send(posts); }
uj5u.com熱心網友回復:
發生這種情況是因為res.send()在您的路線中使用了兩次 if posts == 0。你可以這樣改變它:
export const getAllBlogs = async (req, res) => {
const posts = await Blog.find({});
if(posts == 0) {
res.send('No posts found');
else {
res.send(posts);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405572.html
標籤:
下一篇:資料庫連接問題和api呼叫
