-2

I am trying to use the citymapper API from a react App but I get the following error

Access to fetch at '<CITYMAPPER API URL>' from origin '<MY APP URL>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried to use it on a local development server and on a live server and neither works. I got the request to work using Postman/Insomnia client but as soon as I put it into the App, it does not work.

The code for the request is as follows


  function getNav() {
    const request = new Request(
      `<CITYMAPPER API URL>`,
      {
        headers: {
          "Citymapper-Partner-Key": "<MY KEY>",
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
        },
      }
    );
    fetch(request)
      .then((response) => response.json())
      .then(
        (data) => {
          setNavigation(data);
        }
      )
      .catch((error) => {
        console.log(error);
      });
  }

If I add mode:"no-corse", I get a 401 error.

How can I solve the problem and make a request? Thanks in advance

geof2496
  • 1
  • 1
  • is the server yours? add CORS headers. Is the server NOT yours? Proxy the request using your server as servers aren't blocked by CORS - in the meantime [learn about CORS](https://www.youtube.com/watch?v=PNtFSVU-YTI) – Bravo May 09 '22 at 08:58
  • The Server on which the React app and API are hosted is MINE. The only server I do not own in this is the citymapper API – geof2496 May 09 '22 at 09:00
  • You need to make the request to CityMapper _via_ your server, otherwise (as well as the CORS problem) you're publicly exposing your key. – jonrsharpe May 09 '22 at 09:02
  • so, the server giving the error is not yours ... then you can't access resources on it in a browser, unless it allows you to do so ... since it does not allow this (via CORS responses) then your only choice is to use your own server to make the requests for you - i.e. proxy the request via your server – Bravo May 09 '22 at 09:02

0 Answers0