Liferay - how to retrieve body content of POST request in "serveResource" method

1k views Asked by At

I am issuing a POST request from my Angular 8 Liferay 7.3 Portlet and trying to get its contents in the serveResource method in the MVCResourceCommand class.

The frontend JS looks like this:

submit() {
    let message = {
        type: "form",
        body: this.model
      };
    
    this.http.post<any>("http://my/url", message).subscribe(response => {
        console.log(JSON.stringify(response));
    })
  }

The meesage hits the endpoint, so the backend is well configured. Based on this, this and this I have also set the "com.liferay.portlet.requires-namespaced-parameters=false" property in order namespaces not to be an issue - so, basically, every point in the check list is done and the request body should be accessible. Every post I read so far is talking about getting the request info with ParamUtil.getString(uploadRequest, "text");, but I am not sure how this should work if the body is a JSON object - I mean, how should I retrieve the value if the POST body looks like this:

{
    "firstVal": "abc",
    "secondVal": "def",
    "another": {
        "objectVal1": 1,
        "objectVal2": 2
    }
}
2

There are 2 answers

0
Victor On BEST ANSWER

Thanks to this post, I only came to this piece of code, which retrieves the body as a String:

String body = PortalUtil.getHttpServletRequest(resourceRequest).getReader().lines()
                .collect(java.util.stream.Collectors.joining(System.lineSeparator()));

Even though I solved my problem, I would like to know if there are other ways to do this.

0
MatthewDarton On

Dont expect that requests that work in every other framework will also work with Liferay. In this case you have to send everything as form data to the server. Fortunately Liferay provides a little utility method for this use case. Use this method for your body payload:

Liferay.Util.objectToFormData(payload)

Plus, if you dont provide namespaced attribute names, you also have to add this property to your portlet class: com.liferay.portlet.requires-namespaced-parameters=false.