Search code examples
google-cloud-platformgoogle-cloud-rungoogle-cloud-tasks

Unable to get content-type or body from Cloud Tasks HTTP request


I am creating an HTTP task that is triggering an endpoint on a Cloud Run service. The handler is being called from the queue, but I am unable to get the payload.

I have tried to log the headers, but it doesn't seem to contain content-type and I suspect that is why the app.use(bodyParser.raw({ type: "application/octet-stream" })); is failing.

These are all the request headers I'm receiving according to my Express handler:

{
  "host": "my_service.a.run.app",
  "x-cloudtasks-queuename": "notifications",
  "x-cloudtasks-taskname": "36568403927752792701",
  "x-cloudtasks-taskretrycount": "0",
  "x-cloudtasks-taskexecutioncount": "0",
  "x-cloudtasks-tasketa": "1640337087",
  "authorization": "Bearer some_token",
  "content-length": "193",
  "user-agent": "Google-Cloud-Tasks",
  "x-cloud-trace-context": "496573f34310f292ade89f566e7c8f40/11132544205299294705;o=1",
  "traceparent": "00-496573f34310f292ade89f566e7c8f40-9a7ebdf8d332a1f1-01",
  "x-forwarded-for": "35.187.132.21",
  "x-forwarded-proto": "https",
  "forwarded": "for=\"35.187.132.21\";proto=https",
  "accept-encoding": "gzip, deflate, br"
}

This is currently what the handler looks like:

app.post("/send-notification", (req, res) => {
  console.log(`req.headers: ${JSON.stringify(req.headers)}`);
  console.log(`req.body: ${JSON.stringify(req.body)}`);
});

For body it prints {} but there should be a payload. I create it like this:

const task = {
    httpRequest: {
      httpMethod: "POST" as const,
      url: def.url,
      oidcToken: {
        serviceAccountEmail,
      },
      body: Buffer.from(JSON.stringify(payload)).toString("base64"),
    },
    scheduleTime: {
      seconds: 3 + Date.now() / 1000,
    },
  };

I have run out of ideas for things to try. What am I missing?


Solution

  • According to that example in the documentation, it's possible to add header to the request performed to Cloud Task.

    You can add the content type in the header

    const task = {
        httpRequest: {
          httpMethod: "POST" as const,
          url: def.url,
          headers: {
               "Content-type": "application/json"
          },
          oidcToken: {
            serviceAccountEmail,
          },
          body: Buffer.from(JSON.stringify(payload)).toString("base64"),
        },
        scheduleTime: {
          seconds: 3 + Date.now() / 1000,
        },
      }