I am trying to transform this curl command
curl '<url>' -X POST \
--data-urlencode 'To=<phone>' \
--data-urlencode 'From=<phone>' \
--data-urlencode 'Body=<message>' \
-u '<user>:<pass>'
into this Node.js code
var request = require('request');
var options = {
url: 'url',
method: 'POST',
auth: {
'user': 'user',
'pass': 'pass'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
I don't get how I can add the --data-urlencode option in the Node.js version of this code.
From curl documentation :
--data-urlencode
(HTTP) This posts data, similar to the other -d, --data options with
the exception that this performs URL-encoding.
So you would use form option to send form URL encoded like this :
var options = {
url: 'url',
method: 'POST',
auth: {
'user': 'user',
'pass': 'pass'
},
form: {
To: 'phone',
From: 'phone',
Body: 'message'
},
headers: {
'Accept': '*/*'
}
};
Note that you can use request-debug to show the actual request where you could check that body is :
To=phone&From=phone&Body=message
And to show the actual data sent by curl use as stated here, use --trace-ascii /dev/stdout :
curl '<url>' -X POST --data-urlencode "Body=<message>" -u <user>:<pass> --trace-ascii /dev/stdout
Related
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
I have tried every way I can think of to format this cURL request into something I can do server side on node and I keep getting back an invalid credentials response. I know the creds are valid so I must come to the conclusion that the code is making the wrong type of request.
cURL request:
curl --request GET \
--url https://api.timekit.io/v2/bookings\
--header 'Content-Type: application/json' \
--user : api_key_dfagafrgaegrfareVhROys9V1bUJ1z7
my format:
var options = {
url: 'https://api.timekit.io/v2/bookings',
headers:{
"Content-Type": "application/json",
'user': APP_KEY
},
method:'GET'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
I think you mean --user user:password in your curl command.
When you pass --user to curl, it sends it to the server as an basic authorization header (with the user:password encoded using base64). You can try this by running it against httpbin.org:
curl --request GET --url http://httpbin.org/headers --header 'Content-Type: application/json' --user foo:bar
{
"headers": {
"Accept": "*/*",
"Authorization": "Basic Zm9vOmJhcg==",
"Connection": "close",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.61.1"
}
}
As you can see, they received the header "Authorization": "Basic Zm9vOmJhcg==" where Zm9vOmJhcg== is the base64 encode of foo:bar
I have following CURL command
curl -u YOUR_API_KEY:x \
-H 'Content-Type: application/json' \
-X POST \
-d '{"first_name":"Tony", "kind":"person", "contact_name":"Stark"}' \
'https://ACCOUNT_NAME.quadernoapp.com/api/contacts.json'
I want do this request in NodeJS using the request module.
This is the code I have written.
var options = {
uri: 'https://ACCOUNT_NAME.quadernoapp.com/api/contacts.json',
json: true,
auth: {
user: 'YOUR_API_KEY'
}
data: {"first_name" : "Tonsdfasdy", "kind":"peasdfarson", "contact_name":"Staasdfadfadrk"}
}
request.post(options, function cb(){})
But it is not authenticatd properly. What is the error here?
You're authenticating using HTTP Basic authentication in your cURL command, where username and password are provided with the -u option and separated by :, so you need to provide your code with the password, like so :
var options = {
uri: 'https://ACCOUNT_NAME.quadernoapp.com/api/contacts.json',
json: true,
auth: {
user: 'YOUR_API_KEY',
password: 'x'
},
body: {
first_name : "Tonsdfasdy", kind:"peasdfarson", contact_name:"Staasdfadfadrk"
}
}
request.post(options, function cb(){})
And please try to pass your JSON object in an attribute named body rather than data (it will be transformed to a JSON string thanks to the json: trueoption).
You may also want to check this one : how to do Auth in node.js client
Hope this helps!
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);
});
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'}),