0

I'm a new developer learning how to work with API's and I've run into this error a few times now that keeps crashing Node:

SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage. (/Users/dharmendrasingh/Desktop/WeatherProject/app.js:13:28)

I'm not really sure how to resolve it or what the problem is exactly... my JS code looks like this:

const express = require("express");
const https = require("https");

const app = express();

app.get("/", function(req, res){
  const url = "https://postman-echo.com/get?q=London&appid=639179c2c6d4f4db9c4657a69ac05438&units=matric";

  https.get(url, function(response){
    console.log(response.statusCode);

    response.on("data", function(data){
      const weather = JSON.parse(data);
      console.log(weather);

    });

  })
  res.send("Server is up and running");
})


app.listen(3000, function(req, res){
  console.log("Server is running at port: 3000.");
});
  • 1
    Welcome to SO. Try printing out (somewhere) what the value of ```data``` is and check if it is indeed a valid JSON structure. – ewokx Mar 24 '22 at 04:48
  • You're using the `https` callbacks incorrectly. You're meant to use the `data` event to build up the entire payload. Honestly, I'd avoid clunky utilities like `https` and use something more friendly like [got](https://www.npmjs.com/package/got), [node-fetch](https://www.npmjs.com/package/node-fetch) or Axios – Phil Mar 24 '22 at 05:12

0 Answers0