I'm trying to send a POST request using Javascript fetch
with application/json
as the content-type
and am having issues. When I do the request in Postman, it works fine. When I try to do it via Javascript fetch, I get an error and on the GCF logging side, when I try to log console.log(req.body)
, nothing is registered.
I am able to successfully get the request body to show up and register when I change the request content-type
to text/plain
and then parse the JSON after the fact in my cloud function, but I'd like to remove this extra step if possible (and also figure out why this isn't working).
Here is the client-side fetch request (essentially pasted from Postman) where the body doesn't get passed for some reason, I've tried various combinations of removing quotes from the property names and also removing the stringify:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"key1":"value1","key2":"value2"});
var requestOptions = {
method: 'post',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("mycloudfunctionsurl", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is my Node.JS runtime 10 Cloud Function code:
exports.helloHttp = async ( req, res ) => {
res.set('Access-Control-Allow-Origin', '*');
console.log(req.body); // <-- Shows up with Postman but not above code, unless I change to text/plain
var key1 = req.body.key1;
console.log('key1 is ' + key1);
// other functions to process the response body
};