Skip to content

Commit 2b1ee4a

Browse files
committed
Ensure headers haven't sent prior to send
1 parent a4d9b92 commit 2b1ee4a

1 file changed

Lines changed: 12 additions & 4 deletions

File tree

scrud.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,10 @@ function handleRequest (req, res) {
160160
let jwt = (headers.authorization || '').replace(/^Bearer\s/, '')
161161
let callHandler = () => {
162162
if (!hasBody[action]) return handler(req, res, name, action)
163-
bodyParse(req).then((body) => {
163+
return bodyParse(req).then((body) => {
164164
req.params = Object.assign(body, req.params)
165165
return handler(req, res, name, action)
166-
})
166+
}).catch((e) => sendErr(res, e))
167167
}
168168
if (resource.skipAuth && resource.skipAuth[action]) return callHandler()
169169
authenticate(jwt).then((authData) => {
@@ -173,15 +173,23 @@ function handleRequest (req, res) {
173173
}
174174

175175
function sendData (res, data = null) {
176+
if (res.headersSent) {
177+
logIt(new Error(`can't send data after headers sent`), 'warn')
178+
return Promise.resolve()
179+
}
176180
return new Promise((resolve, reject) => {
177181
res.end(JSON.stringify({data, error: null}))
178182
return resolve()
179183
})
180184
}
181185

182-
function sendErr (res, err = new Error(), code = 500) {
186+
function sendErr (res, err, code = 500) {
187+
res.statusCode = code
188+
if (!err || res.headersSent) {
189+
logIt(err || new Error(`can't send error after headers sent`), 'warn')
190+
return Promise.resolve()
191+
}
183192
return new Promise((resolve, reject) => {
184-
res.statusCode = code
185193
logIt(err, 'fatal')
186194
err = err instanceof Error ? (err.message || err.name) : err.toString()
187195
res.end(JSON.stringify({data: null, error: err}))

0 commit comments

Comments
 (0)