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.