what is the nodejs code for this curl command - node.js

I can successfully execute this curl command from a Unix shell script and I can see output in C:\Users\OutputFile.csv. What is the equivalent code in NodeJS
curl -k -v --user 'helloworld:hello_password'
--header 'Accept: application/vnd.myDMS-dms-api+json; version=1'
-X POST 'https://DMS.com:3001/download/csv'
--data header=true -o C:\Users\OutputFile.csv
I tried using the Online curl to nodeJS converter and it has generated the following NodeJs code:-
var request = require('request');
var headers = {
'Accept': 'application/vnd.myDMS-dms-api+json; version=1'
};
var options = {
url: 'https://DMS.com:3001/download/csv',
method: 'POST',
headers: headers,
auth: {
'user': 'helloworld',
'pass': 'hello_password'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
However, when I run this NodeJS code it does not show any output. Also how can I get this output to C:\Users\OutputFile.csv

Maybe the response isn't return before the script is terminated. You would want the request to be asynchronous:
You can use request-promise
Here's an example
var rp = require('request-promise');
function someFunction() {
let options = {
url: `someURL`,
method: 'POST',
body: {
some: 'payload'
},
json: true
};
return rp(options);
}
This will await the response.

A simple version of your API parameters using request-promise:
var rp = require('request-promise');
function downloadFile() {
var options = {
uri: 'https://DMS.com:3001/download/csv',
method: 'POST',
auth: {
user: 'helloworld',
pass: 'hello_password',
sendImmediately: true
},
headers: {
Accept:'application/vnd.myDMS-dms-api+json; version=1'
},
form: {
'header': 'true'
}
};
rp(options)
.then(function (body) {
console.log('Downloaded body was %d long', repos.length);
})
.catch(function (err) {
console.log(err)
});
}
downloadFile()

Related

cURL to NodeJS Request with multipart/form-data

i need make request like this cURL:
curl -u [staff_email]:[api_key] -F "case[attachments][0]=#/path/to/file1.ext" -F "case[content]=I need help" -F "case[subject]=I need help" -F "case[user_email]=user#domain.ru" -F "case[user_full_name]=FullName" -F "case[language_id]=1" -X POST https://[domain].omnidesk.ru/api/cases.json
i try a lot of times! Pls, help!
last version of code (res: string[]/csv):
const auth = 'Basic ' + Buffer
.from('user:password')
.toString('base64');
const query = {
'case[subject]': "subject",
'case[content]': 'text',
'case[user_email]': 'someemail#gmail.com',
'case[user_full_name]': 'some_name',
'case[group_id]': 18278,
'case[language_id]': 1,
'case[attachments][0]': Buffer.from(res.join("\r\n"), 'utf8'),
};
const cb = (e, r, b) => {
console.log(e, r, b);
};
const options = {
method: 'post',
url: 'https://domain.omnidesk.ru/api/cases.json',
headers: {
"Authorization": auth,
"Content-Type": "multipart/form-data"
},
form: query,
};
request(options, cb);
worked code below:
const query = {
'case[subject]': "subject",
'case[content]': 'content',
'case[user_email]': 'tt#tt.tt',
'case[user_full_name]': 'some name',
'case[language_id]': 1
};
const cb = (e, r, b) => {
console.log(e, b);
};
const options = {
method: 'POST',
url: 'https://domain.omnidesk.ru/api/cases.json',
auth: {
user: 'login',
pass: 'password'
},
qs: query
};
const req = request(options, cb);
const form = req.form();
form.append('case[attachments][0]', res.join("\r\n"), { filename: 'some_file.csv' });

nodejs request post large json fail

I am trying to post large json to a http server(a grafana server actually):
here is my code:
const http = require('http')
const request = require('request')
const fs = require('fs')
const opts = {
hostname: 'myip',
port: 3000,
path: '/api/dashboards/uid/KPEiIQVWk',
method: 'GET',
timeout: 5000,
headers : {
'Authorization' : 'Bearer ********************************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
}
const req = http.request(opts, res => {
console.log(`Fetch: statusCode: ${res.statusCode}`)
var origin = ''
res.on('data', d => {
origin += d
})
res.on('end', function(){
dash = JSON.parse(origin)
dash.dashboard.panels.forEach(p => {
if(p.id == 26){
fs.readFile(__dirname + '/grafana/pm/branch-graph.html','utf-8', function(err, newPanel){
if(err){
console.log(err)
}
p.content = newPanel
const fresh = JSON.stringify(dash)
const updateOptions = {
uri: 'http://myip:3000/api/dashboards/db',
method: 'post',
headers : {
'Authorization' : 'Bearer *************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Content-length' : fresh.length
},
json: fresh
}
fs.writeFile('tmp.json', fresh, function(err){
if(err){
console.error(err)
}
})
request(updateOptions, function(error, response, body){
console.log(`update: statusCode=${response.statusCode}`)
console.log(`update: ${body}`)
})
})
}
})
})
})
req.on('error', error => {
console.error(error)
})
req.on('timeout', () => {
req.abort()
})
req.end()
as you can see, I first fetch a grafana dashboard's source, then make some udpate, then post it back to grafana server. but always get 400 error. The strange thing is that if I dump the json to a file and use curl to post, it will work.
curl -vH "Authorization: Bearer $TOKEN" -H "Expect:" -d #tmp.json -H "Content-Type:application/json" http://myip:3000/api/dashboards/db
the whole json is about 40000+ bytes. any hint on this? I am not very famillar with nodejs. I am just trying to write some CI scripts.
First, I don't think it's necessary to use both the http and request modules. http is a module built into nodejs, and request is an npm package.
I recommend you use the npm request package because it's easier. You can read its documentation here: https://www.npmjs.com/package/request#http-authentication
Second, the options you're passing to the request module is not formatted correctly, I think this is why it is not working. With your current code, I would console.log('POST error', error); to print out the error. The correct options for the request module is proposed below.
const options = {
url: 'https://myip:3000/api/dashboards/db',
body: fresh, // the json from the fs.read callback
auth: {
'bearer': 'bearerToken'
},
json: true // from docs: If json is true, then body must be a JSON-serializable object.
}
request.post(
options,
(err, httpResponse, body) => {
console.log(err, body);
});

POST using multipart/form-data in NodeJS

I need to essentially POST a local image to Cisco Webex room from my NodeJS service. For local files, you need to do a multipart/form-data request instead of JSON as mentioned in the documentation.
The CURL looks like
curl --request POST \
--header "Authorization: Bearer ACCESS_TOKEN" \
--form "files=#/home/desktop/example.png;type=image/png" \
--form "roomId=Y2lzY2....." \
--form "text=example attached" \
https://api.ciscospark.com/v1/messages
But I am not sure how to convert it to nodeJS request format. I tried to use CURL to Node request converter here but doesn't seem like it is handling the multipart/form-data type. Please suggest.
EDIT: after doing some research, I came up with the below code
var request = require('request');
var fs = require('fs');
var params = { roomId: ROOMID,
text: "hello....",
files: {
value: fs.createReadStream(PATH_WO_FILENAME),
options: {
filename: 'image.jpg',
contentType: 'jpg'
}
}
};
var headersWebex = {
'Authorization': 'Bearer MY_BOT_ACCESS_TOKEN',
'Content-Type': 'multipart/form-data' }
request.post({
headers: headersWebex,
url: 'https://api.ciscospark.com/v1/messages',
method: 'POST',
body: params
}, function(error, response, body){
console.log(body);
});
But it is throwing error
undefined
_http_outgoing.js:642
throw new TypeError('First argument must be a string or Buffer');
Ok so here is how I made it work. I essentially needed to look deeper into the docs that #Evan mentioned
var request = require('request');
var fs = require('fs');
var roomID = 'MY_ROOM_ID'
var params = {
roomId: roomID,
text: "hello....",
files: {
value: fs.createReadStream('./image.jpg'),
options: {
filename: 'image.jpg',
contentType: 'image/jpg'
}
}
};
var headersWebex = {
'Authorization': 'Bearer MY_BOT_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
request.post({
headers: headersWebex,
url: 'https://api.ciscospark.com/v1/messages',
method: 'POST',
formData: params
}, function(error, response, body){
if (error)
console.log(error)
console.log(body);
});

Openfigi REST API in node js

I am trying to run the following Nodejs program to retrieve data from OpenFigi.
But, not getting any information whereas curl request returns the data.
var request = require('request');
var options = {
url: 'https://api.openfigi.com/v1/mapping',
data: '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]',
headers: {
'Content-Type': 'text/json'
} };
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info);
}
}
request(options, callback);
The following curl request returns the data
curl -v POST 'https://api.openfigi.com/v1/mapping' \
--header 'Content-Type: text/json' \
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'
Result:
[
{
"data": [
{
"figi": "BBG000BLNNH6",
"securityType": "Common Stock",
"marketSector": "Equity",
"ticker": "IBM",
"name": "INTL BUSINESS MACHINES CORP",
"uniqueID": "EQ0010080100001000",
}
]
}
]
Could you please help to fix the nodejs program.
Thanks,
Saravana
You didn't give method type
var options = {
url: 'https://api.openfigi.com/v1/mapping',
method:'POST',
data: '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]',
headers: {
'Content-Type': 'text/json'
} };

cURL call to API in NodeJS Request

it's me again with another lame question. I have the following call to a Rattic password database API which works properly:
curl -s -H 'Authorization: ApiKey myUser:verySecretAPIKey' -H 'Accept: text/json' https://example.com/passdb/api/v1/cred/\?format\=json
I tried to replicate this call in NodeJS, however the following returns blank:
var request = require('request');
url='https://example.com/passdb/api/v1/cred/?format=json';
request({
url: url,
method: 'POST',
headers: [
{ 'Authorization': 'ApiKey myUser:verySecretAPIKey' }
],
},
function (error, response, body) {
if (error) throw error;
console.log(body);
}
);
Any help is appreciated.
As pointed out in the comments already, use GET, not POST;
headers should be an object, not an array;
You're not adding the Accept header.
All combined, try this:
request({
url : url,
method : 'GET',
headers : {
Authorization : 'ApiKey myUser:verySecretAPIKey',
Accept : 'text/json'
}, function (error, response, body) {
if (error) throw error;
console.log(body);
}
});
One thing you can do is import a curl request into Postman and then export it into different forms. for example, nodejs:
var http = require("https");
var options = {
"method": "GET",
"hostname": "example.com",
"port": null,
"path": "/passdb/api/v1/cred/%5C?format%5C=json",
"headers": {
"authorization": "ApiKey myUser:verySecretAPIKey",
"accept": "text/json",
"cache-control": "no-cache",
"postman-token": "c3c32eb5-ac9e-a847-aa23-91b2cbe771c9"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
Headers should be an object.
var request = require('request');
url='https://example.com/passdb/api/v1/cred/?format=json';
request({
url: url,
method: 'POST',
headers: {
'Authorization': 'ApiKey myUser:verySecretAPIKey'
}
}, function (error, response, body) {
if (error) throw error;
console.log(body);
});

Resources