Reputation: 7598
I want to send data and headers using request (what's below in curl I would like to achieve with request), below is the function foobar()
where the request is taking place. For some reason the below is wrong, but there are no error messages or warnings. Any thoughts?
request used = https://www.npmjs.com/package/request#custom-http-headers
function foobar(a, i, callback){
var requestOptions = {
url: 'http://someurl/endpoint',
headers: {
'X-ELS-Authentication':'FOO',
'Content-Type':'application/json',
'Accept':'application/json'
},
data: {
'xqueryx': "<foo><bar:word path=\""+a+"\">"+i+"</bar:word></foo>'
'start': 0,
'count': 100,
'fields': "*"
}
};
function makeRequest(error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body));
}
}
request(requestOptions, makeRequest);
}
UPDATE:
This curl equivalent does work:
curl_render = 'curl -H "'+curl_request.headers[0]+'" '+
' -H "'+curl_request.headers[1]+'" '+
' -H "'+curl_request.headers[2]+'" '+
" --data '"+JSON.stringify(curl_request.data)+"' "+
curl_request.url;
exec(curl_render, function (error, stdout, stderr) {
cb(stdout);
});
Upvotes: 0
Views: 1022
Reputation: 12303
Always use the first parameter as error in callback.
If the request has no error and the status code is 200
. Your callback function code works, What if there is an error or status code is not 200. You have to handle all the cases.
function makeRequest(error, response, body) {
if (!error && response.statusCode == 200) {
callback(null,JSON.parse(body));
}
else{
callback(error);
}
}
Upvotes: 1