I am new to node js. I am trying to call an API that will give me a URL, then I will use this URL to do a number of things like send an SMS, email, insert to mySql DB.
API call is working fine, when I log the URL inside request block (see code commented with WORKING FINE)
But when I try to log the URL outside the request block, it does not work. (See code commented with NOT WORKING FINE). This where I want to do all the things with URL.
Please help. Thanks
var body =
{
"mobile": Mobile,
"policy": Policy_number,
"name": Policy_Holder_Name,
"docs": Docs_Pending,
"target": 'mobile'
};
var options =
{
uri: BaseURL,
method: 'POST',
headers: header,
json: body
};
var URL = '';
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
URL = response.body.url;
console.log(URL); //WORKING FINE
}
});
console.log(URL); //NOT WORKING FINE
As the others state your problem is in the order in which your code executes.
The call to request declares a function on-the-fly (called a lambda function) which will only be executed once the response is received. Execution will then continue through to the end and THEN run that function.
I've commented the code below to try and explain.
/**THIS CODE IS RUN FIRST**/
var body = {
"mobile": Mobile,
"policy": Policy_number,
"name": Policy_Holder_Name,
"docs": Docs_Pending,
"target": 'mobile'
};
var options = {
uri: BaseURL,
method: 'POST',
headers: header,
json: body
};
var URL = '';
/**DECLARES A FUNCTION BUT IS NOT RUN UNTIL THE REQUEST COMPLETES**/
request(options, function (error, response, body) {
/**THIS CODE RUNS LAST**/
if (!error && response.statusCode == 200) {
URL = response.body.url;
console.log(URL); //WORKING FINE
}
});
/**RUNS SECOND - URL IS STILL NOT DEFINED**/
console.log(URL); //NOT WORKING FINE
If you want some later code to be run, then the best pattern may be to put it in a function.
request(options, function (error, response, body) {
/**THIS CODE RUNS LAST**/
if (!error && response.statusCode == 200) {
doMoreStuff(response.body.url);
}
});
function doMoreStuff(URL){
console.log(URL);
}
Your request is asyncronous that's why this thing is happening I would suggest you to use async waterfall refer this -
https://caolan.github.io/async/docs.html#waterfall
default value for URL is '' ,
now make http request and if you will get response code 200 , means you successfully got response and URL is not '' ,
Nodejs works asynchronous in nature , so console.log(URL); may be executed before you make http request to api , so it will print ' ' in console.
so it is better to access variable URL inside request's response
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
URL = response.body.url;
console.log(URL); //WORKING FINE
}
});
yes you can access URL outside , but you need to wait until your request is completed
for example , wait for 10 second and print URL in console like this :
setTimeout(function(){ console.log(URL)}, 10000);
use AsyncJS for asynchronous operations .
Related
kind of a noob question, hopefully someone can help me with.
I am making an application which uses express.js to communicate with bitcoin-core by sending http reqests.
router.get("/getbalance", (req, res) => {
var dataString = `{"jsonrpc":"1.0","id":"curltext","method":"getbalance","params":[]}`;
var options = {
url: `http://${USER}:${PASS}#127.0.0.1:18443/`,
method: "POST",
headers: headers,
body: dataString
};
callback = (error, response, body) => {
if (!error && response.statusCode == 200) {
const data = JSON.parse(body);
res.send(data);
}
};
request(options, callback);
So far it is working quite well, and the problem arises when i try to pass more than one argument to the request, e.g., when i try to send bitcoin to an address in the console, the command is:
bitcoin-cli -regtest sendtoaddress [someaddress] [amount]
i tried to do it like this:
http://localhost:4444/api/sendtoaddress/bcrt1q3nczv7jr88rwvhsyv2rx49l3czfxurzfk240ue/10
but it just freezes.
This is what the "sendtoaddress" request looks like so far.
router.get("/sendtoaddress/:addr/:amount", (req, res) => {
var dataString = `{"jsonrpc": "1.0", "id": "curltext", "method": "sendtoaddress", "params": [${req.params.addr}, ${req.params.amount}]}`
console.log(req.params.addr)
var options = {
url: `http://${USER}:${PASS}#127.0.0.1:18443/`,
method: "POST",
headers: headers,
body: dataString
};
callback = (error, response, body) => {
if (!error && response.statusCode == 200) {
const data = JSON.parse(body);
res.send(data);
}
};
request(options, callback);
As I'm a new contributor so can't create a comment.
it would be better if u could use query method to get the data from the url.
A basic get url would look like this:
"https://xyc.com/vehicle?name="abc"&color="color"
query method is used to get the fields after the ?
We use req.params to get the :id from the url.
you can try changing your get url from this:
"/sendtoaddress/:addr/:amount"
to this:
"/sendtoaddress/:addr?amount="some_amount"
I hope this helps.
I would like to read xml file from url using next code:
var request = require("request");
request.get(
"http://regnskaber.virk.dk/27946272/ZG9rdW1lbnRsYWdlcjovLzAzLzMwLzllL2M3L2Y5LzUxYzQtNDZmNi04YzliLTdhODg1ODA0ZTdlNA.xml",
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
// Continue with your processing here.
}
}
);
In output I got like next:
�������\D���<a>��4E��hQ�:!B��lu���u�ݶ�~^�Q�=<~��~ ���tq��#FUE+k���զj��_+��aNF�V�)M��E�O؍��V�c���c��r�n��U�����3����:�U���Fa�>�Qa\���+�����������W�;�^�FEi���F���Ū\W�9�
�������M����䯇��+�e����uvr\yR�P��mM�*��Ժ��6��^1>m�U����OV�a#ݣ8�� �3����f�>�Pp\��?���Nj�Nj����rqNZ�W[�;���O��Uw2\�O��.M�>e���4Ǵ����?F.��ώ�A;�P��oG��mS�|~ss��,(Y��JX�qJD����&W��,a��n���H��T��*Պ�an�u!&�T�R�VZ����Z����`�Y�a�
It seems that problem with encoding but I can't identify the encoding and fix it. In browser xml output is correct
Using curl to hit your endpoint gets garbled data instead of XML as well. Looking at the headers, content-encoding is set to gzip. So this worked for me:
var request = require("request");
request.get({
method: 'GET',
url: "http://regnskaber.virk.dk/27946272/ZG9rdW1lbnRsYWdlcjovLzAzLzMwLzllL2M3L2Y5LzUxYzQtNDZmNi04YzliLTdhODg1ODA0ZTdlNA.xml",
gzip: true},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
// Continue with your processing here.
}
}
);
Hello guys i want to use node.js to retrieve the user authenticated from an api URL.
I retrieved the codeToken(jsonwebtoken) and put it in the header of my request in postman it works.
But when i go to the code i can't find a way to use node.js+express request, to retrieve the json response of the user that's logged in using all that.
i can't put the url of the API in the sake of the client.
here is my code guys but it's not the right one please advise
var request = require('request');
var options = {
url: '**********',//for the sake of client hidden
headers: {
tokenCode: '15288648455b20a04d5463e'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info);
}else
//console.log(response );
console.log(response.statusCode);
}
request(options, callback);
Headers in my POSTMAN (only tokenCode)
I am using 'request' module in my node app to POST data in ontology model which resides in a fuseki server. I am using the following code:
var request = require('request');
var querystring = require('querystring');
var myquery = querystring.stringify({update: "PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> INSERT { ?KPIs test:hasValue 2009} WHERE { ?KPIs test:hasValue ?Newvalue}"});
request.post('http://localhost:3030/DS-1/sparql?'+myquery, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Show the HTML for the Google homepage.
console.log('successful update');
console.log(body);
} else {
console.log(response.statusCode);
console.warn(error);
}
});
PS: When I use POSTMAN to send the Post request to insert data it works fine but from my node app, it doesn't. it shows error 'bad request 400'.
P.S: GET methods work fine from both POSTMAN and node app.
Problem Solved:
I was making mistake in the format of post request. The corrected format is given below.
var request = require('request');
var querystring = require('querystring');
var myquery2 = querystring.stringify({update: "PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> INSERT { ?KPI_Variables test:hasValue_ROB1 2000} WHERE { ?KPI_Variables test:hasValue_ROB1 ?Newvalue FILTER(?KPI_Variables= test:Actual_Production_Time)}"});
request.post({headers: {'content-type' : 'application/x-www-form-urlencoded'},url:'http://localhost:3030/DS-1/?'+myquery2 }, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Show the HTML for the Google homepage.
console.log('successful update');
console.log(body);
}
else
{
console.log(response.statusCode)
console.warn(error);
}
});
I was missing the 'headers' and 'url' elements in my request.post.
/DS-1/sparql is the query service.
INSERT is an update operation.
Try /DS-1/update
It is better to POST the update in the body of the request with a Content-type. ?update= may not work.
I´m writing a Node.js app which should make an HTTP request using "request" module and save the response in Parse with some parameters and so. I use setInterval() for the loop.
Problem is I'm getting always the same response, like it´s cached or something. If I do a cURL form my local machine I see the actual data, however the loop in Node.js seems to get always the same response.
EDIT with code:
//Loop
setInterval(function(){
try {
foo.make_request();
}catch(e){
console.log(e);
}
}, 30 * 1000); //30 secs
and my make_request function:
function _make_request(){
//Configure the request
var options = {
url: 'http://player.rockfm.fm/rdsrock.php',
method: 'GET'
};
//Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
var artist = body.substring(0, body.indexOf(':'));
var title = body.substring(body.indexOf(':')+3, body.indexOf('#')-1);
console.log(artist + " - " + title);
//upload to Parse etc etc
}
});
}
module.exports.make_request = _make_request;
Yeah! I left it working all the afternoon and it worked well:
request(options, function (error, response, body) {
response.on('data', function() {});
if (!error && response.statusCode == 200) {
// Print out the response body
var artist = body.substring(0, body.indexOf(':'));
var title = body.substring(body.indexOf(':')+3, body.indexOf('#')-1);
console.log(artist + " - " + title);
//upload to Parse etc etc
}
});
The solution was to actually consume the response with .on() method. As it turns out, you need to do it when throwing many request at the same time.