Not able make post request to third party app - node.js

I've written this code in my nodeJs backend
const url = "localhost:8080/job/test/build";
const username = "admin";
const password = "116c197495ef372f129b85a8a2ca4aadc2";
const token = Buffer.from(`${username}:${password}`, "utf8").toString(
"base64"
);
const data = {
}
axios
.post(url, {
headers: {
Authorization: `Basic ${token}`,
},
})
.then((response) => res.send(response)).catch((e) => {console.log(e)});
I'm getting the following error
The same request with same credential is working in postman.

use http in url, like this"
const url = "http://localhost:8080/job/test/build";

Related

nodejs: make-fetch-happen and socks5 proxy (with auth) doesn't working

Without a proxy, the code works. In another Google account (cloud functions), the code works with and without a proxy. How is that possible?
Error when trying with proxy: "(node:3312) UnhandledPromiseRejectionWarning: TypeError: SocksProxyAgent is not a constructor".
const fetch = require('make-fetch-happen');
async function getSegments(appId, apiKey, proxy) {
const opts = {
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${apiKey}`
}
}
if (proxy) {
opts['proxy'] = proxy
}
const resp = await fetch(`https://onesignal.com/api/v1/apps/${appId}/segments`, opts)
const data = await resp.json()
return data.segments
}
var appId = 'abc123', apiKey = 'abc123', proxy = 'socks5://login:pass#1.2.3.4:1234';
console.log(getSegments(appId, apiKey, proxy));

Creating Wallet Address with coinbase API Using Axios Request

Hello I'm trying to use the coinase api using axios to make request. I have set up the neccessary api authentication using SHA256 HMAC. I have been able to make some GET Request and got response. I have been trying to make a POST Request but i have been getting 401 status code.
const name = "Test BTC Address";
const body = {
name: name
}
var encHash = {
baseUrl: 'https://api.coinbase.com',
method: 'POST',
path: '/v2/accounts/bbc2e3f7-a851-50ab-b4b3-a0f2a700846f/addresses',
body: body,
scopes: "wallet:addresses:create"
};
const sign = generateHashKey(encHash, key.APISECRET);
console.log(sign);
const config = {
headers: {
'CB-ACCESS-SIGN': sign.signature,
'CB-ACCESS-TIMESTAMP': sign.timestamp,
'CB-ACCESS-KEY': key.APIKEY,
'CB-VERSION': '2021-10-15'
}
}
const url = `${encHash.baseUrl}${encHash.path}`
console.log(url);
var options = await axios.post(url, body, config);
return res.send({data: options.data})
} catch (error) {
// console.error(error);
return res.send({error})
} ```

How to get Azure access token with Node js API using Axios

I have a backend in Nodejs using Axios for my API calls. I need to implement Azure Authentication to get a token so I followed the sample below:
https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-nodejs-webapp-msal?WT.mc_id=Portal-Microsoft_AAD_RegisteredApps
The sample uses express and has redirects to first get and authorization and then a token, I have been trying to find a sample with Axios however I couldn't find one.
This is what I have so far, the idea is using the result to get a token,any guidance is much appreciate it.
const msal = require('#azure/msal-node');
const REDIRECT_URI = "http://localhost:3000/";
const LOGIN = "https://login.microsoftonline.com/";
const config = {
auth: {
clientId: "12345678910",
authority: "https://login.microsoftonline.com/12345678910",
clientSecret: "Secret",
knownAuthorities: ["https://login.microsoftonline.com/12345678910"
]
}
};
const pca = new msal.ConfidentialClientApplication(config);
module.exports = {
async getAzureAdToken(){
try {
let instance = axios.create({baseURL: LOGIN});
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI
};
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) =>{
let url = response.substring(LOGIN.length);
instance.get(url).then((result) =>{
});
}).catch((error) => console.log(JSON.stringify(error)));
} catch (error) {
throw error
}
},
You could use client credentials flow to get access token with axios. Client credentials flow permits a web service (confidential client) to use its own credentials, instead of impersonating a user, to authenticate when calling another web service. In the client credentials flow, permissions are granted directly to the application itself by an administrator. We need to add application permissions in API Permission.
Test in Postman:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=<client_id>
&scope=https://graph.microsoft.com/.default
&client_secret=<client_secret>
&grant_type=client_credentials
Code using Nodejs:
// Replace these values from the values of you app
const APP_ID = '[APP_ID/CLIENT_ID]';
const APP_SECERET = '[CLIENT_SECRET]';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/[TENANT_ID]/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';
const axios = require('axios');
const qs = require('qs');
const postData = {
client_id: APP_ID,
scope: MS_GRAPH_SCOPE,
client_secret: APP_SECERET,
grant_type: 'client_credentials'
};
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded';
let token = '';
axios
.post(TOKEN_ENDPOINT, qs.stringify(postData))
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});

Can't Find Response Headers in an NodeJS - ExpressJS App

I have set up a simple api request using node/express.js to access the Feedly Dev Api: https://developer.feedly.com/. The Feedly Api comes with two response headers -- X-Ratelimit-Count and X-Ratelimit-Reset. The problem is that I can't figure out how to access.
Here is the relevant parts of my express.js file:
app.get('/feedly', async (request, response) => {
const apiUrl =
'https://cloud.feedly.com/v3/streams/contents?streamId=user/[USER_ID]/category/global.all'
const fetchResponse = await fetch(apiUrl, {
headers: {
Authorization: `Bearer ${process.env.FEEDLY_ACCESS_TOKEN}`
}
})
const json = await fetchResponse.json()
response.json(json)
response.end()
})
what do I have to do in order to see both X-Ratelimit-Count and X-Ratelimit-Reset response headers?
Thanks.
Fetch API: Headers
(async() => {
const fetchResponse = await fetch("https://httpbin.org/anything");
console.log(fetchResponse.headers.get('X-Ratelimit-Count'))
console.log(fetchResponse.headers.get('X-Ratelimit-Reset'))
fetchResponse.headers.forEach((v, k) => console.log(`${k}: ${v}`));
})();

How can I turn this POST method into valid Node.js code?

Using https://mws.amazonservices.com/scratchpad/index.html, I am able to make a valid request to the MWS endpoint, the details of which look like this:
POST /Products/2011-10-01?AWSAccessKeyId=myAWSAccessKeyId
&Action=GetMatchingProductForId
&SellerId=mySellerId
&SignatureVersion=2
&Timestamp=2018-08-14T01%3A00%3A39Z
&Version=2011-10-01
&Signature=6xwEi3Mk9Ko9v9DyF9g6zA4%2Buggi7sZWTlUmNDxHTbQ%3D
&SignatureMethod=HmacSHA256
&MarketplaceId=ATVPDKIKX0DER
&IdType=UPC
&IdList.Id.1=043171884536 HTTP/1.1
Host: mws.amazonservices.com
x-amazon-user-agent: AmazonJavascriptScratchpad/1.0 (Language=Javascript)
Content-Type: text/xml
How can I take this, and turn it into a valid URL that I can use to make a request from my app, i.e., using fetch or some other javascript implementation. I tried to take the info and make a URL like this:
https://mws.amazonservices.com/Products/2011-10-01?
AWSAccessKeyId=myAWSAccessKeyId
&Action=GetMatchingProductForId
&SellerId=mySellerId
&SignatureVersion=2
&Timestamp=2018-08-14T01%3A00%3A39Z
&Version=2011-10-01
&Signature=6xwEi3Mk9Ko9v9DyF9g6zA4%2Buggi7sZWTlUmNDxHTbQ%3D
&SignatureMethod=HmacSHA256
&MarketplaceId=ATVPDKIKX0DER
&IdType=UPC
&IdList.Id.1=043171884536
, to which I tried to send a POST request via postman, and I got this error:
<?xml version="1.0"?>
<ErrorResponse xmlns="https://mws.amazonservices.com/">
<Error>
<Type>Sender</Type>
<Code>InvalidParameterValue</Code>
<Message>Value 2
for parameter SignatureVersion is invalid.</Message>
</Error>
<RequestID>6ded1eed-eb92-4db6-9837-3453db0f8a77</RequestID>
</ErrorResponse>
How can I make a valid request to an MWS endpoint using javascript?
You could use npm module like superagent, axios or request.
const agent = require('superagent)
agent
.post('https://mws.amazonservices.com/Products/2011-10-01')
.query({
AWSAccessKeyId: myAWSAccessKeyId,
Action: GetMatchingProductForId,
SellerId: mySellerId,
SignatureVersion: 2,
Timestamp: 2018-08-14T01%3A00%3A39Z,
Version: 2011-10-01,
Signature: 6xwEi3Mk9Ko9v9DyF9g6zA4%2Buggi7sZWTlUmNDxHTbQ%3D,
SignatureMethod: HmacSHA256,
MarketplaceId: ATVPDKIKX0DER,
IdType: UPC,
IdList.Id.1: 043171884536
})
.then(res => {
console.log('here is the response');
console.log(res)
})
.catch(error => {
console.log('here is the error');
console.log(error);
})
I haven't written against AWS but are you sure that these parameters should be sent with the querystring. Usually with post, parameters are sent with the body?
The error you are recieving from Postman is telling you that you are reaching the server but something is wrong the with values that you are sending. For example: SignatureVersion should be 1 (or something).
I used node-fetch to make a valid request the MWS endpoint. You can look code as given below.
var param = {};
param['AWSAccessKeyId'] = 'xxxxxxxxxxxxx';
param['Action'] = 'GetMatchingProductForId';
param['MarketplaceId'] = 'xxxxxxxxxxxxx';
param['SellerId'] = 'xxxxxxxxxxxxx';
param['IdType'] = 'ISBN';
param['IdList.Id.1'] = 'xxxxxxxxxx';
param['ItemCondition'] = 'New';
param['SignatureMethod'] = 'HmacSHA256';
param['SignatureVersion'] = '2';
param['Timestamp'] = encodeURIComponent(new Date().toISOString());
param['Version'] = '2011-10-01';
secret = 'xxxxxxxxxxxxx';
var url = [];
for(var i in param){
url.push(i+"="+param[i])
}
url.sort();
var arr = url.join("&");
var sign = 'POST\n'+'mws.amazonservices.com\n'+'/Products/2011-10-01\n'+arr;
const crypto = require('crypto');
let s64 = crypto.createHmac("sha256", secret).update(sign).digest('base64');
let signature = encodeURIComponent(s64);
var bodyData = arr+"&Signature="+signature;
await fetch('https://mws.amazonservices.com/Products/2011-10-01', {
method: 'POST',
body: bodyData,
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Accept': '',
},
})
.then(res => {
console.log(res)
})
.catch(error => {
console.log('Request failed', error);
});
}
amazon-mws package is also available for Node.
https://www.npmjs.com/package/amazon-mws

Resources