Node報錯: can't not set headers after they are sent to the client

今天在開發的時候,Node服務器端報了這個錯誤,根據他的提示不難發現,我在響應之後又去執行了設置響應頭部的操作,導致了這一錯誤,下面我把代碼發一下,給大家做個參考:

user.save((err,rst) => {
    if (err) {
         console.log("Error:" + err);
         ctx.response.type = 'json';
         ctx.response.body = { error: err };
     }
     else {
         console.log("Res:" + rst);
         ctx.response.type = 'json';
         ctx.response.body = { success: 'regist success!' };
     }
 })

這裏呢,是執行了一個Post註冊的操作,使用的mongoose連接mongodb 進行用戶存儲,就在這裏操作,看似我並沒有提前設置headers,但是他實際上在執行save完成之前就已經執行了回調函數中的內容了,導致報錯。這裏多說一句,其實如果你不返回一個response,他會默認返回一個404 Not Found,故你再次設置response他就會給你報這個錯誤。解決辦法這裏我使用了es6的新特性 async … await。

var obj = await user.save();
if (obj.err) {
      ctx.response.type = 'json';
      ctx.response.body = { error: err };
  } else {
      ctx.response.type = 'json';
      ctx.response.body = { success: 'regist success!' };
 }

這一操作可以保證執行完成save操作,然後獲取到save之後返回的信息,再進行返回執行結果,他也不回給你返回not found了,從而不會報錯 set headers after they are sent to client.
更多示例可以參考:koa not found

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章