Can anyone please help me to understand, why am I getting errors while calling the google cloud function, whereas I'm not getting an error if I'm calling the same function locally.
PFB the code of the function, that I'm calling from
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
var n1 = null;
var n2 = null;
app.get('/sum', (req, res) => {
n1 = Number(req.query.n1 || req.body.n1);
n2 = Number(req.query.n2 || req.body.n2);
res.json({
"n1": n1,
"n2": n2,
"result": n1 + n2
})
});
app.listen(3000);
exports.calculator = app;
Javascript code of the call made to google cloud function:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"n1":1,"n2":2});
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://us-central1-testing-297304.cloudfunctions.net/calculator/sum", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
All the requests either local or to cloud function is made through Postman
Error that is given by gcp:
Calling your function returns "Cannot GET /sum" error because requests with GET/HEAD method cannot have
body
. What you should to is to change your request to POST (on your code and also your Postman request).and
I did that on my test function and I was able to get a 200 OK with an output using Postman.