Reputation: 478
How can I execute this cURL shell command curl --data "{\"obj\" : \"1234556\"}" --digest "https://USERNAME:[email protected]/rest-api/v0/objectpost"
that correctly returns expected values using node's request package?
I tried with those post options but got no success:
var request = require('request');
var body = {"obj" : "1234556"};
var post_options = {
url: url,
method: 'POST',
auth: {
'user': 'USERNAME',
'pass': 'PASSWORD',
'sendImmediately': false
},
headers: {
'Content-Type': 'text/json',
'Content-Length': JSON.stringify(body).length,
'Accept': "text/json",
'Cache-Control': "no-cache",
'Pragma': "no-cache"
},
timeout: 4500000,
body: JSON.stringify(body)
}
request(post_options, callback);
This way the body is not parsed (got something like missing required parameter: "obj"
), and I can't understand if it's a matter of encoding or just passing it in the wrong place (i.e. should not be the body). Any suggestion?
Upvotes: 0
Views: 829
Reputation: 106736
By default, cURL will send a Content-Type: application/x-www-form-urlencoded
unless you use -F
(which changes it to Content-Type: multipart/form-data
) for your fields or explicitly override the header (e.g. -H 'Content-Type: application/json'
). However, the data being sent by your cURL example seems to be JSON. So the server will get confused and won't correctly find the data it's expecting.
So the solution is one of two options:
Try application/json
as a Content-Type
in your code instead of text/json
.
Actually use urlencoded formatted data instead of JSON by using the form
property. request
will take that form
object and do all the conversions and setting of headers, etc. for you. For example:
var post_options = {
url: url,
method: 'POST',
auth: {
user: 'USERNAME',
pass: 'PASSWORD',
sendImmediately: false
},
timeout: 4500000,
form: body
};
Upvotes: 3