How to get post request to display in the console - node.js

//Need some help on api in console. I need help figiuring this out
var options = { method: 'POST',
url: URL + 'i/pushes/prepare?api_key=411f2297c3b58651019b3086e17bbfc7',
qs: { api_key: '411f2297c3b58651019b3086e17bbfc7' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
//get request
var options = { method: 'GET',
url: URL + 'o?method=devices&api_key=411f2297c3b58651019b3086e17bbfc7&app_id=5bb537f0b5af9c065041f52d',
qs: { app_id: '5bb537f0b5af9c065041f52d', api_key: '411f2297c3b58651019b3086e17bbfc7', method: 'devices' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log("DEVICE DATAS+++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(JSON.parse(body));
console.log("Device info", ["2018"]["4"])
});
//Please any help is appreciated

Use JSON.stringify to get your response data like this,
console.log(JSON.stringify(body));
Alternatively you can use console.dir like this where you don't have to use JSON.stringify,
console.dir(body);
Hope this helps!

Related

HTTP POST with node.js and request library isn't outputting anything

I'm just testing to see if my POST request to a website works, but it isn't outputting anything. When I use RunKit, it shows an output, but not in my powershell. Am I doing something wrong or is there no output? How can I make it show the output? Here is my code:
var request = require('request');
request.post(
'My_API_URL',
{ json: { "text":"this is my text" } },
function (error, response, body) {
console.log(body);
}
);
What i suggest you, is to update your code like this and try again:
var request = require('request');
var options = {
uri: 'My_API_URL',
method: 'POST',
json: {
"text":"this is my text"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Let me know if the result is the same.
Check this link. You should do post requests like this:
var request = require('request');
var body = JSON.stringify({
client_id: '0123456789abcdef',
client_secret: 'secret',
code: 'abcdef'
});
request.post({
url: 'https://postman-echo.com/post',
body: body,
headers: {
'Content-Type': 'application/json'
}},
function (error, response, body) {
console.log(body);
}
);

how to make async/await work properly in node js?

i am new to node js coding i have two functions in my code one of them,i have made async using async keyword but the issue is it doesn't work the output from second function comes before the first function but i want the output of first function before the second function below given is my code
var request = require("request").defaults({jar: true});
var cookieJar = request.jar();
var options = { method: 'POST',
url: 'http://69.30.210.130:8082/api/session',
headers:
{ 'content-type': 'application/x-www-form-urlencoded' },
form: { email: 'admin', password: 'admin' } };
request(options, async function (error, response, body) {
if (error) throw new Error(error);
let bod=await body;
console.log(bod)
});
var options = { method: 'GET',
url: 'http://69.30.210.130:8082/api/devices',
qs: { id: '1' },
headers:
{ 'postman-token': '021a3566-e1ea-4dd4-4ceb-c81ecd25ddd1',
'cache-control': 'no-cache' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
request uses callbacks as default, it means when you want to chain multiple request, you have to do in this manner:
// first request
request({...}, function(error, response, body1) {
if (error) return console.error('Error', error.message);
// second request
request({...}, function(error, response, body2) {
if (error) return console.error('Error', error.message);
console.log(body1, body2);
});
});
async/await is meant to simplify working with promises, so you can use request-promise:
const rp = require('request-promise');
(async function() { // await can be called only from within an async func
try {
const body1 = await rp({...}); // first request
const body2 = await rp({...}); // second request
console.log(body1, body2);
} catch (e) {
console.error('Error', e.message);
}
})();
Here, the body2 will be resolved after body1 has been resolved. This means async/await brings a synchronous behavior into the asynchronous processing.
You can use axios which is Promises-base out of the box.
EDIT: async from callbacks removed, axios reference added

Unable to access response object data outside the function in node js

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));

Post request to external api

after a post request from an ajax call in angularjs, i want to send the request params from angularjs to an external api. I get all params i want. But I don't know, how i can make a new post request to the api, inside my nodejs url. I need this step to nodejs.
This is my Code
router.post({
url: '/user/:id/sw'
}, (req, res, next) => {
var userId = req.pramas.id;
var firstName = req.pramas.firstName;
var lastName = req.pramas.lastName;
var data = 'test';
res.send(200, data);
});
I found some solutions like this on: (just example code)
request({
uri: 'http://www.giantbomb.com/api/search',
qs: {
api_key: '123456',
query: 'World of Warcraft: Legion'
},
function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(body);
} else {
res.json(error);
}
}
});
but this doesn't work. How I can make a new Post Request with the req.params to an external api? Also i need a Response from the api..
Thanks for help and Ideas :)
Its req.params not req.pramas
Try this
var request = require('request');
router.post({
url: '/user/:userId/shopware'
}, (req, res, next) => {
var params = req.params;
request.get({
uri: 'http://www.giantbomb.com/api/search',
qs: params // Send data which is require
}, function (error, response, body) {
console.log(body);
});
});
Try this,
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'http://localhost.com/test-url',
body: {
foo: 'bar'
},
json: true
// JSON stringifies the body automatically
};
​
request(options)
.then(function (response) {
// Handle the response
})
.catch(function (err) {
// Deal with the error
})
var request = require("request");
exports.checkstatus = async (req, res) => { //this is function line you can remove it
try {
var options = {
method: 'POST',
url: 'https://mydoamin/api/order/status',
headers:
{
signature: '3WHwQeBHlzOZiEpK4yN8CD',
'Content-Type': 'application/json'
},
body:
{
NAME: 'Vedant',
ORDERID: 'ORDER_ID1596134490073',
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body); //get your response here
});
} catch (error) {
return fail(res, error.message);
}
};

Request within a request in nodejs

I am using request library in nodejs. I need to call new url within the request but I am not able to join the response as it is asynchronouse. How do I send variable a as in below request containing result of request within a request.
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
for (i = 0; i < a.length; i++) {
if (a.somecondition === "rightcondition") {
request({
url: url2,
json: true
}, function (error, response, body) {
a.push(response);
});
}
}
res.send(a);
});
Your code seems almost right for what you want. You are just sending the response in the wrong callback. Move it so it only sends after the second request has completed:
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
request({
url: url2,
json: true
}, function (error, response, body) {
for(i=0;i<a.length;i++){
if(a.somecondition === "rightcondition"){
a.push(response);
}
}
res.send(a); // this will send after the last request
});
});
You can use async waterfall
'use strict';
let async = require('async');
let request = require('request');
async.waterfall([function(callback) {
request({
url: url,
json: true
}, function(error, response, body) {
callback(error, [response]);
});
}, function(previousResponse, callback) {
request({
url: url2,
json: true
}, function(error, response, body) {
for(i=0;i<previousResponse.length;i++){
if(previousResponse.somecondition === "rightcondition"){
previousResponse.push(response);
}
}
callback(error, previousResponse);
});
}], function(err, results) {
if (err) {
return res.send('Request failed');
}
// the results array will be final previousResponse
console.log(results);
res.send(results);
});

Resources