Javascript post request function returning undefined - javascript

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.

Related

return response in a function in express app

As we know, we must return the response in the express app to avoid "Cannot set headers after they are sent to the client" error.
However, In below code, I'm trying to return the response but It's returning to our router and causes mentioned error. how I can directly return the response in function?
router.post("/admins", async function (req, res) {
var newAdminObj = await newAdminObjectDecorator(req.body, res);
var newAdmin = new Admins(newAdminObj)
newAdmin.save(function (err, saveresult) {
if (err) {
return res.status(500).send();
}
else {
return res.status(200).send();
}
});
});
// the function
var newAdminObjectDecorator = async function (entery, res) {
// doing some kinds of stuff in here
// if has errors return response with error code
if (err) {
// app continues after returning the error header response
return res.status(500).send();
}
else {
return result;
}
}
Never run a response operation other than the controller's functions. Let the other function return the answer and decide according to the answer.
router.post("/admins", async function (req, res) {
var newAdminObj = await newAdminObjectDecorator(req.body);
if (newAdminObj instanceof Error) {
return res.status(500).send()
}
var newAdmin = new Admins(newAdminObj)
newAdmin.save(function (err, saveresult) {
if (err) {
return res.status(500).send();
}
else {
return res.status(200).send();
}
});
});
// the function
var newAdminObjectDecorator = async function (entery) {
// doing some kinds of stuff in here
// if has errors return response with error code
if (err) {
// app continues after returning the error header response
return err;
}
else {
return result;
}
}

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.

Javascript, error when return on a main function

I have my function who call the DB to do something :
function callQuery(query) {
db.query(query, (err, res) => {
if (err) {
// Error DB connecion
console.log(err.stack)
} else {
// Send back the results
return(res.rows[0])
}
})
}
My problem is when I call this function by :
const idUser = callQuery("INSERT INTO blablabla RETURNING *")
My data is successfully added in the DB, but idUser came null. It should be res.rows[0]
I am using this tutorial (who instead of setting a variable, call console.log) : https://node-postgres.com/features/connecting
Thank you in advance
I think this is something due to asynchronous
let promisess = new Promise(function(resolve, reject) {
function callQuery(query) {
db.query(query, (err, res) => {
if (err) {
// Error DB connecion
console.log(err.stack)
} else {
// Send back the results
resolve(res.rows[0])
}
})
}
});
promisess.then((res)=> {
your data in res
});

Node.js request.post return undefined

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.

Chaining multiple request using bluebird

I'm trying to convert my existing code using BlueBird, please suggest a best option to chain multiple request. Error happening in each callback needs to be redirected to rendered with different error.
request(option1, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data= JSON.parse(body);
if(data.valid){
if(data.expired){
next();
} else {
request(option2, function (error2, response2, body2) {
var data2= JSON.parse(body2);
if(data2.valid) {
request(option3, function (error3, response3, body3) {
next();
})
} else {
res.json({error:'Error1'});
}
})
}
} else {
res.json({error:'Error2'});
}
} else {
res.json({error:'Error3'});
}
})
This is pretty straightforward, also note your current code doesn't handle errors in the second and third requests and this does:
var request = require("request-promise"); // request - converted to bluebird
request(option1).then(data=> {
if(!data.valid) throw Error("Error3");
if(data.expired) return;
return request(option2).then(JSON.parse);
}).then(data2 => {
if(!data2) return; // didn't need to fetch additional data
if(!data2.valid) throw Error("Error2");
return request(option3);
}).then(() => {
next();
}, e => {
res.json(error: e.message);
// better log this.
});
var rp = require('request-promise');
function handleError(err) {
res.json({
error: err.message
});
}
function parse(data) {
if (data) {
return JSON.parse(data);
}
}
rp(option1)
.then(parse)
.then(function (data) {
if (!data || !data.valid) {
throw Error('Error2');
}
if (data.expired) {
return;
}
return option2;
})
.then(rp)
.then(parse)
.then(function (data2) {
if (!data2 || !data2.valid) {
throw Error('Error1');
}
return option3;
})
.then(rp)
.then(parse)
.then(function () {
next();
})
.catch(handleError);
You don't need to manually check for statusCode but if you need to do so, first you have to add resolveWithFullResponse attribute to your option1 object, which allows you to receive the response object:
function checkStatusCode(response) {
if (response.statusCode !== 200) {
throw Error('Error3');
}
return response.body;
}
// add resolveWithFullResponse attribute to option1
option1.resolveWithFullResponse = true;
rp(option1)
.then(checkStatusCode)
.then(parse)
//...

Categories

Resources