在读取有效负载并确认这是一个好请求之前,如何延迟返回响应?
在下面的代码中,该方法在触发data
事件之前返回,因此始终为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);
最佳答案
我只是将响应方法放入函数回调中。下面的代码。在邮递员工作。
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);