HTTP Triggering Cloud Function with Cloud Scheduler

后端 未结 3 2019
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 18:42

I have a problem with a job in the Cloud Scheduler for my cloud function. I created the job with next parameters:

Target: HTTP

URL

3条回答
  •  广开言路
    2021-02-13 19:06


    Disclaimer: I have tried to solve the same issue using NodeJS and I'm able to get a solution


    I understand that this is an old question. But I felt like its worth to answer this question as I have spent almost 2 hours figuring out the answer for this issue.

    Scenario - 1: Trigger the Cloud Function via Cloud Scheduler

    • Function fails to read the message in request body.

    Scenario - 2: Trigger the Cloud Function via Test tab in Cloud Function interface

    • Function call always executes fine with no errors.

    What did I find?

    • When the GCF routine is executed via Cloud Scheduler, it sends the header content-type as application/octet-stream. This makes express js unable to parse the data in request body when Cloud scheduler POSTs the data.
    • But when the exact same request body is used to test the function via the Cloud Function interface, everything works fine because the Testing feature on the interface sends the header content-type as application/json and express js is able to read the request body and parses the data as a JSON object.

    Solution

    I had to manually parse the request body as JSON (explicitly using if condition based on the content-type header) to get hold of data in the request body.

    /**
     * Responds to any HTTP request.
     *
     * @param {!express:Request} req HTTP request context.
     * @param {!express:Response} res HTTP response context.
     */
    exports.helloWorld = (req, res) => {
      let message = req.query.message || req.body.message || 'Hello World!';
    
      console.log('Headers from request: ' + JSON.stringify(req.headers));
    
      let parsedBody;
    
      if(req.header('content-type') === 'application/json') {
        console.log('request header content-type is application/json and auto parsing the req body as json');
        parsedBody = req.body; 
      } else {
        console.log('request header content-type is NOT application/json and MANUALLY parsing the req body as json');
        parsedBody = JSON.parse(req.body);
      }
    
      console.log('Message from parsed json body is:' + parsedBody.message);
    
      res.status(200).send(message);
    };
    
    

    It is truly a feature issue which Google has to address and hopefully Google fixes it soon.

    Cloud Scheduler - Content Type header issue

提交回复
热议问题