Sending 200 success using node js Google Cloud Function

496 Views Asked by At

I'm trying to send a 200 - Success back using the 'res' parameter of a google cloud function. I kept getting the error 'TypeError: res.setStatusCode is not a function.' even though this should be a part of the object. So I did the below to make sure.

const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('app', (req, res) => {
    
    console.log(typeof res); // "Function"
    console.log(Object.keys(res)); // []
    console.log(res.statusCode); // undefined
    console.log(res.headers); // undefined
    console.log(res.body); // undefined
    
    res.setStatusCode(400);
    res.send('Success');
    
});

It appears res is actually a function (not an object) and statusCode is not defined. Is this correct or Am I missing something here? How do I change this to send a 200 while using @google-cloud/functions-framework? Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER

As @cmgchess suggested, this was achieved by using functions.http. I'm adding an example code block for anyone who may get the same problem.

const functions = require('@google-cloud/functions-framework');

functions.http('app', (req, res) => {
   //Do your work
   res.status(200).send('Success');
});
3
On

functions-framework is built on top of Express, and their req/res objects wrap Express's, so it should be res.status, not res.setStatusCode.

Additionally, you're mixing the cloudEvent API with the http API. If you want to directly work with the request and response objects, it looks like you'll need to use cloudevents — I'm unable to find anything in the functions-framework repo that points to a better option, but I would welcome a correction on that.

Also there's no need to manually set a 200, because that's the default.