Call an external API with Create React App using http-proxy-middleware not returning API's response

55 Views Asked by At

I want to use an external API on my local development environment of an app created with Create React App. When I try to call it directly with fetch I get a CORS error. So used a proxy on the package.json and it works but it's really slow. The URL of the request when calling fetch using this proxy is http://localhost:3000/site?url=https%3A%2F%2Fstackoverflow.com%2F.

So now I'm trying to use http-proxy-middleware to see if the response time is faster. I created a setupProxy.js file on src/ as per Create React App's documentation:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    'site?url=',
    createProxyMiddleware({
      target: 'https://api.websitecarbon.com/site?url=',
      changeOrigin: true,
    })
  );
};

This is how I call the API on my app:

const callApi = async () => {
    const encodedUrl = 'site?url=' + encodeURIComponent(url.current);
    try {
      const response = await fetch(encodedUrl);
      const data = await response.json();
      dispatchWebsite({ type: ACTION.add, data: data });
    } catch (e) {
      console.log(e);
    }
  };

The encodedUrl is /site?url=https%3A%2F%2Fstackoverflow.com%2F and the resulting request URL is http://localhost:3000/site?url=https%3A%2F%2Fstackoverflow.com%2F but I get this error in the response:

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.

And that's because when I use that URL on the browser, it takes me to my own app page. Instead I would like to receive the response from the API:

{
  "url": "https://stackoverflow.com/",
  "green": true,
  "bytes": 728020,
  "cleanerThan": 0.85,
  "rating": "A",
  "statistics": {
    "adjustedBytes": 549655.1,
    "energy": 0.0004146440243348479,
    "co2": {
      "grid": {
        "grams": 0.1832726587560028,
        "litres": 0.10193625280008874
      },
      "renewable": {
        "grams": 0.15889159012511372,
        "litres": 0.08837550242758824
      }
    }
  },
  "timestamp": 1704295485
}

Could anyone explain what's going on and how to fix setupProxy.js so that I get the response from the API?

0

There are 0 best solutions below