Convert AJAX request into HTTP request in nodejs - node.js

Actually i am using ajax call to connect to a 3rd party api when i am using the api on browser and i am able to get the data from the api.
Here is the AJAX code:-
var settings = {
async: true,
//crossDomain: true,
url: "https://rest.cricketapi.com/rest/v2/schedule/?access_token=XXX"
//"url": "https://rest.cricketapi.com/rest/v2/match/indaus_2020_one-day_02/?access_token=XXX"
//bblt20_2019_g28
};
//create token for the api for 24hours
let token;
function getToken() {
$.ajax({
type: "POST",
url: "https://rest.cricketapi.com/rest/v2/auth/",
data: {
access_key: "********************************",
secret_key: "********************************",
app_id: "http://localhost:8000/",
device_id: "developer"
},
success: function(data) {
console.log(data);
token = data.auth.access_token;
console.log(token,);
//do something when request is successfull
createUpcomingMatchesSchedule();
},
dataType: "json"
});
}
function createUpcomingMatchesSchedule() {
var urlJson = settings.url;
urlJson = urlJson.replace(/XXX/g, token);
settings.url = urlJson;
$.ajax(settings).done(function(response) {
console.log(response);
toGetUpcomingMatches(response);
});
}
Now i want to convert this ajax method into http request so that i can use the data on the server using nodejs.
Here is the code:-
const { db } = require("../../utility/admin");
var request = require("request");
// //*************************** API INITIALIZATION ********************************
var settings = {
async: true,
//crossDomain: true,
url: "https://rest.cricketapi.com/rest/v2/schedule/?access_token=XXX"
//"url": "https://rest.cricketapi.com/rest/v2/match/indaus_2020_one-day_02/?access_token=XXX"
//bblt20_2019_g28
};
var options = {
method: "POST",
// hostname: "https://rest.cricketapi.com",
uri: "https://rest.cricketapi.com/rest/v2/auth/",
access_key: "********************************",
secret_key: "********************************",
app_id: "http://localhost:8000/",
device_id: "developer"
};
let token;
function getToken() {
request(options, function(error, response, body) {
if (error) {
console.log(error);
} else {
console.log(body);
token = body.auth.access_token;
console.log(token);
// console.log(response);
}
});
}
module.exports = { getToken };
But i am not able to access the data from the api when i am using the nodejs code.
Thanks in advance

👨‍🏫 For an example, you can look at this code below: 👇
var options = {
method: "POST",
// hostname: "https://rest.cricketapi.com",
uri: "https://rest.cricketapi.com/rest/v2/auth/",
// make sure, on this API, use body or headers.
// If body, you can change this `headers` to `form`.
headers: {
access_key: "********************************",
secret_key: "********************************",
app_id: "http://localhost:8000/",
device_id: "developer"
}
};
let token;
function getToken() {
return new Promise((resolve, reject) => {
request(options, function(error, response, body) {
if (error) return reject(error)
body = JSON.parse(body);
console.log(body);
token = body.auth.access_token;
return resolve(token);
});
})
}
I hope it can help you 🙏.

Related

Always get 502 error when calling AWS lambda endpoint from Node Js using `requestjs`

