Skip to content

Commit

Permalink
400 on bad requests, dont crash
Browse files Browse the repository at this point in the history
  • Loading branch information
calebTomlinson committed May 12, 2020
1 parent 90af6b4 commit a1722b2
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,12 @@ exports.requestHandler = function (req, res) {
function sendTimestamp(req, res) {
if (req.body) {
// express.js or similar
sendTimeStampResponse(res, req.body);
sendTimeStampResponse(null, res, req.body);
}
else {
// node.js
readRequestBody(req, function (err, body) {
sendTimeStampResponse(res, body);
sendTimeStampResponse(err, res, body);
});
}
}
Expand All @@ -124,27 +124,36 @@ function readRequestBody (req, callback) {
}
});
req.on('end', function () {
callback(null, JSON.parse(body));
try {
callback(null, JSON.parse(body));
} catch {
callback(new Error('Invalid json in post body'));
}
});
}

function sendTimeStampResponse (res, body) {
function sendTimeStampResponse (err, res, body) {
if (err) {
res.writeHead(400);
res.end(err.message);
} else {

var data = {
id: 'id' in body ? body.id : null,
result: Date.now()
};
var data = {
id: 'id' in body ? body.id : null,
result: Date.now()
};

// Set content-type header
res.setHeader('Content-Type', 'application/json');
// Set content-type header
res.setHeader('Content-Type', 'application/json');

if(res.status && res.send) {
// express.js or similar
res.status(200).send(JSON.stringify(data));
} else {
// node.js
res.writeHead(200);
res.end(JSON.stringify(data));
if(res.status && res.send) {
// express.js or similar
res.status(200).send(JSON.stringify(data));
} else {
// node.js
res.writeHead(200);
res.end(JSON.stringify(data));
}
}

}
Expand Down

0 comments on commit a1722b2

Please sign in to comment.