Nodejs, http post json - node.js

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.

Related

getting 404, firebase + node.js, using "projects.locations.instances.create"

I'm trying to make an instance of a database with node.js in firebase realtime database.
My node.js route looks like this:
const axios = require('axios');
var {google} = require("googleapis");
var serviceAccount = require("paht/to/json");
router.post('/createnewdatabase', function (req, res) {
//scopes used for the create
var scopes = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
let apiKey = req.body.apiKey;
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
};
axios({
method: 'post',
url: 'https://firebasedatabase.googleapis.com/v1beta/projects/{project-id}/locations/europe-west1',
data: {
key: apiKey,
databaseId: 'segesggseg-656-sdgsdgs',
},
config
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
res.send('POST request to the homepage')
}
});
})
I'm getting a 404 when trying to call the route. I'm guessing it's something with the tokens. The documentation is here: https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create
I can't figure it out :-)
Please consider that according to the official documetation link:
"name field - Currently the only supported location is 'us-central1'."
I was able to create an instance using the api only with empty data parameter.
'https://firebasedatabase.googleapis.com/v1beta/projects/111111111111/locations/us-central1/instances?databaseId=myinstanceiddd&validateOnly=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{}' \
--compressed
200
{
"name": "projects/111111111111/locations/us-central1/instances/myinstanceiddd",
"project": "projects/111111111111",
"databaseUrl": "https://myinstanceiddd.firebaseio.com",
"type": "USER_DATABASE",
"state": "ACTIVE"
}
After answer above did not work for me... I was forced to read docs (https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create) word by word...
Second paragraph says that ur project needs to be on the Blaze plan in order to be able to create instance... After this doing this, it now works for me.

Unable to exchange code for access token in node.js. Mailchimp API

I am trying to use OAuth2 with the Mailchimp API, and I am following their documentation to the letter, but I am unable to complete step 4. At this step, I exchange the code I received from the authorization screen for the token. Per the documentation, this can be done in curl like so:
curl --request POST \
--url 'https://login.mailchimp.com/oauth2/token' \
--data "grant_type=authorization_code&client_id={client_id}&client_secret={client_secret}&redirect_uri={encoded_url}&code={code}" \
--include
I attempted to convert this to work on node.js by writing this:
var dataString = 'grant_type=authorization_code&client_id=' + clientid + '&client_secret=' + clientsecret + '&redirect_uri=' + encodedurl + '&code=' + url.parse(req.url, true).query.code;
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
data: dataString
};
function callback(error, response, body) {
if (!error) {
console.dir(JSON.stringify(body));
}
else{
console.dir(error);
}
}
request(options, callback);
When I make the request.debug = true, I see that I am getting a 400 error. The message sent to the console is a bunch of garbled characters though. When I use these same variables and endpoints to authenticate through Postman though, it works fine, so the issue is not with the variables or the API itself.
I am not entirely sure what I am doing wrong here. The request I am making seems almost identical what is written in curl in the documentation. So where am I going wrong?
Hmm, did you forget to define request?
var request = require("request");
Finally figured it out. The issue was in the header of the request. There are two ways to fix this. The first is to use "form" instead of "data". Request includes a "content-type: x-www-form-urlencoded" header automatically if the option "form" is used.
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
form: dataString
};
I am not sure what header is used when the "data" option is used, or if no content-type is declared at all. Either way, if you choose to continue to use the "data" option, you can manually declare a content-type header. This is the second possible solution.
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers:
{ 'Content-Type': 'application/x-www-form-urlencoded' },
body: dataString
};
After alot of tries, I figured out. You can use code only once. So make sure you use code you get from redirect URI only once.
With new code use this code
const dataString = "grant_type=authorization_code&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&code="+req.body.code
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
},
form: dataString
};
function callback(error, response, body) {
if (!error) {
let str = JSON.stringify(body)
res.setHeader("Content-Type", "application/json; charset=utf-8")
res.send(body)
}
else{
console.dir(error);
res.send(error)
}
}
request(options, callback);

How to write curl 'PUT' request in node with 'request' module

