I've recently started learning javascript, specifically node.js, and am having trouble in the program I am writing.
Basically I need to make an HTTP request and then set a variable based on the response.
The problem seems to be when my node.js program sends a response the variable is blank. Here is the code for the HTTP request:
function search(productCategory, productId) {
var options = {
"method": "GET",
"hostname": 'HOSTNAME',
"path": [
"PATH",
],
"headers": {
"x-api-key": "API_KEY",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
var result = JSON.parse(body);
var id = result.result[0].value;
// console.log(id);
return req.id;
});
});
req.end();
}
console.log correctly outputs the desired value.
The function that calls this one looks something like this:
module.exports = function getId(req, res) {
var categoryId = "";
var productId = '';
var posId = "";
for(var i=0; i < req.body.result[0].products.length; i++){
categoryId = req.body.result[0].products[i].category_id;
productId = req.body.result[0].products[i].product_id;
posId = search(categoryId, productId);
var product = {
"product number": i,
"product_category": categoryId,
"product_id": productId,
"posId": posId
};
productsArray.push(product);
}
res.send(JSON.stringify(orderingProducts));
};
The goal is to send a response with an array of objects with the key posId gotten from the search method.
Thanks for the help!