Web 操作 returns 正文为空的 HTTP 200 响应

Web Action returns HTTP 200 response with empty body

从 CLI 创建 OpenWhisk Web 操作后,通过 public Web 操作调用该操作 URL 总是 return 一个空的响应主体。 HTTP 状态代码 returned (200) 表示调用成功。

无论函数的 return 值如何,空响应正文中都不包含任何内容。

const fs = require('fs')
const execFile = require('child_process').execFile

function hello(params) {
  return new Promise((resolve, reject) => {
    fs.writeFileSync('test.js', params.code)
    const child = execFile('node', ['test.js'], (error, stdout, stderr) => {
      if (error) {
        console.error('stderr', stderr)
        reject({ payload: error })
      }

      console.log('stdout', stdout)
      resolve({ payload: stdout })
    })
  })

}

exports.hello = hello

操作是使用以下命令创建的。

wsk action create test test.js

使用 public HTTP API return 以下响应调用操作。

$ http get "https://openwhisk.ng.bluemix.net/api/v1/web/NAMESPACE/default/test"
HTTP/1.1 200 OK
Connection: Keep-Alive
Date: Thu, 22 Jun 2017 12:39:01 GMT
Server: nginx/1.11.13
Set-Cookie: DPJSESSIONID=PBC5YS:-2098699314; Path=/; Domain=.whisk.ng.bluemix.net
Transfer-Encoding: chunked
X-Backside-Transport: OK OK
X-Global-Transaction-ID: 1659837265

无论 return 从函数中输入什么值,JSON 响应正文中永远不会有任何内容。

Web Actions use the body parameter 设置响应正文的内容。如果函数返回的对象中缺少此值,则响应正文将为空。

修改您的代码以使用此参数将解决该问题。

const fs = require('fs')
const execFile = require('child_process').execFile

function hello(params) {
  return new Promise((resolve, reject) => {
    fs.writeFileSync('test.js', params.code)
    const child = execFile('node', ['test.js'], (error, stdout, stderr) => {
      if (error) {
        console.error('stderr', stderr)
        reject({ body: error })
      }

      console.log('stdout', stdout)
      resolve({ body: stdout })
    })
  })

}

exports.hello = hello