1

我怎样才能在 Meteor restivus中获得 POST 原始身体?尝试了一些东西,但它不起作用。这是代码。

if(Meteor.isServer) {
    var Api = new Restivus({
        useDefaultAuth: true
    });

    Api.addRoute('test', {authRequired: false}, {
        post: {
            action: function() {
                var response;
                var readable = this.request;
                var rawBody = "";
                readable.on('data', function(chunk) {
                    rawBody += chunk;
                });
                readable.on('end', Meteor.bindEnvironment(function() {
                    //dosometing and insert into Collection
                    //make response data
                }));
                return response;
            }
        }
    });
}

它继续返回响应,然后readable.on('end'.. ) 返回 null 是错误的。如果我将返回响应移入readable.on('end'...),也会出现同样的错误。我想如果可以等待 POST 返回直到readable.on('end'..)完成,它会工作,但我不知道如何。

4

1 回答 1

0

您可以使用node-fibersFuture直到waitreadable.on('end', ..)调用。

 if(Meteor.isServer) {
        var Future = Npm.require('fibers/future');
        var Api = new Restivus({
            useDefaultAuth: true
        });
    
        Api.addRoute('test', {authRequired: false}, {
            post: {
                action: function() {
                    var response;
                    var readable = this.request;
                    var rawBody = "";
                    var future = new Future();

                    readable.on('data', function(chunk) {
                        rawBody += chunk;
                    });

                    readable.on('end', Meteor.bindEnvironment(function() {
                        //dosometing and insert into Collection
                        //make response data
                        future.return(response); //response is what you want to return
                        // you can also throw error using future.throw(err);
                    }));

                    return future.wait();
                }
            }
        });
    }
于 2016-03-08T03:41:50.760 回答