gcloud 函数调用抛出无效 JSON 错误

gcloud functions call throwing invalid JSON error

我正在学习有关如何设置本地 gcloud 函数环境的 this 教程。我设置并部署了这个脚本:

exports.helloGET = (req, res) => {
    console.log(req.body);
    
    // Example input: {“name”: “Junior”}
    if (req.body.name === undefined) { 
      // This is an error case, as “name” is required.
      res.status(400).send('No name defined!');
    } else {
      console.log(req.body.name);
      res.status(200).send('Hello ' + req.body.name);
    }
};

我尝试在 Cloud GUI(网站)上测试此功能,当您使用 {"name": "Junior"} 测试时它可以正常工作。它 returns Hello Junior 符合预期。

我现在希望能够从命令行在本地运行测试,所以参考docs,他们给出了例子:

gcloud functions call helloWorld --data='{"message": "Hello World!"}'

但是,当我尝试 运行 以下内容时:

gcloud functions call helloGET --data='{"name": "Junior"}' --region=northamerica-northeast1

我不断得到

ERROR: (gcloud.functions.call) Invalid value for [--data]: Is not a valid JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

为什么会这样?我正在做文档和教程正在做的事情。

我无法重现您的问题(Linux)。

我想知道你是否:

  • 使用非Linux OS 并且这不兼容
  • 无意中包含了非标准 '"

已部署:

gcloud functions deploy hello \
--entry-point=hello \
--runtime=nodejs12 \
--trigger-http \
--allow-unauthenticated \
--region=${REGION} \
--project=${PROJECT}

然后:

gcloud functions call hello \
--data='{"name":"Freddie"}' \
--region=${REGION} \
--project=${PROJECT}
executionId: 7igxh5sfvjvk
result: Hello Freddie

并且:

gcloud functions call hello \
--data='{"name":"Freddie"}' \
--region=${REGION} \
--project=${PROJECT} \
--log-http
=======================
==== request start ====
uri: https://cloudfunctions.googleapis.com/v1/projects/.../functions/hello:call?alt=json
method: POST
== headers start ==
b'Authorization': --- Token Redacted ---
b'accept': b'application/json'
b'accept-encoding': b'gzip, deflate'
b'content-length': b'34'
b'content-type': b'application/json'
== headers end ==
== body start ==
{"data": "{\"name\":\"Freddie\"}"}
== body end ==
==== request end ====
---- response start ----
status: 200
-- headers start --
...
-- body start --
{
  "executionId": "7igx3sfj3ate",
  "result": "Hello Freddie"
}

-- body end --
total round trip time (request+response): 0.289 secs
---- response end ----
----------------------
executionId: 7igx3sfj3ate
result: Hello Freddie

NOTE curl encodes the value of data as "{\"name\":\"Freddie\"}

并且:

ENDPOINT=$(\
  gcloud functions describe hello \
  --project=${PROJECT} \
  --format="value(httpsTrigger.url)")

TOKEN=$(gcloud auth print-access-token)

curl \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Bearer ${TOKEN}" \
--data '{"name":"Freddie"}' \
${ENDPOINT}
Hello Freddie