Node.js-将主体设置为Google云任务队列

时间:2019-01-16 07:03:27

标签: node.js google-app-engine google-cloud-platform task-queue google-tasks-api

我在Google App Engine中有一个nodejs服务器,我想在其中使用Google Cloud Task queue将长时间运行的任务委托给任务队列。

任务队列未传递请求主体,但到达了端点:

这是我将任务添加到任务队列的方式:

// Imports the Google Cloud Tasks library.
const cloudTasks = require('@google-cloud/tasks');

// Instantiates a client.
const client = new cloudTasks.CloudTasksClient();
const project = 'projectname';
const queue = 'queuename';
const location = 'us-central1';
const parent = client.queuePath(project, location, queue);

// Send create task request.
exports.sender = async function (options) {
// Construct the fully qualified queue name.
    let myMap = new Map();
    myMap.set("Content-Type", "application/json");
    const task = {
        appEngineHttpRequest: {
            httpMethod: 'POST',
            relativeUri: '/log_payload',
            headers: myMap,
            body: options/* Buffer.from(JSON.stringify(options)).toString('base64')*/
        },
    };
    
    /* if (options.payload !== undefined) {
         task.appEngineHttpRequest.body = Buffer.from(options.payload).toString(
           'base64'
         );
     }*/
    
    if (options.inSeconds !== undefined) {
        task.scheduleTime = {
            seconds: options.inSeconds + Date.now() / 1000,
        };
    }
    
    const request = {
        parent: parent,
        task: task,
    };
    client.createTask(request)
      .then(response => {
          const task = response[0].name;
          //console.log(`Created task ${task}`);
          return {'Response': String(response)}
      })
      .catch(err => {
          //console.error(`Error in createTask: ${err.message || err}`);
          return `Error in createTask: ${err.message || err}`;
      });
};

这是端点接收:

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: String(JSON.stringify(JSON.stringify(req.body)))
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});

当收到电子邮件时,两个正文都是一个空的Json对象。 我在做什么错了?

2 个答案:

答案 0 :(得分:2)

只是对@Joan Grau的回答的补充:

如果添加此过滤器,则可以确保正确解析结果:

var bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

(想法取自this post

尤其是,一个好的做法是将解析器仅应用于您需要的任何地方。此外,请考虑将内容作为 base64 字符串发送到正文(这对于云任务来说是必需的,以便正常工作)。用所有这些重写代码:

const task = {
        appEngineHttpRequest: {
            httpMethod: 'POST',
            relativeUri: '/log_payload',
            headers: myMap,
            body: Buffer.from(JSON.stringify(options)).toString('base64')
        },
    };

和端点:

var bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use('/log_payload', bodyParser.json({ verify: rawBodySaver }));
app.use('/log_payload', bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use('/log_payload', bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: req.body //no need to parse here!
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});

答案 1 :(得分:0)

this example的指导下,我认为从请求中解析正文的最佳方法是使用body-parser package

您可以通过更改接收端点文件来实现此目的,包括以下内容:

const bodyParser = require('body-parser');

app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.text());

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: req.body
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});