Firebase REST API POST request fails with error: "Invalid data; couldn't parse JSON object, array, or value..."

Firebase REST API POST request fails with error: "Invalid data; couldn't parse JSON object, array, or value..."

我正在尝试使用 Firebase REST API 将内容保存到我的数据存储中。我尝试使用 jQuery 和 vanilla JS XHR。但是,两者都给出相同的错误。 403 错误请求和此响应:

Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names.

这是我的示例 JSON,我正在尝试保存:

{
    "date": "2pm", 
    "name": "John"
}

这里是例子ajax请求:

jQuery.ajax({
    accept: "application/json",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "https://something.firebaseio.com/endpointnode.json",
    data: {
        "name": "John", 
        "date": "2pm"        
    },
});

请求的响应:

{
    "error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."
}

如您所见,没有特殊字符或任何东西。它应该可以正常工作。

它适用于 CURL 和 Httpie。我试图检查 Httpie 中的 -v 选项以获取详细信息。我像 Httpie 一样放置了所有 headers。没有任何帮助。 顺便说一句,我的环境是可写的,所以应该不会有任何权限问题。

知道如何实现吗?

谢谢。

您已通过分配 contentType 属性 指定您的 AJAX 请求包含 json 字符串。但是,附加到请求的参数不是 JSON 字符串。为了使数据成为 json 字符串,只需调用 JSON.stringify(params) 方法。

以下代码片段可以帮助您解决问题。

var data = {"name": "John", "date": "2pm"};
jQuery.ajax({
    accept: "application/json",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "https://something.firebaseio.com/endpointnode.json",
    data: JSON.stringify(data),
});

干杯。

您的数据需要是字符串,使用JSON.stringify将您的对象转换为字符串:

data: JSON.stringify({"name": "John", "date": "2pm"})

如果您想将值存储为 JSON 而不是字符串,请检查您的密钥。正如错误消息所说 "Perhaps you're using invalid characters in your key names." 键中不允许使用像 (/.\,) 这样的字符。