Node js passing query string to url - node.js

I am using the request promise plugin request to create the get and post api. I want to pass the URL with a parameter. below is my code. How to pass parameter value in URL?
async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/{studen_id}/branch/{studentbranch}',
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}

To pass the parameter by URL, you can pass like this:
http://localhost:3000/api/student/?id={studen_id}&branch={studentbranch}

async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/'+encodeURIComponent(req.body.id)+'/branch/'+encodeURIComponent(req.body.branch),
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}

Related

a single script in node to get authToken from some xyz oath2 /token end point and call the following api. I have coded something like this below

// getToken.mjs
import axios from 'axios';
import qs from 'qs';
var data = qs.stringify({
'client_id': 'xxxx-xxx',
'client_secret': 'xxxx-xxx',
'scope': 'https://graph.microsoft.com/.default',
'grant_type': 'client_credentials'
});
const config = {
method: 'get',
url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded', },
data : data
};
export let accessToken = axios(config)
.then(function (response) {
console.log((response.data.access_token));
})
.catch(function (error) {
console.log(error);
});
--------- Calling the API in the second script -----
//get response.js
import axios from "axios";
import { accessToken } from "./getToken.mjs";
const config = {
method: 'get',
url: 'https://graph.microsoft.com/v1.0/me/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${accessToken}`,
}
};
export let data000 = axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
}).catch(function (error) {
console.log(error);
});
console.log(data000);
On executing the > node response.js ... returns 401, client secret, and id is correct. However, I feel the accessToken is not getting imported and hence the error. How do I fix this?
Try to use POST method to get accessToken.
const config = {
method: 'post',
url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded', },
data : data
};

Sending form in post request using https library

I have to call an api, for which we are using request library.
const options = {
uri: 'https://abcd.com',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xxxxxxxxx'
},
form: {
'a':1,
'b':2
}
}
request(options, (e, res, data) => {});
How would I rewrite the same using node's https library.
I tried using https library's https.request() with 'POST' type and .write with form object. Didn't work.
Also changed Content-Type to application/x-www-form-urlencoded, didn't work either
This example is from the documentation using the request package ,the form takes a object consisting of key value pair from that of the form
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}},
function(err,httpResponse,body){ /* ... */ })
enter link description here
You can read the API docs at: https://nodejs.org/api/https.html
Below code should work fine:
const https = require('https')
const data = JSON.stringify({
'a':1,
'b':2
})
const options = {
hostname: 'example.com',
port: 443,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Length': data.length
'Authorization': 'Bearer xxxxxxxxx'
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()

HTTP Module to Request Module Translation

How to rewrite this node.js code, just using the request module not http module?
var options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
}
};
var req = http.request(options, function(res) {
console.log('Status:' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.on('data', function(body) {
console.log('Body:' + body);
});
});
req.write('{"x-api-key":"12345", "Content-Type":"application/json", "appId":"DEMO1","momentId":"GAME_COMPLETE","deviceType":'
Android ','
campaignId ':"DEMOCAMP1","rewardGroupId":"amz1yprime"}');
req.end();
I've done part of it:
const request = require('request');
const data = JSON.stringify({
"appId": "DEMO1",
"momentId": "GAME_COMPLETE",
"deviceType": 'Android ',
'campaignId ': "DEMOCAMP1",
"rewardGroupId": "amz1yprime"
})
const options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetReward',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
},
};
request.post(options, function(err, res, body) {
console.log(body);
});
But i don't know how to send "data" and how to get a response to the request
The re-write is not drastic. It's some few simple change.
const request = require('request')
var options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
},
body: {
'appId': 'DEMO1',
'momentId':'GAME_COMPLETE',
'deviceType' : 'Android',
'campaignId' : 'DEMOCAMP1',
'rewardGroupId': 'amz1yprime'
},
json: true // sets body to JSON representation of value
};
request.post(options, (err, httpResponse, body) => {
if (err) console.error(err);
// httpResponse contains the full response object, httpResponse.statusCode etc
else console.log(body);
})

How to use bearer token for authorization for POST method in sync-request?

How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.

incorrect behaviour of node-fetch while trying to get token from an api

I want to connect to an external api using some node-fetch code. My code first sends the login details & should receive a token from the api. Then this token is used for all the later communications.
Here is the code :
import fetch from 'node-fetch';
function getTokenForAuth(info) {
try {
var auth_token = '';
fetch(api_url + '/api/api-token/', {
method: 'POST',
body: JSON.stringify(info),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(res) {
return res.json();
})
.then(function(json) {
auth_token = json;
})
return auth_token.token;
}
catch (e) {
console.log('[-] Error: Token Not Received');
console.log('[!] Exception: ' + e);
}
}
function getJSONFromRelativeURL(relativeURL, info) {
return fetch(`${api_url}${relativeURL}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + getTokenForAuth(info)
}
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
})
}
In the getJSONFromRelativeURL() function's request headers, if I hardcode the token, I get correct results. But if I run the code as it is now, I get an error saying : { detail: 'Invalid token.' }.
I think this is because of async nature of the promise in the fetch function, because of which it sometimes isnt able to send the token in time before the getJSONFromRelativeURL() gets called. I am not sure about this hypothesis & don't know how to correct this.
Your problem is here:
.then(function(json) {
auth_token = json;
})
return auth_token.token;
Your return statement is outside the Promise chain. This means that, at the point you hit return, the fetch request hasn't had a chance to even run yet. You've essentially just told the fetch Promise chain what to do when it does return.
So essentially
I think this is because of async nature of the promise in the fetch function, because of which it sometimes isnt able to send the token in time before the getJSONFromRelativeURL() gets called.
is 100% correct.
What you'll need to do is restructure things a little bit:
function getTokenForAuth(info) {
return fetch(api_url + "/api/api-token/", {
method: "POST",
body: JSON.stringify(info),
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
}).then(function(res) {
return res.json();
});
}
function getJSONFromRelativeURL(relativeURL, info) {
return getTokenForAuth(info)
.then(function(token) {
return fetch(`${api_url}${relativeURL}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${token}`
}
});
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
});
}
Have not tested it but it looks something like the following. For error handling use .catch(()=>{}) at the end of each chain.
function getTokenForAuth(info) {
var auth_token = '';
return fetch(api_url + '/api/api-token/', {
method: 'POST',
body: JSON.stringify(info),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(res) {
return res.json();
})
}
function getJSONFromRelativeURL(relativeURL, info, token) {
return fetch(`${api_url}${relativeURL}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + token
}
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
})
}
getTokenForAuth(info)
.then((token)=>{
return getJSONFromRelativeURL(relativeURL, info, token)
})

Resources