Trouble sending object with fetch - node.js

I am sending an object with fetch method from a webpage, that must then be appended to a json file on server. Here is how I am sending it:
fetch(url + '/send', {
method: 'POST',
body: {a: 1, b:2}
})
However, upon reading, all I get is an empty object.
When I send Body with Postman POST request, it works fine. Please help me find out why that is.
{
"a":"1",
"b": "2"
}

You need to send the appropriate Content-Type header with your POST request:
fetch(url + '/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {a: 1, b:2}
})

Related

Why am I getting an empty body as response from HTTP request Noe.js

so I am trying to send a http request to a server and as response I should get the body where all the information I need is in. When I then try to .parseJSON() the body I get an exception telling me that my body is empty. There is no way that the body is really empty so there has to be a mistake in the code.
I can not give you the whole code because of passwords and stuff like that.
Code:
public addVehicle(): Promise<void>{
return new Promise<void>((resolve, reject) => {
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: JSON.stringify({
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
})
}
let req = request.post(options, (err, res, body) => {
let rawAuth = JSON.parse(body);
console.log(body);
resolve();
})
})
}
Try removing the JSON.stringify().
I am assuming that your receiving API expects the fields in the body. Sending the data as string will hide the fields from the receiving API. It will just see one string object (not sure what the key will be tho).
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: {
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
}
}

In what format should a fetch POST request be created to access the Imagga API?

I am building a mobile application using React-Native that recommends clothing to users. I am using Imagga's API to get the colors of the clothing while excluding the background. I have tried to make a POST request using fetch from analyzing the node.js code given in the documentation:
image_file_b64 = "" + image_file_b64
//Extracting the colors from the object
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
let responseJson = await response.json()
console.log(responseJson)
However, the only output that I have received is (what is logged on the last line):
Object {
"status": Object {
"text": "Please provide content for processing.",
"type": "error",
},
}
I've worked with someone from Imagga to solve this issue, but he wasn't familiar with react native. he suggested changing the content-type to "application/x-www-form-urlencoded" or "application/x-www-form-urlencoded;charset=UTF-8", but neither have worked.
I am fairly confident that the problem is from the way that I set up my fetch. If anybody is familiar with the Imagga API, can you please identify what in the code is wrong or the mismatch in formatting between what Imagga expects and what I am giving it that results in it not thinking that I have given it input. Thanks!
the fetch body is not correct, the Content-Type that you use is JSON, why you send the string. modify it as the following, and try it.
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: {
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
I read the official API, it gives the node.js example. you can according to it and modify. If the above code is not successful, you can change the content-type to formdata
let params = {
image_base64: image_file_b64,
extract_overall_colors: 0,
};
let formData = new FromData()
formdata.append('RequestData',JSON.stringify(params))
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData)
})
this is the official api, and you can use postman software to test the request

How to make a POST with XML body/content-type header using request promise native in Node?

I need to make an XML POST (I know don't ask it's government...) and I can't get it to work with node request promise native.
I have tried turning my string of XML into a buffer, String(), .toString etc. The POST works if I turn json:true so I don't think it's a networking issue ( when passed a xml string with json true it sends a json like { 'variablename': 'stringed XML that I want to send as the body' } )
Here is what I'm working with. I've been banging my head for a while here any help appreciated.
Would ideally be promise/async.
Maybe I should look to find a XMLHttp request npm module?
var request_promise_native_options = {
method: 'POST',
uri: 'http://requestbin.fullcontact.com/198flbs1',
headers: {
'User-Agent': 'Request-Promise',
'Content-Type': 'text/xml'
//'Content-Length': Buffer.byteLength(my_xml_string) //I've tried multiple ways to use this
},
body: {
my_xml_string //also tried many ways here Buffer, String() etc
},
json: false // automatically stringifys body to json if true
};
request_promise(request_promise_native_options)
.then(function (response) {
console.log("success");
})
.catch(function (err) {
console.log(err);
})
Kudos to #kevin-b to help me see the obvious. Simply remove {}
var request_promise_native_options = {
method: 'POST',
uri: 'http://requestbin.fullcontact.com/198flbs1',
headers: {
'User-Agent': 'Request-Promise',
'Content-Type': 'text/xml'
'Content-Length': Buffer.byteLength(my_xml_string)
},
body: my_xml_string,
json: false // automatically stringifys body to json if true
};

