首页 > 解决方案 > Google Cloud HTTP 函数 - 为什么函数对 cURL json 格式如此挑剔

问题描述

我可以使用一些帮助来理解为什么我的 Google Cloud Function 对我在 JSON 中传递的格式如此挑剔。

我正在关注Google Cloud的本指南。页面上的第一个示例让您创建一个完全像这样的函数:

exports.helloHttp = (req, res) => {
  res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
};

然后他们要求您通过 curl 触发它:

curl -X POST HTTP_TRIGGER_ENDPOINT -H "Content-Type:application/json"  -d '{"name":"Jane"}'

令我惊讶的是,我无法让它工作,我花了很多时间玩参数和选项,直到这对我有用:

curl -X POST HTTP_TRIGGER_ENDPOINT -H "Content-Type:application/json"  -d {\"name\":\"Jane\"}

我正在使用 Windows 10 机器和安装了 node(10) 的终端(以防万一)。

1.是什么让我需要删除单引号并添加反斜杠,这种格式有名称或关键字吗?

2.问题 1 的答案可以用在 vanilla javascript XMLHttpRequest 中吗?因为我无法成功应用我的 curl 修改。

var xhr = new XMLHttpRequest();
xhr.open("POST", "myFunctionURL");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(`{\"name\":\"Jane"}`);
xhr.onreadystatechange = function () {
 if (xhr.readyState === 4) {
   console.log('response: ', JSON.stringify(xhr), ' status: ', xhr.status);
 }
}

我尝试将许多参数传递给发送,包括:

var body = {};
body.name = 'Jane';
*passing body into xhr.send*

var body = `{\"name\",\"Jane\"};
*passing body into xhr.send*

标签: jsonhttpcurlgoogle-cloud-platformxmlhttprequest

解决方案


这不是谷歌云功能,它是 CURL 命令的 Windows 版本,它在发布 JSON 有效负载时存在单引号问题。

看看以下似乎讨论相同问题但在不同上下文中的线程:

https://superuser.com/questions/1016710/how-to-make-a-curl-post-call-in-windows https://superuser.com/questions/1291352/curl-command-runs-in-linux -但不是 Windows-2008


推荐阅读