1

所以,我正在尝试将任务发送到谷歌云任务队列,但是当它到达那里时,它变得未定义。这是我的代码的快照。我究竟做错了什么?

我正在使用 node.js 和框架 Adonis.js 来做这件事。有效负载包含一个带有用户信息的对象。类似:{ first_name: 'Bla', last_name: 'Bla bla', email: 'bla@bla.com'} 等等。我已经完成了以前真正有效的任务,但我找不到那个错误......所以,这是我的代码片段:

这是我创建任务的地方:

const payload = { users }
    const http = {
      method: 'PUT',
      endpoint: '/api/task/users',
      headers: {
        Authorization: request.header('Authorization')
      }
    }

    const task = new Task('users', http, payload)

    try {
      await task.createTask()
    } catch (e) {
      console.log(e)
      return response.status(500).send({ message: 'Users task: Internal Error!' })
    }

这是我的任务类(顺便说一句,我这样做就像 Cloud Tasks 文档一样):

constructor (queue, http, payload = undefined, seconds = undefined) {
    const project = Config.get('google.projectId')
    const location = Config.get('google.location')

    this._client = new cloudTasks.CloudTasksClient()
    console.log(project, location, queue)
    this._parent = this._client.queuePath(project, location, queue)
    this._payload = payload
    this._http = http
    this._seconds = seconds
  }

  async createTask() {
    const task = {
      appEngineHttpRequest: {
        httpMethod: this._http.method,
        relativeUri: this._http.endpoint,
        headers: this._http.headers
      },
    }

    if (this._payload !== undefined) {
      task.appEngineHttpRequest.body = Buffer.from(JSON.stringify(this._payload)).toString('base64')
    }

    if (this._seconds !== undefined) {
      task.scheduleTime = {
        seconds: this._seconds + Date.now() / 1000
      }
    }

    const request = {
      parent: this._parent,
      task: task
    }

    console.log(`Sending task: ${task}`)
    const [ res ] = await this._client.createTask(request)
    console.log(`Created task ${res.name}`)
  }

这是将接受任务的工人:

async users ({ request, response, domain }) {
    const { users } = request.only(['users'])

    for (const user of users) {
      try {
        let u = await User.findOrCreate({ email: user.email }, user)
        if (u.id) {
          u.merge(user)
          await u.save()
        } else {
          await u.test().associate(test)
        }
      } catch (e) {
        console.log(e)
        return response.status(500).send(`User Task Error: ${e}`)
      }
    }

在到达工人之前,我期待着与我描述的相同的对象,但我只能得到一个“未定义”的值。你们能帮帮我吗?谢谢!:D

4

1 回答 1

2

这可能是由于解析了传入的请求正文。默认情况下,Content-Type任务请求的标头设置为“application/octet-stream”(https://cloud.google.com/tasks/docs/reference/rest/v2beta3/projects.locations.queues.tasks#AppEngineHttpRequest) .

因此,您可能需要将解析器设置为适当的解析类型(https://github.com/googleapis/nodejs-tasks/blob/master/samples/server.js#L27)或手动设置Content-Type.

于 2019-06-17T18:19:45.770 回答