Nodejs Ajax Call - node.js

I was calling this function from javascript file. which was working perfect but now i want to call same function using Node js. please give me any alternate method. this function is use to insert data onclick event before.
function signup_validations_google(name_g,email_g,pass_g)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8000/uri?name="+name+"&email="+email+"&pass="+pass, true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
alert("Registration successful");
}
}
xmlhttp.send();
}

In node.js, you would generally use http.get() from the http module or request() from the request module. I find request() is a bit easier to use:
const request = require('request');
let query = {name, email, pass};
request({uri: "http://localhost:8000/uri", query: query}, function(err, msg, body) {
if (err) {
// error here
} else {
// response here
}
});
There are a zillion other possible options for the request() module described here.

Related

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.

mocking the request module with sinon

I want to mock the following piece of code using sinon,
request(options, function(error, response) {
if (error) {
reject(error);
} else {
resolve(response);
}
});
can you help me with this ?
Assuming it as a get request,
let request = require('request') // request module.
let options = "some url" // mock data for url
requestStub = sinon.stub(request, 'get').callsArgsWith(0, options);// first argument of request call is options.
requestStub.yields(error, response)//It returns error and response. These will be mock data
sinon.assert.calledOnce(requestStub)//Test to check whether stub is called or not.
requestStub.restore(); // need to restore stub every time after use.
So depending upon what error and response you pass, it will return output accordingly.

Getting data from API inside a graphQL resolver deployed on Azure node.js function

I am trying to deploy a GraphQL server on node.js platform using Azure functions. I have been able to deploy a basic hello world app.
However, I need to get data from a backend API in the resolver. I am not able to get either fetch or request package to work in Azure functions.
Below is my code:
var { graphql, buildSchema } = require('graphql');
var fetch = require('node-fetch');
var request = require('request');
var schema = buildSchema(`
type Query {
myObject: MyObject
}
type MyObject {
someId (data: String) : String
}
`);
var root = {
myObject: () => {
return {
someId: (args) => {
// Code enters till this point.
// I can see context.info messages from here.
// return "hello"; <--- This works perfectly fine.
return request('http://example.com', function (error, response, body) {
// -----> Code never enters here.
return body;
});
}
}
}
};
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
graphql(schema, req.body, root)
.then(response => {
context.res = {
body: JSON.strigify(response)
};
context.done();
});
};
I have tried using fetch and request modules. But with both of them, I see the same behavior - the response never returns. The request eventually times out after 5 minutes. If instead of fetch or request, I choose to return some dummy value, I see the response getting returned correctly to the query. With fetch, I don't see the then block or the catch block ever executing.
Note: I have tried both http and https URLs in the request URIs but none of them seem to return any data.
Is it an issue with the way I have implemented the fetch/request or is it an issue with Azure functions in general?
Answering my own question:
It seems that node-fetch and request don't actually return promises. Wrapping the request around Promise seems to solve the problem. Something similar to this answer.

Node JS callback executed without waiting

I have the following function which performs a GET call. I want to wait for the response and then perform the next step. My code looks like this
getListOfChannels : function(token, callback){
var Channels = [];
var options = { method: 'GET',
url: url,
headers:
{
'x-api-key': token } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
var json = JSON.parse(body)
var data = json.MemberEntitlement;
for(var i=0 ; i < data.length ; i++){
if(data[i].Entitled == false){
Channels.push(data[i].ChannelNumber);
}
}
});
callback(Channels[0]);
}
Also my callback function is just printing the value
simplePrint : function(arg){
console.log(arg)
}
But still, the callback function does not wait for the full response and prints out undefined.
What should i do. I can add implicit wait but that doesnt seem like a good practice.
I think you are invoking callback after the request function invocation. It's not in request's scope, but in getListOfChannels scope. Therefore, callback is running synchronously. Try replacing:
});
callback(Channels[0]);
}
with
callback(Channels[0]);
});
}

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));
}
})

Resources