Why is the inconsistency of data sent by my node.js code and Postman tool?

I have following node.js code to make a HTTP request:
var data = {
'Token' : 'cfe45090d19da5dbcc41a1f48c8cfd030e2af9d9',
'BrandId' : 2,
'Data': [{ /* one entry */
'Email': 'test#test.com',
'Name': 'test',
'Cphone': '5553338888',
}],
}
var formData = JSON.stringify(data)
var contentLength = formData.length
var headers = {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
}
var req_options = {
uri: 'https://webAPI',
method: 'POST',
headers: headers,
body: formData,
}
request(req_options, function (error, response, body) {
// response handling
)}
The HTTP post request is made successfully. I can get the server response with code 200. However, the server thinks my data is wrong (proprietary protocol).
So I test it with a HTTP request tool (Chrome extension - Postman), and here is the screen shot for the data I sent:
The server does reply that my data is right. (proprietary protocol)
What is wrong with the above code that would cause this inconsistency? (between the data I sent by the code and the data sent by Postman tool)
EDIT:
I want to modify the node.js code so that it can achieve what is done in Postman.
In node, you are encoding the data as JSON.
In Postman, it is encoding the data as form data.
You can make the reuqest in node by using this:
request({
uri: 'https://webAPI',
method: 'POST',
form: {
Token: 'cfe45090d19da5dbcc41a1f48c8cfd030e2af9d9',
BrandId: '2',
Data: JSON.stringify([{ /* one entry */
Email: 'test#test.com',
Name: 'test',
Cphone: '5553338888',
}])
}
})

Unable to overwrite header attribute Content-type in http calls

Following is the code which sends the request -
var requestData = {
"trigger_id":global.config.primusConfig.trigger_id,
//"mobile":global.config.primusConfig.trigger_id,
"email": global.config.primusConfig.email,
"params":{
"Amount":"200"
}
/*,
"files":{
“sample.pdf” : fileData
}*/
};
request({
headers: {
'cid': global.config.primusConfig.client_id,
'datetime': datetime,
'hash': hash,
'Content-type': 'application/json',
'From':'sandeepan#example.com'
},
url: global.config.primusConfig.apiEndPoint,
method: 'POST',
form: requestData,
body : req.rawBody,
},
function(error,httpResponse,body) {
console.log("Response handling part "+global.config.primusConfig.apiEndPoint+" formdata "+JSON.stringify(requestData));
if(error) {
console.log("Error "+error);
}
else {
console.log("Not error case- Body: "+body+" httpResponse:"+JSON.stringify(httpResponse));
callback();
}
});
From the logged httpResponse, I can see the request which was actually sent -
httpResponse:{"statusCode":500,"body":"\n <h1> 500 - Internal server error </h
1>\n <h2> </h2>\n","headers":{"content-type":"text/html; charset=utf-8","date"
:"Tue, 31 Oct 2017 15:19:13 GMT","etag":"W/\"38-3b8a0f21\"","x-powered-by":"Expr
ess","content-length":"56","connection":"Close"},"request":{"uri":{"protocol":"h
ttps:","slashes":true,"auth":null,"host":"domain.com","port":4
43,"hostname":"domain.com","hash":null,"search":null,"query":n
ull,"pathname":"/sendnotification","path":"/sendnotification","href":"domain.com/sendnotification"},"method":"POST","headers":{"cid":"
19","datetime":"2017-10-31 00:00:00","hash":"88072482e5125ed69f28ce60af859653049
9e11d","Content-type":"application/x-www-form-urlencoded","From":"sandeepan#exam
ple.com","content-length":70}}}
I can see the From attribute set to sandeepan#example.com, as I modified it, but I cannot see the Content-type changed to application/json.
Can someone explain? Any pointers?
form option implies application/x-www-form-urlencoded content-type: https://github.com/request/request/blob/master/request.js#L1249
If you are sending json, you need to use json option instead: https://github.com/request/request/blob/master/request.js#L1278
There is no need to set content-type explicitly:
request({
headers: {
'cid': global.config.primusConfig.client_id,
'datetime': datetime,
'hash': hash,
'From':'sandeepan#example.com'
},
url: global.config.primusConfig.apiEndPoint,
method: 'POST',
json: requestData
},

Resources