Server not sending correct response to frontend?

Viewed 223

I am trying to make my server a middleman so that the frontend queries the server with a searchedValue, the server queries the API with the searchedValue, and the server returns the API response to the frontend.

Currently, the server is querying the API correctly. Here is the code and responses:

Query: http://localhost:3000/optionsAPI/AAPL

Code [server.js]:

app.get("/optionsAPI/:ticker", (req, res) => {
    var tempJSON = [];
    const searchString = `${req.params.ticker}`;
    const url = `API URL HERE, HIDING FOR SECURITY`;

    fetch(url, { headers: { Accept: 'application/json' } })
    .then(res => res.json()
    .then((json) => {
        
        tempJSON = json;
        console.log(tempJSON);
    }))
    .catch(err => console.error(err)); // eslint-disable-line
    
    
    res.send({ message: tempJSON });
});

Here is the code in the component:

Code [Component.js]:

useEffect(() => {
    const fetchData = () => {
      const url = `/optionsAPI/${searchedValue}`;
      fetch(url, { headers: { Accept: 'application/json' } })
        .then(res => res.json()
          .then((json) => {
            setOptions(json.option_activity || []);
          }))
        .catch(err => console.error(err)); // eslint-disable-line
    };
    debounce(fetchData());
  }, [searchedValue]);

The console log is perfect! It logs tempJSON as I would expect to see it, but the res.send message is simply {"message":[]}. Therefore, the response my frontend gets is an empty []. This doesn't; make sense - the console is logging the response, so why is the frontend receiving a blank []?

Thanks in advance.

1 Answers

In your code you are calling an api which returns a promise, so to handle the data returned by the promise you should add your code inside .then() function, meaning you have to wait for the promise to be resolved before accessing the data and sending it to the client

app.get("/optionsAPI/:ticker", (req, res) => {
    var tempJSON = [];
    const searchString = `${req.params.ticker}`;
    const url = `API URL HERE, HIDING FOR SECURITY`;

    fetch(url, { headers: { Accept: 'application/json' } })
    .then(res => res.json()
    .then((json) => {
        
        tempJSON = json;
        console.log(tempJSON);

        // the response should be sent from here
        res.send({ message: tempJSON });
    }))
    .catch(err => {
        console.error(err);
        // you also need to send a response when catching erros
        res.status(400).send({ err });
    }); 
});

you can use async / await to make your code much cleaner

app.get("/optionsAPI/:ticker", async (req, res) => {
    var tempJSON = [];
    const searchString = `${req.params.ticker}`;
    const url = `API URL HERE, HIDING FOR SECURITY`;

    try {
        const result = await fetch(url, { headers: { Accept: 'application/json' } })
        const json = await result.json()
        
        tempJSON = json;
        console.log(tempJSON);

        res.send({ message: tempJSON });
    } catch (error) {
        console.error(error);
        res.status(400).send({ error });
    }      
});
Related