0

I am trying to return a json string in my web sever using node.js. I am trying to return the json variable, but it says its not defined. I just need some guidance on how would I be able to return the json variable which is a string

 var http = require("http");
    var https = require("https");

    http 
     .createServer(function (req, res) {
       res.setHeader("Content-Type", "application/json");
       var url = require("url");
       var billing_no = url.parse(req.url, true).query["BOL"]; 

       let url_BOL = "https://www.matson.com/vcsc/tracking/bill/BOL"; 
       var url = url_BOL.replace("BOL", billing_no);

    https //get data from JSON url
      .get(url, (res) => {
        let body = "";

        res.on("data", (chunk) => {
          body += chunk;
        });

        res.on("end", () => {
          try {
            let obj = JSON.parse(body);
            var scraper = {
              message: "Processed results",
              response_code: 200,
              container: [],
            };

            for (var i in obj) {
              var item = obj[i];

              scraper.container.push({
                bookingNumber: item.bookingNumber,
                containerNumber: item.containerNumber,
                originPort: item.originPort,
                destPort: item.destPort,
                equipmentType: item.equipmentType,
                events: item.events,
              });
            }

            var json = JSON.stringify(scraper);
          } catch (error) {
            console.error(error.message);
          }
        });
      })
      .on("error", (error) => {
        console.error(error.message);
      });

     res.end(json);   //return json string 
})
.listen(7000);
  • Duplicate: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Take-Some-Bytes Jul 10 '20 at 20:02
  • Welcome to Stack Overflow. Please take the [tour](https://stackoverflow.com/tour), read about what's [on-topic](https://stackoverflow.com/help/on-topic), and read [How to Ask a Good Question](https://stackoverflow.com/help/how-to-ask). – Ivo Mori Jul 11 '20 at 05:55

0 Answers0