-1

I am attempting to build a full-stack application using React and Google Cloud Products, but it is proving to be difficult for a first-timer. I hosted a very simple function and have been trying to call it from my React application. Every time I call the function, I can see that it gets called and returns a 200 response in the Google Cloud Logs, but on the front-end, I get this message every time:

Access to XMLHttpRequest at 'https://[insert-url-here].cloudfunctions.net/helloWorld' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.

Here is the code for the function:

exports.helloWorld = (req, res) => {
  res.header("Content-Type", "application/json");
  res.header("Access-Control-Allow-Origin", "*");
  let message = req.query.message || req.body.message || 'Hello World!';
  res.status(200).send(message);
};

and here is the code from React:

const cloudCall = async () => {
    try {
      const response = await axios.post(
        `https://us-central1-ss-anglr-dev.cloudfunctions.net/test`,
        {
          message: "Howdy, y'all!",
        },
        {
          headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "Origin",
          },
        }
      );
      const responseData = await response.json();
    } catch (error) {
      console.log(error);
    }
  };

I have no idea how to get around this. All I want to do is host a function and call it from React. It seems like the only way to do that is through Firebase? Whatever that is?

Any guidance would be much appreciated.

  • Your request is being blocked by the browser due to no CORS support in your cloud function. Add CORS headers to your function. https://stackoverflow.com/a/43418322/8016720 – John Hanley Jun 04 '22 at 21:40

0 Answers0