2017-02-10 33 views
1

我是新來的節點,我有一個簡單的情況,我在某​​個節點/快速應用的端點上發佈消息。問題是,我得到:未處理的承諾拒絕 - 錯誤:發送後無法設置標頭

POST /api/v2/user 500 25.378 ms - 54 
(node:19024) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent. 
(node:19024) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

相關的代碼,我有它產生是這樣的:

router.post('/', (req, res, next) => { 
    return authHelpers.createUser(req, res) 
    .then((user) => { 
     return localAuth.encodeToken(user[0]); 
    }) 
    .then((token) => { 
     res.status(201).json({ 
     status: 'success', 
     message: 'User Created', 
     token: token 
     }); 
    }) 
    .catch((err) => { 
     res.status(500).json({ 
     status: 'error' 
     }); 
    }); 
}); 

然後:

function createUser(req, res) { 
    return handleErrors(req) 
    .then(() => { 
     const salt = bcrypt.genSaltSync(); 
     const hash = bcrypt.hashSync(req.body.password, salt); 
     return knex('users') 
     .insert({ 
      email: req.body.email, 
      first_name: req.body.first_name, 
      last_name: req.body.last_name, 
      username: req.body.username, 
      password: hash 
     }) 
     .returning('*'); 
    }) 
    .catch((err) => { 
     res.status(410).json({ 
     status: err.message 
     }); 
    }); 
} 

function handleErrors(req) { 
    return new Promise((resolve, reject) => { 
    if (req.body.username.length < 6) { 
     reject({ 
     message: 'Username must be longer than 6 characters' 
     }); 
    } else if (req.body.password.length < 6) { 
     reject({ 
     message: 'Password must be longer than 6 characters' 
     }); 
    } else { 
     resolve(); 
    } 
    }); 
} 

我知道,如果我刪除res.status(500).json({status:'error'});具體而言,那麼錯誤消失,但我不知道這是否正確。

任何線索到底是什麼是我的錯誤,以及如何解決?

+0

我忘了提及,當用戶名,密碼不夠長或用戶名已經存在於數據庫中時出現此錯誤消息。 –

回答

2

您正嘗試發送回覆兩次。捕捉錯誤

res.status(410).json({ 
    status: err.message 
    }); 

再搭上後首當,承諾繼續鏈,直到正常路線:

return localAuth.encodeToken(user[0]); 

哪個失敗,因爲用戶是不確定的,並拋出一個異常..所以調用錯誤處理程序而你正試圖再次發送響應,而是因爲它已經被一次該錯誤是在最後拋出

res.status(500).json({ 
    status: 'error' 
    }); 

控制檯日誌發送失敗的話,我敢河畔e它就像

TypeError: Cannot read property '0' of undefined 
相關問題