0

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

  • where did you define the [routes](https://stackoverflow.com/questions/8864626/using-routes-in-express-js) and the app? – Nir Alfasi Jul 08 '19 at 07:17
  • I have them included in my main.js file using app.use('/', require(router)); and app=express(). is that what you mean? the server code is also in my main.js – Mark Piccirilli Jul 08 '19 at 07:33
  • I read your code wrong. You are using core nodejs method to create an endpoint and not expressjs. `end` should work fine. – Akash Tomar Jul 08 '19 at 08:19
  • You likely want to checkout http.request (https://nodejs.org/api/http.html#http_http_request_options_callback) rather than using XMLHttpRequest on the server side. http.request is the primary supported method of making http calls in nodejs (plus other community libraries on npm). – Elliot Blackburn Jul 08 '19 at 09:35

0 Answers0