curl -> node, how to? - node.js

I need to set the password for Neo4j and can do it from the command line like this:
curl -H "Content-Type: application/json" \
-H "Authorization: Basic `echo -n 'neo4j:neo4j' | base64`" \
-X POST -d '{"password":"nopass"}' \
http://localhost:7474/user/neo4j/password
but I'm now trying to do it in node.js like this:
var f = require('node-fetch');
var url = 'http://neo4j:n0p4ss#localhost:7474/user/neo4j/password';
var auth = new Buffer('neo4j:neo4j').toString('base64');
f(url, {
method: 'POST',
body: {'password': 'nopass'},
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + auth
}
})
.then(res => res.text())
.then(txt => { console.log(txt); });
however, what I get back is:
{
"errors" : [ {
"code" : "Neo.ClientError.Request.InvalidFormat",
"message" : "Required parameter 'password' is missing."
} ]
}
which to me means the body: {...} isn't getting sent correctly. can anyone see what's wrong with my code?

ah. figured it out. it needs:
body: JSON.stringify({'password': 'nopass'}),

Related

-F file=#foo.png equivalent in node fetch

I'm trying to perform an API call to Squarespace using node-fetch.
const FormData = new FormData();
formData.append(
"file",
"testimage.jpg",
fs.createReadStream("testimg.jpg")
);
const send_img = await fetch(
"https://api.squarespace.com/1.0/commerce/products/" + img_id + "/images",
{
method: "POST",
headers: {
Authorization: "Bearer " + process.env.SQUARESPACE_API_KEY,
"User-Agent": "foobar",
"Content-Type": "multipart/form-data",
},
body: formData,
}
);
After performing this call I was getting the error
{
type: 'INVALID_REQUEST_ERROR',
subtype: null,
message: "Expected exactly one file part named 'file', but found none.",
details: null,
contextId: 'IEBROFREUTEWDREAYEAF'
}
The following cURL call successfully uploads the image
curl "https://api.squarespace.com/1.0/commerce/products/63ab0ff8796311649603ee49/images" \
-i \;
-H "Authorization: Bearer <myAPIKey>" \
-H "User-Agent: foobar" \
-H "Content-Type: multipart/form-data" \
-X POST \
-F file=#testimg.png
What if -F and what is the equivalent of it in a fetch call?
Squarespace API reference:
https://developers.squarespace.com/commerce-apis/upload-product-image

Imgix Purge Post Request fails for unknown reason

I wanna purge an image from the imgix cache, they have a API for that (https://docs.imgix.com/setup/purging-images)
I use axios to make the request from my nodejs backend:
const imgixKey = functions.config().imgix.key;
const headers = {
Authorization: `Bearer ${imgixKey}`,
'Content-Type': 'application/json',
};
const data = JSON.stringify({
type: 'purges',
attributes: {
url: href,
source_id: 'SOsourceId',
},
});
try {
await axios.post('https://api.imgix.com/api/v1/purge', data, { headers });
functions.logger.log('Purged Image successfully' + href);
} catch (e) {
functions.logger.error('Error removing image from cache ' + href + ' -> ' + e);
}
Error removing image from cache {stackoverflowimgpath.png} -> Error: Request failed with status code 400
The problem is other than the status code 400 there is nothing else specified, I checked the image paths and tried different Content-Type headers like in their example but that also did not work.
Since I cannot get any more information out of the response I ask for help here since I do not know how to continue.
Checking imgix documentation, the body of your request should have a data property:
curl -X POST 'https://api.imgix.com/api/v1/purge' \
--header 'Authorization: Bearer <api-key>' \
--header 'Content-Type: application/vnd.api+json' \
--data-raw '{ "data": { "attributes": { "url": "<url-to-purge>" }, "type": "purges" } }'
So, just modify your message to (adding the data property to your json object):
const data = JSON.stringify({
data: {
type: 'purges',
attributes: {
url: href,
source_id: 'SOsourceId',
},
}
});

sending multiform data with DUPLICATE KEYS in nodejs

I need to send a POST request with NodeJS to an API that requires the same multiform key be used more than once.
This is a CURL example of the required action:
curl -H "Authorization: Bearer MY_ACCESS_TOKEN" -i -X POST -F "whitespace=1" \
-F "terms[]=lait" -F "definitions[]=milk" -F "terms[]=petits pois" \
-F "definitions[]=peas" -F "title=My first set via the API" \
-F "lang_terms=fr" -F "lang_definitions=en" \
https://api.quizlet.com/2.0/sets
As you can see, the keys "terms[]" and "definitions[]" are used more than once in the same request.
I've tried using the nodejs request/http/multi-form libraries with no success, as most of them require a JavaScript object to define the form data, which of course cannot accept duplicate keys.
Other than resorting to an exec() command to cURL, is there any nodejs library that will enable me to send a request with duplicate multiform keys?
I'm really banging my head against a wall with this one..
Try this its an example with request library
let options = { method: 'POST',
url:url,
headers:
{
'cache-control': 'no-cache',
authorization: 'Bearer '+accessToken ,
'content-type': 'application/json'
},
body:
{ //your array here
terms:['terms'] ,
definitions:['milk']
},
json: true
};
request(options, function (error, response, body) {
if(error){
console.log("Error ",error);
}
console.log("Response",body);
})
With unirest:
var unirest = require('unirest');
var req = unirest('POST', 'YOUR URL')
.headers({
'Content-Type': 'multipart/form-data; boundary=--------------------------846713359653092950719061',
'Authorization': 'YOUR AUTH'
})
.field('AAA', 'VAL1')
.field('AAA', 'VAL2')
.field('AAA', 'VAL3')
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});

