Hi,
I would like to know how to send this structure:
[
{
"sha1": "3722059cc37f7a56db064c1911f063da826cb211",
"size": 36
},
{
"sha1": "a9993e364706816aba3e25717850c26c9cd0d89d",
"size": 1
}
]
In a PUT request.
I am developing a Cloud foundry client for Node.js and I have this doubt.
http://apidocs.cloudfoundry.org/214/resource_match/list_all_matching_resources.html
I have this request:
var url = this.API_URL + "/v2/resource_match";
var headers = {
'Accept': 'application/json',
'Authorization': token_type + " " + access_token,
'Content-Type': 'application/x-www-form-urlencoded'
};
return new Promise(function (resolve, reject) {
request.put({url:url, headers: headers}, function optionalCallback(err, httpResponse, body) {
if (err) {
console.error('upload failed:', err);
return reject(error);
}
console.log('Upload successful! Server responded with:', body);
return resolve(body);
});
});
but my question is how to add the JSON to the request.
What is the best way?
Many thanks in advance.
Juan Antonio
{body:JSON.stringify({object})}
Hi,
I have tested the idea, but I receive the following error:
Error: Error: Argument error, options.body.
Full code:
HttpUtils.prototype.DEBUG = function(method,url,headers,qs,body,httpStatusAssert){
var resources = [
{
"sha1": "3722059cc37f7a56db064c1911f063da826cb211",
"size": 36
},
{
"sha1": "a9993e364706816aba3e25717850c26c9cd0d89d",
"size": 1
}];
var options = {
method: 'PUT',
url: url,
headers: headers,
body: {body:JSON.stringify(resources)}
};
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if(error){
return reject(error);
}
console.log(body);
return resolve(body);
});
});
}
In what option, I have to append: {body:JSON.stringify({object})} in the request?
I am using:
"request": "^2.45.0"
Nope, just {body:JSON.stringify({object})}
- _string_. Also make sure you are using the latest version of request.
Many thanks, it runs nice!
Please note, this has changed and per the README section related to options
it should instead be request({body: <JSON-serializable-object>, json: true, url:...})
and not the _stringified_ object mentioned above when json is true. I found this confusing when mixing requests in my code.
I'll add to this, since I had a similar issue. I needed to not wrap the value of "body" in options with object braces. So this was my valid code:
var solution = [ {"x": 0, "y": 0}, {"x": 1, "y": 0},
{"x": 2, "y": 0},
{"x": 2, "y": 1},
{"x": 2, "y": 2},
{"x": 3, "y": 2},
{"x": 3, "y": 3}
]
var options = {
method: 'POST',
url: url,
headers: headers,
body: solution
};
rp(options)...
}
I use nodejs http request
Change
request.write(JSON.stringify(data));
To
request.write(JSON.stringify({body: data}));
It's work for me
Most helpful comment
{body:JSON.stringify({object})}