如何在POST有效负载验证之前延迟响应

时间:2014-11-18 01:30:02

标签: javascript node.js asynchronous

在读取有效负载并确认这是一个好请求之前,如何延迟返回响应?

在下面的代码中,该方法在触发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);

1 个答案:

答案 0 :(得分:2)

我只是将响应方法放入函数回调中。代码如下。在邮递员工作。

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);