1

I use Fetch in ReactJs to send a request to api Moleculer like this :

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

Then, I want to get body of request in Moleculer (Framework of NodeJS). How can i do?

Icebob
  • 1,132
  • 7
  • 14
M.Quynh
  • 13
  • 1
  • 5

2 Answers2

2

In 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 in router settings.

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
  • 1,132
  • 7
  • 14
0

In addition to the @Icebob answer, If your POST API process request Asynchronously(most likely it will)& returning a promise. Here is an example(This is how we are using) :

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