NodeJS http get method access url in response function - node.js

I want to access http request url and parameters in callback function. When I print id with console.log I get error is id undefined. How can I access id and request url?
const Request = require('request');
var id=5;
Request.get('https://example.com/'+id, function (error, response, body) {
console.log("id", id);
}
});

Your code works .may be some syntax error issue,this is the updated
code. I tested it in my console and is working fine.
const Request = require('request');
var id=5;
Request.get('https://example.com/'+id, function (error, response, body) {
if(error) {
return console.dir(error);
}
console.log("id", id);
});
You might need to have a look at the official documentation of the Request package-here and link which explains its usage in detail

Related

How do I read request header without Express

Simply, I have a function that gets the weather using request library. I want to see my request header but all the topics I looked at used with Express. How can I do this ?
const request = require('request');
function getDegree(cityURL){
request.get({
url:cityURL
}, (err, res, body)=>{
if (err) console.log(err);
//My standart codes
console.log(temps);
//I want console.log(requestHeader) or something like this here, for example.
})
}
You can read the request headers by storing it inside a variable (myRequest), then use myRequest.headers.
const request = require("request");
var myRequest = request.get(options, (err, res, body) => {
console.log(requestHeaders);
});
var requestHeaders = myRequest.headers;

How to Store an respone into a variable nodejs request module

I am trying to store the response of an http request made using nodejs by request module but the problem is I can't acsess it after the request is completed in more details we can say after the callback
How I can add it
Here is what I tried till now
Tried to use var instead of let
Tried passing it to a function so that i can use it later but no luck
Here is my code can anyone help actually new to nodejs that's why maybe a noob question
var request = require('request')
var response
function sort(body) {
for (var i = 0; i < body.length; i++) {
body[i] = body[i].replace("\r", "");
}
response = body
return response
}
request.get(
"https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
(err, res, body) => {
if (err) {
return console.log(err);
}
body = body.split("\n");
sort(body);
}
);
console.log(response)
In this I am fetching up the proxies from this api and trying to store them in a variable called as response
var request = require("request");
var response;
async function sort(body) {
await body.split("\n");
response = await body;
console.log(response); // this console log show you after function process is done.
return response;
}
request.get(
"https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
(err, res, body) => {
if (err) {
return console.log(err);
}
sort(body);
}
);
// console.log(response); //This console log runs before the function still on process, so that's why it gives you undefined.
Try this code it works fine I just tested.
put the console log inside the function so you can see the result.
The console.log that you put actually runs before you process the data so that's why you are getting "undefined".
Actually, you will get the data after the sort Function is done processing.

node.js server and AWS asynchronous call issue

I have a simple node Express app that has a service that makesa call to a node server. The node server makes a call to an AWS web service. The AWS simply lists any S3 buckets it's found and is an asynchronous call. The problem is I don't seem to be able to get the server code to "wait" for the AWS call to return with the JSON data and the function returns undefined.
I've read many, many articles on the web about this including promises, wait-for's etc. but I think I'm not understanding the way these work fully!
This is my first exposer to node and I would be grateful if somebody could point me in the right direction?
Here's some snippets of my code...apologies if it's a bit rough but I've chopped and changed things many times over!
Node Express;
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET","http://localhost:3000/listbuckets",false);
Httpreq.send(null);
console.log(Httpreq.responseText);
return Httpreq.responseText;
Node Server
app.get('/listbuckets', function (req, res) {
var bucketData = MyFunction(res,req);
console.log("bucketData: " + bucketData);
});
function MyFunction(res, req) {
var mydata;
var params = {};
res.send('Here are some more buckets!');
var request = s3.listBuckets();
// register a callback event handler
request.on('success', function(response) {
// log the successful data response
console.log(response.data);
mydata = response.data;
});
// send the request
request.
on('success', function(response) {
console.log("Success!");
}).
on('error', function(response) {
console.log("Error!");
}).
on('complete', function() {
console.log("Always!");
}).
send();
return mydata;
}
Use the latest Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP calls. It has built-in support with Promise.
fetch('http://localhost:3000/listbuckets').then(response => {
// do something with the response here
}).catch(error => {
// Error :(
})
I eventually got this working with;
const request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
console.log(JSON.stringify(result));
});
// from within the callback, write data to response, essentially returning it.
res.send(body);
}
else {
// console.log(JSON.stringify(response));
}
})

How to "pass forward" a post() req to another api , get the res and send it back?

Background:
I am using building a system which uses 2 different 3rd parties to do something.
3rd party #1 - is facebook messenger app, which requires a webhook to connect and send info via POST() protocol.
3rd party #2 - is a platform which I used to build a bot (called GUPSHUP).
My server is in the middle between them - so, I need to hook the facebook messenger app to my endpoint on MY server (already did), so every message that the Facebook app get's, it sends to MY server.
Now, what I actually need, is that my server to act as "middleware" and simply send the "req" and "res" it gets to the other platform url (let's call it GUPSHUP-URL), get the res back and send it to the Facebook app.
I am not sure how to write such a middleware that acts like this.
My server post function is:
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
});
Yes , you can pass do request on another server using request module
var request = require('request');
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
request('GUPSHUP-URL', function (error, response, body) {
if(error){
console.log('error:', error); // Print the error if one occurred
return res.status(400).send(error)
}
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
return res.status(200).send(body); //Return to client
});
});
2nd Version
var request = require('request');
//use callback function to pass uper post
function requestToGUPSHUP(url,callback){
request(url, function (error, response, body) {
return callback(error, response, body);
}
app.post('/webhook', function (req, res) {
/* send to the GUPSHUP-URL , the req,res which I got ,
and get the update(?) req and also res so I can pass them
back like this (I think)
req = GUPSHUP-URL.req
res = GUPSHUP-URL.res
*/
requestToGUPSHUP('GUPSHUP-URL',function (error, response, body) {
if(error){
return res.status(400).send(error)
}
//do whatever you want
return res.status(200).send(body); //Return to client
});
});
More info Request module

How to Store the Response of a GET Request In a Local Variable In Node JS

I know the way to make a GET request to a URL using the request module. Eventually, the code just prints the GET response within the command shell from where it has been spawned.
How do I store these GET response in a local variable so that I can use it else where in the program?
This is the code i use:
var request = require("request");
request("http://www.stackoverflow.com", function(error, response, body) {
console.log(body);
});
The easiest way (but it has pitfalls--see below) is to move body into the scope of the module.
var request = require("request");
var body;
request("http://www.stackoverflow.com", function(error, response, data) {
body = data;
});
However, this may encourage errors. For example, you might be inclined to put console.log(body) right after the call to request().
var request = require("request");
var body;
request("http://www.stackoverflow.com", function(error, response, data) {
body = data;
});
console.log(body); // THIS WILL NOT WORK!
This will not work because request() is asynchronous, so it returns control before body is set in the callback.
You might be better served by creating body as an event emitter and subscribing to events.
var request = require("request");
var EventEmitter = require("events").EventEmitter;
var body = new EventEmitter();
request("http://www.stackoverflow.com", function(error, response, data) {
body.data = data;
body.emit('update');
});
body.on('update', function () {
console.log(body.data); // HOORAY! THIS WORKS!
});
Another option is to switch to using promises.

Resources