Nodejs twitter api does not return expected token

I am using nodejs to get bearer token i my code looks like
var fs = require("fs");
var https = require("https");
var querystring = require("querystring");
var bearer = "cunsomer_key:cunsomer_secret"
var base64ed = new Buffer(bearer).toString("base64");
var options = {
port: 443,
hostname: "api.twitter.com",
path: "/oauth2/token",
method: "post",
headers: {
Authorization: "Basic " + base64ed,
"Content-Type": "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"User-Agent": "socialginie"
},
key: fs.readFileSync("./testssl.key"),
cert: fs.readFileSync("./testcert.cert"),
}
var req = https.request(options, res => {
res.on("data", d => {
console.log(d.toString());
})
})
req.on("error", e => {
console.log(e);
});
req.write(querystring.stringify({
"grant_type": 'client_credentials'
}))
req.end();
The expected return from the api is my bearer token and it does so in postman app but here i get the error {"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]}
Does anyone have any idea why api server cannot read the grant type
Your problem is just a typo. On this line:
"Content-Type": "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
you are specifying "Content-Type" as part of the header value.
When I use this curl command, sending your invalid Content-Type, I see the same error you do:
$ curl --data "grant_type=client_credentials" -H "Authorization: Basic <credentials-omitted>" -H "Content-Type:" -H "Content-Type: Content-Type: application/x-www-form-urlencoded;charset=UTF-8" https://api.twitter.com/oauth2/token
{"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]}
If I correct the header, I get a token:
$ curl --data "grant_type=client_credentials" -H "Authorization: Basic <credentials-omitted>" -H "Content-Type:" -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" https://api.twitter.com/oauth2/token
{"token_type":"bearer","access_token":"<token-omitted>"}

How can I make this request in nodejs(status 415)?

I was using bash to do a task. And had some mess while trying to parse the response. Now I am using nodejs for the task. But I get following error:
"httpStatus" : 415,
"messages" : [ {
"errorCode" : "305",
"message" : "Unsupported media type 'application/x-www-form-urlencoded'"
} ]
This used to be my curl request in bash file:
curl --include\
--request POST \
--user "$USERNAME:$PASSWORD" \
--header "Content-Type: application/vnd.profitbricks.resource+json" \
--data-binary "{
\"properties\": {
\"name\": \"$servername\",
\"ram\": $RAM,
\"cores\": $CORES
}
}" \
https://api.profitbricks.com/rest/datacenters/$ID/servers ;
This is my current request:
var request = require('request');
var reqoptions = {
method: 'POST',
uri: 'https://api.profitbricks.com/rest/datacenters/'+options.vdcID+'/servers',
form:{
"properties":{
"cores": options.cores,
"ram": options.ramsize,
"name": options.servername
}
},
headers: {
'Authorization': 'Basic ' + new Buffer(options.user+':'+options.password).toString('base64'),
'Content-Type': 'application/vnd.profitbricks.resource+json'
}
};
request(reqoptions, function(err, res, body){});
form option changing content-type to form-urlencoded
you shouldn't use form in request options
send a binary data like here nodejs/express and binary data in POST
so use body: myBuffer instead of form: {...}
The problem was serialization. I stringified the object. Now it works.
var request = require('request');
var body = {
"properties":{
"cores": options.cores,
"ram": options.ramsize,
"name": options.servername
}
}
var reqoptions = {
method: 'POST',
uri: 'https://api.profitbricks.com/rest/datacenters/'+options.vdcID+'/servers',
body: JSON.stringify(body),
headers: {
'Authorization': 'Basic ' + new Buffer(options.user+':'+options.password).toString('base64'),
'Content-Type': 'application/vnd.profitbricks.resource+json'
}
};
request(reqoptions, function(err, res, body){});
This did the trick.

Resources