cuneyttyler
cuneyttyler

Reputation: 1355

Dojo request writes [object Object] to request

I have a request as below:

request.post("/webappbuilder/rest/layerGroups/" + this.appId + "/save", {
                data: {groupInfo: this.groupInfo},
                headers: {
                }
            }).then(function (r) {
                console.log("The server returned: " + r);
                context.setting.destroyLayerSelector();
                context.setting.createGroupableLayerSelector(this.groupInfo);
                context._promptSaved();
            });

When I look at the serverside log I see that this object is accepted as {"groupInfo":"[object Object]"}. It writes [object Object] to my this.groupInfo object.

What should I do to make the server accept the variable as a json object?

Upvotes: 1

Views: 236

Answers (1)

Frode
Frode

Reputation: 5710

When you provide an object as the data property, dojo assumes that you want to send the data as regular HTML form parameters to the server. Those parameters are just a list of plain key=value pairs.

So, if you want one such value to be a JSON representation of an object, you would have to do (note the JSON.stringify):

request.post("/webappbuilder/rest/layerGroups/" + this.appId + "/save", {
    data: {groupInfo: JSON.stringify(this.groupInfo)},
    headers: {...}
}).then(...

However, this actually means the groupInfo is sent to the server like this:

groupInfo=%7B%22id%22%3A32%2C%22name%22%3A%22Group1%22%7D

On your server, you will then likely see something like:

 {"groupInfo": "{id:32,name:\"Group1\"}"}

So you see, the value is still just a string! Remember, HTTP parameters are just key=value pairs. Here, the key is groupInfo, and the value is a string which happens to contain JSON (but HTTP doesn't know that, so you will have to parse it yourself in your application).

However, a POST request doesn't have to be boring key=value pairs. The request body is just text, so we can put anything there: XML, JSON, you name it. We can tell the server what the format is with a Content-Type header. If your web application backend framework is clever, it may inspect the header and parse the request body into an object for you.

request.post("/webappbuilder/rest/layerGroups/" + this.appId + "/save", {
    data: JSON.stringify( {groupInfo: this.groupInfo} ),
    headers: {"Content-Type": "application/json"}
}).then(...

Note that here, we have moved the JSON.stringify call so that it encloses the entire data object. That means the data property is actually a string, and dojo will use it as the request body directly. We have also provided the Content-Type header as a clue to the web server.

If you do not provide the Content-Type header, dojo will send the default "application/x-www-form-urlencoded", even though your request body does not contain key=value pairs.

Upvotes: 1

Related Questions