Michael Mauracher
Michael Mauracher

Reputation: 201

Loopback.io rest connector - json post not working

I'm trying to proxy a rest service with the loopback-rest-connector. The remote rest service method is POST and one argument is required. When I call the loopback endpoint with a querystring then everything works fine. When I call the service with a body json object I get the error that the required variable is undefined but the arguments are inside the object ctx.req.body. Loopback does not see them. I tried to add the bodyparser middleware but it did not worked either.

Datasource.js

{
      "db": {
        "name": "db",
        "connector": "memory",
        "file": "db.json"
      },

      "rest": {
        "name": "rest",
        "connector": "rest"
      },
      "geoRest": {
            "connector": "rest",
            "debug": "true",
            "operations": [{

                "template": {
                    "method": "POST",
                    "url": "https://url/endpoint",
                    "headers": {
                        "accept": "application/json",
                        "content-type": "application/json",
                        "Authorization": "sdfsdf"
                    },
                    "body": {
                        "address": "{^address:string}",
                        "country": "{country:string}"
                    }
                },
                "functions": {
                    "geocode": ["address", "country"]
                }
            }]
        }
    }

Model definition

{
  "name": "geoRest",
  "plural": "geoRests",
  "base": "Model",
  "strict": true,
  "idInjection": false,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

Model Config

"geoRest": {
    "dataSource": "geoRest",
    "public": true
  }

Upvotes: 2

Views: 2058

Answers (1)

ashwinik001
ashwinik001

Reputation: 5163

Try using form instead of body. So modified template section should be something like below:

"template": {
    "method": "POST",
    "url": "https://url/endpoint",
    "headers": {
        "accept": "application/json",
        "content-type": "application/json",
        "Authorization": "sdfsdf"
    },
    "form": {
        "address": "{^address:string}",
        "country": "{country:string}"
    }
},

Using form will send your parameters just like a form is submitted using POST method and hence as part of the request body.

While using body or req sends it appending to the request-url i.e. essentially in the form of query parameters.

Upvotes: 2

Related Questions