Node.js: http.js:691 throw new Error('Can\\'t set headers after they are sent.')

拜拜、爱过 提交于 2019-12-05 20:40:25

In

app.get('/api/employees/:employeeId', function() {...});

you are using res.json twice. Lets assume Employee.findById returns the results first. Then,

res.json(employee)

is already sent. Then the code enters Employee.find callback with a slight delay. This again triggers res.json(). But since the response to your request is already sent, it can't send another response to the same request.

This condition is throwing the error.

There are two ways to solve this.

  1. Nested callbacks - Call Employee.find inside Employee.findById callback.
  2. Add conditions in both the callbacks to check if other callback is complete. Then send a single response.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!