0

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:

Yash
  • 27
  • 1
  • 7
  • I'm not following the story. With Cloud Functions, I usually expect to see just a function that is invoked with req/res parameters. In your code samples, I see a full express.js application. Can you clarify exactly what is deployed to the Cloud Function? Can you also describe the exact nature of the error being reported back to the caller as well as any logs written to Cloud Logging that may include additional details? – Kolban Dec 06 '20 at 20:29
  • Hi Kolban, Thanks for the quick reply. Through the code, I want to check that the user is getting the output if & only if the request is of a particular method(here GET) & have the correct route(here /sum). Also, if the above function executes successfully, I want to add a middleware that will check the authorization token of the request. If the above-mentioned conditions aren't satisfied then, the function should give an error. Error: Your client has issued a malformed or illegal request. Logs: No log is getting generated when the function is called – Yash Dec 07 '20 at 05:16

1 Answers1

0

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).

app.post('/sum', (req, res)

and

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

I did that on my test function and I was able to get a 200 OK with an output using Postman.

Donnald Cucharo
  • 3,866
  • 1
  • 10
  • 17