URI encode query parameter in request - node.js

I want to replicate the below curl request in node using request module.
curl -X POST \
'https://control.msg91.com/api/sendotp.php?authkey=fdfdfdfdfdfd&mobile=%203456786444&message=Your%20OTPis%20456897&otp=456897' \
-H 'cache-control: no-cache'
How ever when I tried the below code where I have used qs object to send the query parameters seems the + in mobile number is not uri encoded as above. How can I achieve this. Is qs is not the right parameter ? I have also tried using form .
My node code
var request = require('request');
request.post(
{
url:'https://control.msg91.com/api/sendotp.php',
headers: {
'content-type': 'application/json'
},
qs : {
authkey:'fdfdfdfdfdfd',
message:'Your OTP is 456789',
mobile :'+3456786444',
otp: '456789'
}}, function(err,httpResponse,body){
console.log(err);
});

Related

Convert multipart/form-data cURL to Fetch node js

With the following cURL request I am able to successfully interact with a pulsar api to update the configurations of a function.
Working cURL Request
curl --request PUT -H "Content-Type: multipart/form-data" -F functionConfig='{"parallelism":2};type=application/json' http://pulsar-test:8080/admin/v3/functions/test/ingest/test-entity-FeedTransformer
But I'm having trouble converting to an equivalent fetch request in Node.
Note: I'm using formdata-node to import FormData.
import { FormData } from 'formdata-node'
Non Working Fetch (Bad Request)
const body = new FormData()
body.append('functionConfig', '{"parallelism":2};type=application/json')
return fetch(
'http://pulsar-test:8080/admin/v3/functions/test/ingest/test-entity-FeedTransformer',
{
body,
headers: {
Authorization: 'Bearer abcd'
},
method: 'PUT'
}
)
Apparently the form data is not being set in a way the api server can recognize.
{"reason":"Function config is not provided"}
What am I missing here?
the problem is most likely that multipart request is not recognized/not well formed, or something like that, so try using another library, here's an example with Form-Data:
import { FormData } from 'form-data';
const body = new FormData();
body.append('functionConfig', '{"parallelism":2};type=application/json')
return fetch(
'http://pulsar-test:8080/admin/v3/functions/test/ingest/test-entity-FeedTransformer', {
body,
headers: {
Authorization: 'Bearer abcd'
},
method: 'PUT'
}
)
alternatively, you could run your curl command with child-process
see: How to use curl with exec nodejs

Nodejs post Json data with headers

How to post Json data via node js either with form-data or via request ?
Using form-data. It does not allow to send custom headers and if replaced bodyParams.getHeaders() with custom headers it does not send request data
https://www.npmjs.com/package/form-data
const smsResponse = await request.post(url, bodyParams, {headers:bodyParams.getHeaders()})
Using Request it does not allow to send parameters
require('request');
const subscription = await request.post(url, body, {headers:{'Accept':'text/html'}})
Postman curl request It works via postman. tried to use postman nodejs request code but it fails
curl --location --request POST 'https://personalsite.com//test.php' \
--header 'accept: text/html' \
--header 'SECRET-TOKEN-MESSAGE: dataforport' \
--header 'Content-Type: application/json' \
--header 'Cookie: PHPSESSID=1d2shuebo7lal8sn2itgppvfk4' \
--data-raw '{
"mobileno": "888888888",
"messagetext": "Test message"
}'
Tried but it did not worked
Node.js: How to send headers with form data using request module?
Use new Headers() to build your header.
https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
var myHeaders = new Headers();
myHeaders.append('Accept', 'text/html');
var myInit = { method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default',
body: JSON.stringify({coffee: 'yes...'})
};
var myRequest = new Request('https://personalsite.com//test.php',myInit);
fetch(myRequest).then(function(response) {
console.log(response)
});

Nodejs, http post json

Here is an example post that I want to do in my Nodejs server to get ClientID and secret.
Request example:
curl --request POST \
--url https://api.opskins.com/IOAuth/CreateClient/v1/ \
--header 'authorization: Basic {{AUTH_HASH}}' \
--data name=TestApp2 \
--data redirect_uri=http://localhost:1234
Response returns JSON structured like this:
{
"status": 1,
"time": 1535408581,
"response": {
"secret": "$nGwYVda##PErKAUpG#kHQ&YA1L)A*X1",
"client": {
"client_id": "ff371b045307",
"name": "TestApp2",
"redirect_uri": "http://localhost:1234",
"time_created": 1535407757,
"has_secret": true
}
}
I am trying with request :
const request = require('request');
var headers = {
'authorization': 'Basic ***my-api-key****'
};
var dataString = 'name=TestApp2&redirect_uri=http://localhost:5000';
var options = {
url: 'https://api.opskins.com/IOAuth/CreateClient/v1/',
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(body);
}
request(options, callback);
but getting error output like this :
{"status":401,"time":1540115259,"message":"API Key Required"}
I have been trying different codes and middlewares but couldn't make it. Also my test works perfect on Postman. I need help to post that and get my client_id and secret.
I found a way. It was really tricky for me. I needed to use my API Key and also client id.
Bellow codes worked. Thank you very much vitomadio !
I used reqclient from npm.
here is my code
var client = new RequestClient({
baseUrl:"https://api.opskins.com/IOAuth/CreateClient/",
debugRequest:true, debugResponse:true,
auth: {
user:"***My_apikey****",
}
});
var resp = client.post("v1/", {"name": "testApp2", "redirect_uri":"http://localhost:5000/"},{headers: {"authorization":"Basic **my_clientID"}}).then(response => {
// console.log(response);
});
also I am really curies and would like to know how can I do that with request.

How to get the equivalent nodejs Requst to CURL command?

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!

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);
});

Resources