trying to post data in our AWS serverless api using Nodejs Request package but always get 502 error and can post data from the front end app (React or Jquery).
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
request(
{ method: 'POST'
, uri: 'url here...'
, headers: {
'User-Agent': 'request'
} , multipart:
[ { 'content-type': 'application/json'
, body: JSON.stringify(dataToPost)
}
]
}
, function (error, response, body) {
if(response.statusCode == 201){
console.log('document saved')
} else {
console.log('error: '+ response.statusCode)
console.log(body)
}
}
)```
If you are able to post data using react and Jquery then probably you are not making a post request correctly.Try this code for post request :
const request = require('request');
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
const options = {
url: 'url goes here',
json: true,
body: dataToPost
};
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(`Status: ${res.statusCode}`);
console.log(body);
});
Alternatively you can also use axios which makes code more readable and have inbuilt promise support:
const axios = require('axios');
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
const url = 'put url here'
axios.post(url, data)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
Also check what does AWS Lmbada logs says.

Got error when trying to get access token in nodejs using azure, AADSTS50058: A silent sign-in request was sent but no user is signed in

I am trying to implement azure login in nodejs scheduler app, and then want to upload file to share point.
First i need to login, then get access token,refresh token, admin access token etc.
When i try to get access token , i got error like this.
Here no use of any front end.
URL= 'https://login.microsoftonline.com/' + TENANT_ID + '/oauth2/token',
Status Code Error: 400 -
"{"error":"invalid_grant","error_description":"AADSTS50058: A silent sign-in request was sent but no user is signed in.\r\nTrace ID: 05db5c6a-155c-4870-9bca-a518b5931900\r\nCorrelation ID: 1e8372d0-c1ba-4070-88d7-597e9cb5cb2c\r\nTimestamp: 2019-08-14 12:04:42Z","error_codes":[50058],"timestamp":"2019-08-14 12:04:42Z","trace_id":"05db5c6a-155c-4870-9bca-a518b5931900","correlation_id":"1e8372d0-c1ba-4070-88d7-597e9cb5cb2c","error_uri":"https://login.microsoftonline.com/error?code=50058\"}"
Here the code
async function init(parsedBody) {
var jwtToken = await sharepointAuth.getJWTToken(parsedBody);
console.log("jwtToken:",jwtToken)
const config = {
JWK_URI: appConstants.JWK_URI,
ISS: appConstants.ISS,
AUD: appConstants.conf.AUD,
};
console.log(config)
await azureJWT.verify(jwtToken, config).then(async () => {
console.log("----------------------------------")
var fileName = 'analytics.min.js';
var filePath = './public/analytics.min.js';
var userAccessToken = await getAccessToken(jwtToken);
console.log("userAccessToken:", userAccessToken);
var accessTokenObj = await sharepointAuth.getAdminAccessToken();
accessToken = accessTokenObj.access_token;
console.log("accessToken:", accessToken)
fs.readFile(filePath, { encoding: null }, function (err, data) {
const relativeUrl = web/GetFolderByServerRelativeUrl('${selectedFolderName}');
const SHAREPOINT_HEADER = {
'Authorization': Bearer ${accessToken},
"Content-Type": application/json;odata=verbose,
'Accept': 'application/json;odata=verbose',
}
const options = {
method: "POST",
uri: ${SHAREPOINT_URI}${relativeUrl}/Files/add(url='${fileName}',overwrite=true),
headers: SHAREPOINT_HEADER,
body: data
};
console.log(options)
rp(options)
.then(() => {
// POST succeeded...
console.log('File uploaded!');
})
.catch((error) => {
// POST failed...
console.log("File Upload Error: ", error.toString());
});
});
});
}
const request = require("request");
const endpoint = "https://login.microsoftonline.com/tenentId/oauth2/token";
const requestParams = {
grant_type: "client_credentials",
client_id: "ClientId",
client_secret: "Secret",
resource: "ClientId"
};
request.post({ url: endpoint, form: requestParams }, function (err, response, body) {
if (err) {
console.log("error");
}
else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
}
else {
console.log("parsedBody : " + parsedBody);
console.log("Access Token=" + parsedBody.access_token);
init(parsedBody);
}
}
});
function getAccessToken(jwtToken) {
return new Promise(async (resolve) => {
try {
const options = {
method: 'POST',
uri: URL,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
formData: {
grant_type: appConstants.OTB_GRANT_TYPE,
client_id: appConstants.conf.AUD,
client_secret: appConstants.conf.CLIENT_SECRET,
resource: appConstants.OTB_RESOURCE_URI2,
client_assertion_type: appConstants.OTB_CLIENT_ASSERTION_TYPE,
requested_token_use: appConstants.OTB_REQ_TOKEN_USE,
scope: appConstants.OTB_SCOPE,
assertion: jwtToken,
},
};
console.log("options:", options)
await rp(options)
.then(async (parsedBody) => {
// POST succeeded...
const result = JSON.parse(parsedBody);
console.log("****************************************** result", result)
refreshToken = result.refresh_token;
resolve(result.access_token);
})
.catch((error) => {
// POST failed...
console.log('getAccessTokenRequestError: ', error.toString());
resolve(appConstants.ACCESS_TOKEN_ERROR);
});
} catch (error) {
console.log('getAccessTokenRequestPromiseError: ', error.toString());
resolve(appConstants.MIDDLEWARE_ERROR);
}
});
}
I have no idea about azure login without front end. I want to login in azure and upload file to share point in scheduler app in node.
First i need to login by using client id and secret. then i got bearer token. then i want to get access token by using bearer token. At that time i get error like this.
AADSTS50058: A silent sign-in request was sent but no user is signed in
Why don't you get the access token this way(client credentials flow)?
const request = require("request");
const endpoint =
"https://login.microsoftonline.com/{tenant}/oauth2/token";
const requestParams = {
grant_type: "client_credentials",
client_id: "",
client_secret: "",
resource: "https://mydomain.sharepoint.com"
};
request.post({ url: endpoint, form: requestParams }, function(
err,
response,
body
) {
if (err) {
console.log("error");
} else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
}
}
});
If you need the access token which contains login user message, you can use ROPC flow.
const request = require("request");
const endpoint =
"https://login.microsoftonline.com/{tenant}/oauth2/token";
const requestParams = {
grant_type: "password",
username: "",
password: "",
client_id: "",
resource: "https://mydomain.sharepoint.com"
};
request.post({ url: endpoint, form: requestParams }, function(
err,
response,
body
) {
if (err) {
console.log("error");
} else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
}
}
});

make a post request with a body in nodejs

I am using nodeJS to communicate with an API.
To do that, I am using a post request.
In my code, I use form data to pass the variables, but I get error 400. When I try to put body instead, I get an error saying that my variables are undefined.
This is the API: https://developer.hpe.com/api/simplivity/endpoint?&path=%2Fdatastores
My request:
async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
console.log (name, clusterID, policyID, size)
var options = {
method: 'POST',
url: url + '/datastores',
headers: {
'Content-Type': 'application/vnd.simplivity.v1.1+json',
'Authorization': 'Bearer ' + token,
},
formdata:
{
name: name,
omnistack_cluster_id: clusterID,
policy_id: policyID,
size: size,
}
};
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if (response.statusCode === 415) {
console.log(body);
resolve(body);
} else {
console.log("passed");
console.log(JSON.parse(body));
resolve(response.statusCode);
}
});
});
}
the answer:
testsimon20K 4a298cf0-ff06-431a-9c86-d8f9947ba0ba ea860974-9152-4884-a607-861222b8da4d 20000
passed
{ exception:
'org.springframework.http.converter.HttpMessageNotReadableException',
path: '/api/datastores',
message:
'Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Object> com.simplivity.restapi.v1.controller.DatastoreController.createDatastore(javax.servlet.http.HttpServletRequest,com.simplivity.restapi.v1.mo.actions.CreateDatastoreMO) throws org.apache.thrift.TException,org.springframework.web.HttpMediaTypeNotSupportedException,com.simplivity.restapi.exceptions.ObjectNotFoundException,java.text.ParseException,java.io.IOException,com.simplivity.util.exceptions.ThriftConnectorException,com.simplivity.common.exceptions.DataSourceException',
timestamp: '2019-07-04T08:51:49Z',
status: '400' }
thank you for your help!
I advice to use node-fetch to post your data. This package let you use the default fetch function from ES6.
Here is your answer:
//require the node-fetch function
const fetch = require('node-fetch');
async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
console.log(name, clusterID, policyID, size);
try {
const response = await fetch(`${url}/datastores`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify({
name,
omnistack_cluster_id: clusterID,
policy_id: policyID,
size
})
});
const json = await response.json();
console.log(json);
return json;
}
catch(e) {
throw e;
}
}

Not return value from custom helper

I have problem with my node.js helper. My helper send post request to payu API, API return access_token which i need. If receive access_token then i need return him.
My code:
module.exports = {
createPaymentToken: async () => {
const response = await request({
method: 'POST',
json: false,
url: payuAuthUrl,
form: {
'grant_type': 'client_credentials',
'client_id': payuMerchantID,
'client_secret': payuSecret,
}
},
function (error, response, body) {
if (response) {
const result = (JSON.parse(body));
const token = result.access_token;
return token;
}
}
);
},
When i add console.log(token) before return token, then i see my access_token. The problem is when I want to pass this token to the controller, i.e. it reaches me undefined.
My controller
testPayment: async (req, res) => {
var result = await payuHelper.createPaymentToken();
res.send({
result
});
},
I have no idea what I'm doing wrong.
Your return statement was placed inside callback, so the createPaymentToken function doesn't return anything, just fix your code like sample below:
module.exports = {
createPaymentToken: () => {
return new Promise((resolve, reject) => {
request({
method: 'POST',
json: false,
url: payuAuthUrl,
form: {
'grant_type': 'client_credentials',
'client_id': payuMerchantID,
'client_secret': payuSecret,
}
},
function (error, response, body) {
if (error) {
return reject(error)
}
if (response) {
const result = (JSON.parse(body));
const token = result.access_token;
return resolve(token);
}
}
);
})
},
}
Promise document

Unable to send button template as response on Facebook Messenger Platform (Node.js)

I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: {
access_token: Config.FB_PAGE_TOKEN
},
headers: {
'Content-Type': 'application/json'
},
});
const fbMessage = (recipientId, msg, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
text: msg,
},
},
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.
const fbInfo = (recipientId, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
attachment:{
type:"template",
text:"Check out our website",
payload:{
template_type:"button",
buttons:[
{
type:"web_url",
url:"https://some.website.com",
title:"Website"
}
]
}
}
}
}
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
Instead of form you should use json.
take a look at the code which I have written on glitch
should be something like:
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: <TOKEN> },
method: 'POST',
json: messageData}, ...)

Resources