安全浏览 API returns 'Invalid JSON payload received'

Safebrowsing API returns 'Invalid JSON payload received'

我正在使用安全浏览 API 从我的数据库中检查一些 URL,但是请求给了我这样的结果:

data {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"threatInfo[threatTypes][0]\": Cannot bind query parameter. Field 'threatInfo[threatTypes][0]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"threatInfo[threatTypes][1]\": Cannot bind query parameter. Field 'threatInfo[threatTypes][1]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"threatInfo[platformTypes][0]\": Cannot bind query parameter. Field 'threatInfo[platformTypes][0]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"threatInfo[threatEntryTypes][0]\": Cannot bind query parameter. Field 'threatInfo[threatEntryTypes][0]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"threatInfo[threatEntries][0][url]\": Cannot bind query parameter. Field 'threatInfo[threatEntries][0][url]' could not be found in request message."
  }
} 

我正在尝试以下代码:

const request = require('request');
    const body = {
      threatInfo: {
        threatTypes: ["SOCIAL_ENGINEERING", "MALWARE"],
        platformTypes: ["ANY_PLATFORM"],
        threatEntryTypes: ["URL"],
        threatEntries: [{url: "http://www.urltocheck2.org/"}]
      }
    }

    const options = {
      headers: {
        "Content-Type": "application/json"
      },
      method: "POST",
      url: "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${API_KEY}",
      form: body
    }

    console.log(options);
    request(options,
        function(err, res, data) {
            console.log('data', data)
            if (!err && res.statusCode == 200) {
              console.log(data);
            }
        }
    )

我希望请求的输出是 {},在此示例中状态代码为 200。

如果您查看 request() doc for the form property,您会看到:

form - when passed an object or a querystring, this sets body to a querystring representation of value, and adds Content-type: application/x-www-form-urlencoded header. When passed no options, a FormData instance is returned (and is piped to request). See "Forms" section above.

当您查看 Google safe browsing API 时,您会看到:

POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY HTTP/1.1 Content-Type: application/json

您正在发送 Content-type: application/x-www-form-urlencoded,但 API 想要 Content-Type: application/json。您需要发送 JSON,而不是形成编码数据。

您可能只需将 form 属性 更改为 json 属性,方法是:

const options = {
  headers: {
    "Content-Type": "application/json"
  },
  method: "POST",
  url: "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${API_KEY}",
  form: body
}

对此:

const options = {
  method: "POST",
  url: "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${API_KEY}",
  json: body     // <=== change here
}

内容类型会自动设置为与生成的正文格式相匹配,因此您无需进行设置。