Node.js request.post return undefined - javascript

I'm trying to return the body of a post request of another site in node.js, but the function below doesn't return anything
// returns "undefined"
mysqlVerify = (socialclub_id, session_id) => {
request({
url: 'http://myapi.site/VerifyUser',
method: 'post',
form: {
socialclub_id: socialclub_id,
session_id: session_id
}
}, (error, response, body) => {
if(error) {
return false // this isnt returning
} else {
console.log(response.statusCode, body)
return body == "1" // this isnt returning
}
})
}
The other site is receiving the post request, and I am also getting the right body back when I use console.log, but the return just doesn't work. What am I doing wrong?

You can't use return inside a callback to return a value when your function is called. You could pass mysqlVerify a callback (a function which is run once the result is determined) and call it once you get a response, like so:
mysqlVerify = (socialclub_id, session_id, callback) => {
request({
url: 'http://myapi.site/VerifyUser',
method: 'post',
form: {
socialclub_id: socialclub_id,
session_id: session_id
}
}, (error, response, body) => {
if(error) {
callback(false) // call the function if false
} else {
console.log(response.statusCode, body)
callback(body == "1") // call the function if condition met
}
});
}
The callback function can then do whatever you need with the result of mysqlVerify.

Related

How can I print the "PUT" and "POST" method at the same time?

The function written to the bottom of the two functions works but the other one does not work. I am not getting an error message either. I think the transaction is taking place but nothing has been written. How can I get both to be written to the console? I'll put the console's printout below. Thank you in advance for your answers.
class Request {
constructor() {
this.xhr = new XMLHttpRequest
}
post(url, data, callback) {
this.xhr.open("POST", url)
this.xhr.setRequestHeader("Content-type", "application/json")
this.xhr.onload = () => {
if (this.xhr.status === 201) {
callback(null, this.xhr.responseText)
} else {
callback("Hata", null)
}
}
this.xhr.send(JSON.stringify(data))
}
put(url, data, callback) {
this.xhr.open("PUT", url)
this.xhr.setRequestHeader("Content-type", "application/json")
this.xhr.onload = () => {
if (this.xhr.status === 200) {
callback(null, this.xhr.responseText, callback)
} else {
callback("Hata", null)
}
}
this.xhr.send(JSON.stringify(data))
}
}
const request = new Request()
request.post("https://jsonplaceholder.typicode.com/albums", {
userId: 9,
title: "Thriller"
}, function (error, response) {
if (error === null) {
console.log(response);
} else {
console.log(error);
}
})
request.put("https://jsonplaceholder.typicode.com/albums/9", {
userId: 2,
title: "Thriller"
}, function (error, response) {
if (error === null) {
console.log(response);
} else {
console.log(error);
}
})
// Console Print
{
"userId": 2,
"title": "Thriller",
"id": 9
}
You should use your xhr once, not multiple times. To fix this, simply call const xhr = new XMLHttpRequest() in each method you need it.
You're only creating one Request object, named request. The first call to request.post() uses this.xhr to perform a POST, but before that async process finishes, you're calling request.put() which performs a PUT, effectively ignoring the previous POST.
A simple way to resolve this is by creating two Request objects:
const request = new Request()
const request2 = new Request()
request.post("https://jsonplaceholder.typicode.com/albums", {
userId: 9,
title: "Thriller"
}, function (error, response) {
if (error === null) {
console.log(response);
} else {
console.log(error);
}
})
request2.put("https://jsonplaceholder.typicode.com/albums/9", {
userId: 2,
title: "Thriller"
}, function (error, response) {
if (error === null) {
console.log(response);
} else {
console.log(error);
}
})
You could also refactor your code to use fetch() instead. Other possible solutions: In JavaScript how do I/should I use async/await with XMLHttpRequest?

Javascript post request function returning undefined

I have the function:
const request = require('request')
function test() {
request.post('endpoint', {
json: {
<DATA>
}
}, (error, res, body) => {
if (error) {
console.log(error);
}else {
return body
}
}
);
}
returns undefined, however when I add/ change my code to:
function test() {
request.post('endpoint', {
json: {
<DATA>
}
}, (error, res, body) => {
if (error) {
console.log(error);
}else {
response_code.push(body);
console.log(body); //Changed Line
}
}
);
}
It will print the value I'm expecting to the console.
How do I fix this function it will return the value, instead of undefined? Appreciate the help.
Edit: Both functions will trigger the api successfully, but getting the return value is crucial for the rest of the program.

NodeJS Request return JSON from function

