I am making an ajax request from the client side to the server side. Then from the server I am making another ajax request to a nutrition api to get information about certain foods. I am doing it this way so that my api key is not in the public client side javascript code. It seems that the request from the client is sent and then received by my server. Then the server makes the request to the api and receives a correct response. However, the response is getting lost between the server and the client.
I have tried printing to the console at various test locations. I tried using res.write(object) and res.end(object)
here is my node.js server:
http.createServer(function(req, res) {
var q = url.parse(req.url, true).query;
console.log("q.newIngredient: " + q.newIngredient);
var apireq = new XMLHttpRequest();
apireq.open('GET', 'https://api.nutritionix.com/v1_1/search/' + q.newIngredient + '?results=0:1&fields=item_name,nf_serving_size_qty,nf_serving_size_unit,nf_calories,nf_total_fat,nf_colesterol,nf_sodium,nf_total_carbohydrate,nf_sugars,nf_protein&appId=' + apiid + '&appKey=' + apikey, true);
apireq.addEventListener("load", function() {
if(apireq.status >= 200 && apireq.status <= 400) {
console.log("respond test");
res.writeHead(200, {"Content-Type": "application/json"});
console.log("type: " + typeof(apireq.responseText));
console.log(JSON.parse(apireq.responseText));
res.end(apireq.responseText);
console.log("respond test 2");
}
else {
console.log("Error in network request: " + req.statusText);
}
});
apireq.send(null);
//event.preventDefault();
}).listen(3001);
and here is my client side ajax request
req.open("GET", "http://localhost:3001/?newIngredient=" + newIngredient, true);
req.addEventListener('load', function() {
if(req.status >= 200 && req.status < 400) {
console.log("respond test 3");
var response = JSON.parse(req.responseText);
console.log(response);
console.log(response.hits[0].fields.item_name);
var nfacts = response.hits[0].fields;
console.log(nfacts);
}
else {
console.log("Error in network request: " + req.statusText);
}
});
req.send(null);
event.preventDefault();
});
}
the "response test 3" message does not get printed to the console. However the other response test messages are printed, and the correct response from the api is printed.
Thank You!
Edit: I have discovered that this is a CORS issue. I am getting an error message in the browser developer tools console saying:
Access to XMLHttpRequest at 'http://localhost:3001/?newIngredient=ham' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I added this line of code and it worked:
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");