2

I have made a Cloud Function in GCP with a HTTP trigger. I am attempting to use fetch to pass a JSON object to this endpoint in a POST request. I have tried using both the functions-framework to server the function locally and also deploying to GCP. I am able to successfully make the request and receive the correct response if I use Postman/dev tools.

I have a React app which is running the following function in the componentDidMount() function of a component:

getData() {
    const requestOptions = {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Origin': 'AUTHORITY'
        },
        body: JSON.stringify({
          "vendors": [{
            "postcode": "12345",
            "distance": 15
          }, {
            "postcode": "67890",
            "distance": 15
          }, {
            "postcode": "13579",
            "distance": 15
          }, {
            "postcode": "24680",
            "distance": 25
          }, {
            "postcode": "10293",
            "distance": 10
          }],
          "customer": "12345"
        })
    };

    return fetch('http://localhost:8080/', requestOptions)        
      .then((response)=>response.json())
      .then((responseJson)=>{return responseJson});
  }

When I check the Network tab, the JSON object is not being passed with the request. The POST request and the OPTIONS request both have a status of blocked in the Network tab. I can press Edit and Resend and attach the correct JSON object and the response returns a 200 status.

Inside the Cloud Function I am currently returning the response as:

res.set({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': '*' }).send(result);

It feels like the issue is on the React side (JSON not being sent with the POST request), but it could well be a CORS issue.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Sam Brown
  • 21
  • 1
  • If it were a CORS issue, the browser would be logging a message in the devtools console that explicitly mentions CORS. If the browser isn’t logging such a message, then you can safely rule out CORS behavior as a source of the problem. – sideshowbarker Dec 31 '20 at 18:15
  • Please, see [this SO question](https://stackoverflow.com/questions/29775797/fetch-post-json-data), I think it will be helpful – jccampanero Dec 31 '20 at 18:22
  • I do get a CORS error in the network tab `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).`. I am adding this header inside the function already. Thanks both - will check the question. – Sam Brown Jan 02 '21 at 13:03
  • Did the information in the second question fixed the issue you were facing? – Ralemos Jan 12 '21 at 16:25

0 Answers0