Fetching from my own Server, ERROR: "Unexpected end of JSON input"

Viewed 52

i'm really new to Backend and was trying to fiddle around with API-Calls and Client-Server stuff.

const express = require("express");
const cors = require("cors");
const fetch = require("node-fetch");

const app = express();
app.use(cors());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get("/express_backend", (req, res) => {
  fetch(
    "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=XXXXXXXXXXXXXXXXXX&steamid=76561197996613749&format=json"
  )
    .then((response) => response.json())
    .then((data) => console.log(data))
    .then((data) => res.send(data));
});

so this is my server file and it properly fetches the data from the steam api output screenshot

But im struggling to get this from the server to my client.

import React, { useState, useEffect } from "react";

const App = () => {
 const [data, setData] = useState(null);

 useEffect(() => {
   fetch("/express_backend")
     .then(function (response) {
       return response.json();
     })
     .then(function (json) {
       let fetchedData = json;
       setData(fetchedData);
     })
     .catch(function (err) {
       console.log(err.message);
     });
 }, []);

 return (
   <div>
     <p>{data}</p>
   </div>
 );
};

export default App;

I think that the "Unexpected end of JSON input" Error is related to the "response.json() line but im not really sure how to go on with this or how to fix it. Thanks in Advance!

1 Answers

there is a small issue on the backend server. In the below Promise chain, the second thenable is not returning anything to the third thenable, so basically you are not writing anything to the 'response' when doing res.send(data)

app.get("/express_backend", (req, res) => {
  fetch(
    "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=XXXXXXXXXXXXXXXXXX&steamid=76561197996613749&format=json"
  )
    .then((response) => response.json())
    .then((data) => console.log(data))
    .then((data) => res.send(data));
});

The correct order would be to merge second and third then handlers, like so

app.get("/express_backend", (req, res) => {
  fetch(
    "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=XXXXXXXXXXXXXXXXXX&steamid=76561197996613749&format=json"
  )
    .then((response) => response.json())
    .then((data) => {
         console.log(data);
         res.send(data);
     })
})
Related