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);
})
Related
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;
}
I'm trying to get get a json from a get request it's work in python but in NodeJs that display me the html code source of the page
this is my code :
app.get("/well", function(request, response) {
const req = require('request');
const options = {
url: 'https://swarmmanager.francecentral.cloudapp.azure.com:3000',
method: 'GET',
headers: {
'Accept': 'application/json',
},
agentOptions: {
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
}
};
req(options, function(err, res, body) {
console.log(body);
});
});
and this is another version but same problem:
app.get("/well", function(request, response) {
g_CnieOidcAddr = 'https://swarmmanager.francecentral.cloudapp.azure.com:3000';
const options = {
hostname: 'swarmmanager.francecentral.cloudapp.azure.com',
port: 3000,
method: 'GET',
headers: {
'Accept': 'application/json',
},
ca: fs.readFileSync("public/IdaktoPKIRootCA.crt")
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
});
i try to do it in python and it's work find that return me a json:
headers = {'Accept': 'application/json'}
r = requests.get(g_CnieOidcAddr + '/.well-known/openid-configuration', params={}, headers = headers, verify='./IdaktoPKIRootCA.crt')
print (r.text)
if anyone has an idea i'm a taker ^^ thanks for reading.
ok that work find i just forgot something at the end of the url so if you come to this page the 2 codes work find to to a request
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()
DigiSigner is working fine if I call it from the postman, but it is giving error Bad Request if I call it with axios form nodejs application.
Here is my code sample.
const digi_signer_url = "https://api.digisigner.com/v1/documents";
const digi_signer_options = {
method: 'POST',
headers: { "Content-Type": "multipart/form-data", 'Authorization': `Basic ${process.env.DIGI_SIGNER_KEY}` },
data: {file: file},
url: digi_signer_url,
}
const r = axios(digi_signer_options)
Here is the solution.
const opts = {
method: 'POST',
url: 'https://api.digisigner.com/v1/documents',
headers:
{
'cache-control': 'no-cache',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`,
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
formData:
{
file:
{
value: fs.createReadStream(path.join(__dirname, '../../templates/sample-po.pdf')),
options: { filename: 'sample-po.pdf', contentType: null }
}
}
};
request(opts, function (error, response, body) {
if (error) throw new Error(error);
if (body) {
const document = JSON.parse(body);
const {document_id} = document;
const send_to_signature = {
method: 'POST',
url: 'https://api.digisigner.com/v1/signature_requests',
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`
},
body:
{
documents:
[{
document_id: document_id,
subject: subject,
message: content,
signers:
[{
email: to_email,
fields: [{ page: 0, rectangle: [0, 0, 200, 100], type: 'SIGNATURE' }]
}]
}]
},
json: true
};
request(send_to_signature, function (error, response, result) {
if (error) throw new Error(error);
console.log(result)
});
}
});
This curl request to the spotify API works perfectly fine
curl -X "POST" -H "Authorization: Basic <my-key-here>" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I'm trying to do this in node, but it's not working and returns a 400 Bad Request. Here is my code. What am I doing wrong?
function AuthRequest(key) {
const req_body_params = JSON.stringify({
grant_type: "client_credentials"
})
const base64_enc = new Buffer(key).toString("base64")
const options = {
host: "accounts.spotify.com",
port: 443,
path: "api/token",
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Basic ${base64_enc}`
}
}
const req = https.request(options, function (res) {
res.on('data', function (data) {
alert("success: " + data)
})
})
req.on('error', function (err) {
alert("error: " + err)
})
req.write(req_body_params)
req.end()
}
I'm trying to use the Client Credentials method as explained here: https://developer.spotify.com/web-api/authorization-guide/
The request should be in application/x-www-form-urlencoded instead of JSON, it should be const req_body_params = "grant_type=client_credentials" with a header of "Content-Type": "application/x-www-form-urlencoded"
function AuthRequest(key) {
const req_body_params = "grant_type=client_credentials";
const base64_enc = new Buffer(key).toString("base64");
const options = {
host: "accounts.spotify.com",
port: 443,
path: "/api/token",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${base64_enc}`
}
};
const req = https.request(options, function(res) {
res.on('data', function(data) {
alert("success: " + data)
})
});
req.on('error', function(err) {
alert("error: " + err)
});
req.write(req_body_params);
req.end();
}
Because token expires is good to request them dynamically, I created a method that output a token as a promise, then you can consume in your request.
const axios = require('axios')
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
function getToken( ) {
return axios({
url: 'https://accounts.spotify.com/api/token',
method: 'post',
params: {
grant_type: 'client_credentials'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: client_id,
password: client_secret
}
})
}
async function getSpotifyData( endpoint ){
const tokenData = await getToken( );
const token = tokenData.data.access_token;
axios({
url: `https://api.spotify.com/v1/${endpoint}`,
method: 'get',
headers: {
'Authorization': 'Bearer ' + token
}
}).then( response => {
console.log( response.data );
return response.data;
}).catch( error => {
throw new Error(error);
});
}
getSpotifyData( 'browse/new-releases' );