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

How to delay response until POST payload is validated

本文关键字:延迟 响应 负载 有效 验证 POST      更新时间:2023-09-26
如何

延迟返回响应,直到我读取有效负载并确认它是一个好的请求?

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