1

I've been having CORS error when deploying my app so I decided to try out Netlify Dev.

I followed all steps of the written tutorials but I keep getting errors without being able to identify whats wrong. I haven't even deployed it yet and right now I am having the 403 error, before this was the 500 internal server error.

Please let me know if you notice any obvious mistake on my part.

Here's the node-fetch code:

const fetch = require("node-fetch");
exports.handler = async function () {
  const headers = {
    "x-api-key": process.env.REACT_APP_MY_API_KEY,
    "content-type": "application/json",
  };
  try {
    const response = await fetch("https://api.crimeometer.com", { headers });
    if (!response.ok) {
      return { statusCode: response.status, body: response.statusText };
    }
    const data = await response.json();

    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (err) {
    console.log(err);
    return {
      statusCode: 500,
      body: JSON.stringify({ msg: err.message }),
    };
  }
};

Here's the frontend of my app (with the relevant code):

  const initializeApp = useCallback(() => {

    async function fetchData() {
      try {
        let req = new Request(
          `./.netlify/functions/node-fetch?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1`);
        const res = await fetch(req);
        const info = await res.json();

        setCrimes(info.incidents);

      } catch (err) {
        console.log(err);
      }
    }

  }, [submit, lat, lon]);

  useEffect(() => {
    initializeApp();
  }, [initializeApp]);

This is the error in my console: enter image description here

This is where i am trying to fetch data from:

https://api.crimeometer.com/v1/incidents/raw-data?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1

It requires two headers to be set on frontend, which I have done in the netlify function
Parsa
  • 111
  • 3
  • 14
  • https://api.crimeometer.com/v1/incidents/raw-data returns forbidden by default. I guess you suppose to have some auth header for it – rockTheWorld Apr 05 '20 at 08:43
  • I've been fetching data from this api normally on my react app. I had CORS issue locally once. But that was resolved now I can fetch without an issue. Only when I try to deploy to netlify I get the cors error again. Thus i was trying to use netlify functions to work around it – Parsa Apr 05 '20 at 08:51

1 Answers1

0

The API key is currently being added to the React side, where it sets a header and makes a call to the netlify function. But the API key is actually required at the netlify function to request the third party API.

So you have to move the request header from React to Netlify function with something like:

const headers = {
  'x-api-key': API_KEY,
  'content-type': 'application/json',
}

const response = await fetch(
   "https://api.crimeometer.com/v1/incidents/raw-data",
   { headers }
);
Agney
  • 18,522
  • 7
  • 57
  • 75
  • Hey thanks for the answer! So did you mean to name this constant Headers? 'const Headers = require('node-fetch');' Also I removed the headers from the React side and added them on the function. Which now returns a 500 (internal server error) – Parsa Apr 05 '20 at 09:27
  • Sorry, had copied that from their docs, but now that I read it definitely looks off, can you try the edit @parsa – Agney Apr 05 '20 at 13:32
  • Sorry, had copied that from their docs, but now that I read it definitely looks off, can you try the edit @parsa – Agney Apr 05 '20 at 13:32
  • Yes Agney I did put the headers in the function and removed from React side and it gives me a 500 internal error. Do you need to see anymore code? This is my first time using Netlify functions so I really don't have a clue what the issue is – Parsa Apr 05 '20 at 14:02
  • @Parsa Can you add your current function code to the question? – Agney Apr 05 '20 at 14:10
  • @Parsa It seems you are still using `Headers` constructor, can you try this as in my answer – Agney Apr 05 '20 at 14:37
  • *embarassing* Sorry just updated it correctly now, doing it exactly like you did. But the 500 error is still there :( – Parsa Apr 05 '20 at 14:42
  • Is there an error message with the 500? Are you sure API_KEY is available? – Agney Apr 05 '20 at 15:01
  • oh because of the copy pasting I messed up the API_KEY, it should be process.env.REACT_APP_MY_API_KEY. Okay updated that. Now i am back to my old 403 forbidden error SyntaxError: Unexpected token F in JSON at position 0 – Parsa Apr 05 '20 at 15:05
  • I'm wordering if the env key is available in Netlify fn. can you try hardcoding the API key? – Agney Apr 05 '20 at 16:08
  • i did make it available in functions and also in the .env.development file in my react root – Parsa Apr 05 '20 at 16:23