在 Moleculer 中获取 body POST 请求

Get body POST request in Moleculer

我在 ReactJs 中使用 Fetch 向 api Moleculer 发送请求,如下所示:

 var data ={
            'ordername' : 'PUG',
            'receivername' : 'AnSama'
        }
        fetch(url,{
            method: 'POST',
            header: {              
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body : data
        })
            .then(res => {return res.json()})
                .then(
                    (result) => {
                        alert(JSON.stringify(result));
                    },
                    (error) => {
                        alert('error');
                    }
                )

然后,我想在 Moleculer(NodeJS 框架)中获取请求主体。我能怎么做?

在路由器设置中 Moleculer API Gateway the JSON body is always parsed and reachable via ctx.params. If you want to send header values to the service, use the onBeforeHook

broker.createService({
    mixins: [ApiService],
    settings: {
        routes: [
            {
                path: "/",
                onBeforeCall(ctx, route, req, res) {
                    // Set request headers to context meta
                    ctx.meta.userAgent = req.headers["user-agent"];
                }
            }
        ]
    }
});

除了@Icebob 的回答之外,如果您的 POST API 异步处理请求(很可能会)并返回承诺。这是一个例子(这就是我们使用的方式):

actions : {
    postAPI(ctx) {
        return new this.Promise((resolve, reject) => {
            svc.postdata(ctx, (err, res) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(res);
                }
            });
        })
            .then((res) => {
                return res;
            }, (err) => {
                return err;
            });
    }
}