I've read a couple of posts about this here (callbacks) but I still don't really fully understand how to solve my problem. So I was hoping that somebody here could help me with mine and I would get it better.
Simple put I want the ID I get from the first request to be used for the second request.
I'm new to JavaScript and NodeJS in general.
function idRequest(name) {
var options = {
...
};
function callback(error, response, body) {
if (response.statusCode == 200 && !error) {
const info = JSON.parse(body);
//console.log(info.accountId);
return info.accountId;
}
}
request(options, callback);
}
function requestById(accountId) {
var options = {
...
};
function callback(error, response, body) {
if (response.statusCode == 200 && !error) {
const info = JSON.parse(body);
console.log(info);
}
}
request(options, callback);
}
var id = idRequest('..');
requestById(id);
Try by returning a promise from the first function and inside it resolve the callback, so the once it is resolved , you can use it's then to trigger the second function
function idRequest(name) {
var options = {
...
};
function callback(error, response, body) {
if (response.statusCode == 200 && !error) {
const info = JSON.parse(body);
//console.log(info.accountId);
return info.accountId;
}
}
return new Promise(function(resolve, reject) {
resolve(request(options, callback))
})
}
function requestById(accountId) {
var options = {
...
};
function callback(error, response, body) {
if (response.statusCode == 200 && !error) {
const info = JSON.parse(body);
console.log(info);
}
}
request(options, callback);
}
var id = idRequest('..').then(function(data) {
requestById(data);
});
since callback is a async call, so var id will be undefined, when you call the requestById(id);
so either you can use the promise method, answered by #brk or you can call your requestById(id) function directly from the first callback.

Request Params Node JS 500 Error

As the uri is generated is as expected and list data is shown in page but while sending the req in request method, 500 error occurs instead of retruning body.
uri: http://yufluyuinnepal.com/?vTRIPTYPE=O&vOPSID=O&vSTRFROM=KTM&vSTRFROMTXT=&vSTRTO=PKR&vSTRTOTXT=&vFLIGHTDATE=27-Nov-2018&vRETURNDATE=27-Nov-2018&vADULT=1&vCHILD=0&vNATIONALITY=NP&vNATIONALITYTXT=Nepal&
const uri = `http://yufluyuinnepal.com/?${queryString(query)}`;
console.log(uri);
const req = {
uri: uri,
};
request(req, (error, response, body) => {
if (error) {
return reject(error);
}
if (response.statusCode !== 200) {
return reject(new Error(`Expected 200 but got ${response.statusCode}`));
}
return resolve(body);
});
Let me know how can i return body and what is wrong in my code.
In Request npm module, specify what kind of request is it (GET/POST etc)
// Example GET Request
var options = {
method: "GET",
url:
uri,
headers:
{
// headers as per documentation
}
};
request(options, (error, response, body) => {
if(error){}
if(response.statusCode !== 200){}
return resolve(body);
})
This is your current implementation with a callback function.
const req = {
uri: uri,
method: 'GET'/'POST'
};
request(req, (error, response, body) => {
if (error) {
console.log(error);
}
if (response.statusCode !== 200) {
//Do something
}
console.log(body);
//Do something
});
When using request-promise module you should write something like this
var rp = require('request-promise');
const req = {
uri: uri,
method: 'GET'/'POST'
}
rp(req)
.then((res) => {
//Do something
})
.catch((error) => {
//Do something with error
});
Please try this
let requestp=require('request-promise');
var options = {
    method: 'POST',
    url: 'uri',
    resolveWithFullResponse: true,
    headers: {
                'Accept': 'application/json',
                'Content-Type' : 'application/json'
            },
            body: TextedValue
        };
     
        await  requestp(options).then(async function(Content){
           await requestp(options).then(async function(response){
                if (await response.statusCode == 200)
                    {
                        console.log(Content); // in ur case it is body
                    }
                 else
                    {
                        console.log("Response code "+response.statusCode+" .Try Again Later")
                   }
                })
           })

How to recurse asynchronously over API callbacks in node.js?

An API call returns the next 'page' of results. How do I recurse over that result callback elegantly?
Here is an example of where I need to do this:
var url = 'https://graph.facebook.com/me/?fields=posts&since=' + moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
request.get({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
_.each(body.posts.data, function (post) {
User.posts.push(post); //push some result
});
if (body.pagination.next) { // if set, this is the next URL to query
//?????????
}
} else {
console.log(error);
throw error;
}
});
I would suggest wrapping the call in a function and just keep calling it until necessary.
I would also add a callback to know when the process has finished.
function getFacebookData(url, callback) {
request.get({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
_.each(body.posts.data, function (post) {
User.posts.push(post); //push some result
});
if (body.pagination.next) { // if set, this is the next URL to query
getFacebookData(body.pagination.next, callback);
} else {
callback(); //Call when we are finished
}
} else {
console.log(error);
throw error;
}
});
}
var url = 'https://graph.facebook.com/me/?fields=posts&since=' +
moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
getFacebookData(url, function () {
console.log('We are done');
});

Categories

Resources