json - 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*
解决方案
这不是谷歌云功能,它是 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
推荐阅读
- scala - 如何创建涉及某些功能在范围内的“块”的 DSL?
- python - 在 Python3 上使用 Pandas 未对齐数据框
- r - Plot dates with regular interval in R
- python-3.x - 如何使用烧瓶获取图像上传到服务器的元数据。
- angular - 角度自定义控件 - 星级 - 来自输入的值
- jquery - Jquery根据选项更改div
- c++ - 缺少链表的测试用例
- angular - 我们如何在 Angular5 中的(单击)事件上添加两个函数
- android - android.view.InflateException:二进制 XML 文件行(不存在)
- php - php中的表单验证——错误和成功信息同时显示