0

I tried to make a food recipe app and wrote this code using node:

const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");

const app = express();
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
  const numberOfRecipes = req.body.totalRecipes;
  const apiKey = "apiKey...";

  const url = "https://api.spoonacular.com/recipes/random?apiKey=" + apiKey + "&number=" + numberOfRecipes;

  https.get(url, function(response) {
    response.on("data", function(data) {
      const recipeData = JSON.parse(data);
      // console.log(recipeData);
      // console.log(data);
      const title = recipes[0].title;
      res.write("<h1>The title of the recipe is " + title + ".</h1>");
      res.send();
    })
  });
});

app.listen(3000, function() {
  console.log("The server started at port 3000");
});

But the terminal says

C:\Users\ArunBohra\Desktop\food-recipes\app.js:23 const recipeData = JSON.parse(data); ^

ReferenceError: data is not defined at ClientRequest. (C:\Users\ArunBohra\Desktop\food-recipes\app.js:23:41)

Can anyone help me with this?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You can't expect to parse the entire response once the first `data` event fires. There's an example of how to use it for fetching JSON in [the documentation](https://nodejs.org/api/http.html#http_http_get_options_callback) but you'd be better off using something like axios or node-fetch which have much friendlier APIs. – Quentin Feb 10 '21 at 16:32
  • @Quentin That's true, but it doesn't explain why `data` is undefined. It should be a chunk of the response. – Barmar Feb 10 '21 at 16:34
  • @Barmar — I would expect that, but I try to avoid using that module directly. I was speculating that it might be firing because the headers had arrived but the body hadn't. – Quentin Feb 10 '21 at 16:44
  • @Quentin The sample code in the documentation doesn't have any check for that. – Barmar Feb 10 '21 at 16:47
  • Please check the status code returned from the API. It looks like it's not returning a 200 status code and hence data maybe undefined. – Abrar Hossain Feb 10 '21 at 16:53

1 Answers1

0

I think your not accessing that API content right. Try this :

axios.get('https://api.github.com/users/mapbox')
.then((response) => {

  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
  console.log(response.config);

});

find a popular third-party library like Axios or others and use that to make API calls. then do console logs that will you refer this one How do I use axios within ExpressJS? and this one ReferenceError: request is not defined

turbopasi
  • 3,327
  • 2
  • 16
  • 43
krishna kakade
  • 429
  • 1
  • 6
  • 17