【问题标题】:Get body POST request in Moleculer在 Moleculer 中获取正文 POST 请求
【发布时间】:2018-08-17 18:21:07
【问题描述】:

我在 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 框架)中获取请求主体。我能怎么做?

【问题讨论】:

    标签: node.js api request moleculer


    【解决方案1】:

    除了@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;
                });
        }
    }
    

    【讨论】:

      【解决方案2】:

      Moleculer API Gateway 中,JSON 正文始终通过ctx.params 进行解析和访问。如果您想向服务发送标头值,请在路由器设置中使用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"];
                      }
                  }
              ]
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2022-01-07
        • 1970-01-01
        • 2023-03-16
        • 2018-05-10
        • 2015-10-15
        相关资源
        最近更新 更多