I am somewhat new to Nodejs. I am working on a pair of Microservices, and I need one to post data to the other. I am using the request-promise-native library.
My code is to make the call is like this:
const options = {
method: 'POST',
uri: url,
formData: {
command: command,
version: version,
session_id: sid,
aicc_data: data
},
headers: {
'content-type' : 'application/x-www-form-urlencoded'
}
}
rp(options)
However, when I inspect the request as it come in to the other server, the header I have specified does not appear.
headers: { 'content-type': 'multipart/form-data; boundary=--------------------------395968157759002211606136',
host: 'localhost:9000',
'content-length': '513',
connection: 'close' }
What am I doing wrong?
options includes a formData object which enforces multipart/form-data.
You should add the form object instead when you want to use application/x-www-form-urlencoded.
Related
This Node.js code in a React-app doesn't work (fetch never resolves)
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Content-Type", "application/x-www-form-urlencoded");
const options = {
method: "POST",
body: formBody,
headers: headers
};
However, if you don't use the Headers interface, the code works:
const options = {
method: "POST",
body: formBody,
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
}
};
The example is from Express router where fetch returns an access token. I usually use the Headers interface and this specific case is the first time I have had problems. Is there a reason why I can't use the Headers interface in this case or is it a bug?
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
I want to send a get request but I need to insert my api key in to a 'x-api-key' header. I am using NodeJS + Express. Right now i'm using fetch from the "isomorphic unfetch" lib:
https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch
I use it in order to fetch data from the get request. I use this library specially because it works well on both the server and a client.
How should I add the header to my request? Thanks!
There's an example in the unfetch repository that shows how to add headers to fetch requests.
// complex POST request with JSON, headers:
fetch('/bear', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'Bearer XYZ'
},
body: JSON.stringify({ hungry: true })
}).then( r => {
open(r.headers.get('location'));
return r.json();
})
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
};
How can I execute this cURL shell command curl --data "{\"obj\" : \"1234556\"}" --digest "https://USERNAME:PASSWORD#www.someurl.com/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?
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
};