I have this curl request working.
curl -v "https://developer.api.autodesk.com/oss/v2/buckets/:bucketName/objects/"
-X "PUT" -H "Authorization: Bearer tokenGoesHere"
-H "Content-Type: application/octet-stream" -T "forupload.rvt"
How can I write this in node with npm request module.
I tried the following with 'request' and 'fs'.
I get back "Token is not provided in the request".
function uploadFile(bucketData){
var uri = 'https://developer.api.autodesk.com/oss/v2/buckets/' + bucketData['bucketKey'] + '/objects/'
var authorizationHeader = ' Bearer ' + bucketData['token'] // this works in other post/get requests
var contentTypeHeader = 'application/octet-stream'
var streamTarget = 'C:\\Users\\architech\\Desktop\\Forge Node\\Test.rvt';
console.log(uri)
console.log(authorizationHeader)
console.log(contentTypeHeader)
console.log(streamTarget)
// console output:
// https://developer.api.autodesk.com/oss/v2/buckets/bucketpqglrzt/objects/
// Bearer ....token....
// application/octet-stream
// C:\Users\architech\Desktop\Forge Node\Test.rvt
request.put(
{
url: uri,
// preambleCRLF: true,
// postambleCRLF: true,
multipart:
[
{
'Authorization': authorizationHeader,
'Content-Type': contentTypeHeader,
body: fs.createReadStream(streamTarget)
},
]
},
function(error, response, body){
if(!error){
console.log(body);
}else{
console.log(error);
}
})
}
After trying several approaches, while I couldn't reproduce your specific problem, the trouble I had was with the binary attachment loading properly. Because createReadStream() runs asynchronously, it doesn't really seem to work the way the request docs say it should when added to the multipart or formData keys. Not sure why this is?
I got it working first using http://requestb.in - comparing the curl request to the same request constructed with Node. Here is the final, working version:
var request = require('request')
fs = require('fs')
var options = {
uri: 'https://developer.api.autodesk.com/oss/v2/buckets/<yourBucket>/objects/<yourFile.ext>',
headers: {
'Content-Type': 'application/octet-stream',
'Authorization': 'Bearer <token>'
}
}
fs.createReadStream(__dirname + '/<fileName.ext>').pipe(request.put(options, function(err, response, body) {
console.log(body)
/*
{
"bucketKey" : "< yourBucket>",
"objectId" : "urn:adsk.objects:os.object:brandontestbucket2/skyscpr1.3ds",
"objectKey" : "<fileName.ext>",
"sha1" : "...redacted...",
"size" : 43791,
"contentType" : "application/octet-stream",
"location" : "https://developer.api.autodesk.com/oss/v2/buckets/< yourBucket>/objects/<fileName.ext>"
}
*/
}))

Slack Webhook - Getting Invalid_Payload

I am attempting to set up a webhook to Slack, but am getting an Error message of "Invalid_Payload"
I've looked through Stack, Slack, and Github... but cant' find the answer I seek.
"CustomLink" in there for privacy, actual link is begin used.
CODE:
var request = require('request')
var webhook = "https://hooks.slack.com/services/CUSTOMLINK"
var payload={"text":"This is via an integration from Me - It is a test"}
request.post({url: webhook, payload: payload}, function(err, res){
if(err){console.log(err)}
if(res){console.log(res.body)}
})
ERROR:
invalid_payload
var payload= {"text":"This is via an integration from Me - It is a test"}
payload = JSON.stringify(payload)
I had forgot to stringify the JSON I was creating. Stupid Me.
This worked for me
var payload = {"text":"Message to be sent"}
payload = JSON.stringify(payload);
request.post({url: url, body: payload},function(err,data){
console.log(data.body);
})
My guess is that you are missing the Content-type: application/json header. Then it doesn't recognize the json you are sending as json correctly.
You could try:
var request = require('request')
var webhook = "https://hooks.slack.com/services/CUSTOMLINK"
var payload={"text":"This is via an integration from Me - It is a test"}
var headers = {"Content-type": "application/json"}
request.post({url: webhook, payload: payload, headers: headers}, function(err, res){
if(err){console.log(err)}
if(res){console.log(res.body)}
})
Check the "Send it directly in JSON" here for reference
var request = require('request');
var apiurl = webhookurl;
var payload= {
username:'myusername',
text:'test'
}
payload = JSON.stringify(payload);
request.post(
{
url:apiurl,
form:payload
}, function (err, result, body) {
if(err) {
return err;
} else {
console.log(body);
}
});
Try with postman for sending the post request by using your webhook as URL and under body use raw and use { "text":"hello" } and follow the following image:
or use this curl command:
curl --location --request POST 'https://hooks.slack.com/services/o1GLCDvsanqNDqMHCBQAd7F3' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": "hello"
}'

I have curl documentation for how to use a site's APIs but would like to use Node JS for the API

I'm trying to make an API for saleforeceIQ and their documentation doesn't include Node JS which is what I'm most familiar with. I'm wondering if I could make an API with Node JS from looking at their documentation. Here is their curl documentation get get an account:
DEFINITION
GET https://api.salesforceiq.com/v2/accounts/{accountId}
REQUEST
curl 'https://api.salesforceiq.com/v2/accounts/abcdef1234567890abcdef0b'
-X GET
-u [API Key]:[API Secret]
-H 'Accept: application/json'
RESPONSE
HTTP/1.1 200 OK
{
"id" : "abcdef1234567890abcdef0b",
"modifiedDate" : 1389124003573,
"name" : "Account"
}
Here is what I have come up with so far for converting this to Node JS:
var key = "[KEY]"
var secret = "[SECRET]"
var request = require('request');
var headers = {
'Accept': 'application/json'
};
var options = {
url: 'https://api.salesforceiq.com/v2/accounts/',
headers: headers
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("body " +body);
}
else{
console.log(error)
}
}
request(options, callback)
My problem is I don't know how to incorporate the key and secret into Node JS
The -u option of curl specify the username and password. So translated for request.js became:
var options = {
// your options
'auth': {
'user': '[KEY]',
'pass': '[SECRET]',
'sendImmediately': true
}
}
You can find more info here: https://github.com/request/request#http-authentication

Resources