How do I delay returning the response until I have read the payload and confirmed it is a good request?
In the following code, the method is returning before the data
event is fired, thus it is always 200
.
http.createServer(function(request, response) {
var payloadValid = true; // <-- Initialise an 'payloadValid' variable to true
request.on('data', function(chunk) {
payloadValid = false; // <-- set it to true when the payload is examined
});
/*
* This is executed before the payload is validated
*/
response.writeHead(payloadValid ? 200 : 400, { // <-- return 200 or 400, depending on the payloadValid variable
'Content-Length': 4,
'Content-Type': 'text/plain'
});
response.write('Yup!');
response.end();
})
.listen(PORT_NUMBER);
I would just put the response method into the function callback. Code below. Works in postman.
var http = require('http');
http.createServer(function(request, response) {
var payloadValid = true;
request.on('data', function(chunk) {
payloadValid = false;
response.writeHead(payloadValid ? 200 : 400, {
'Content-Type': 'text/plain'
});
response.write('Yup!');
response.end();
});
})
.listen(8080);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다