1

我正在使用安全浏览 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。

4

1 回答 1

1

如果您在request()文档中查找formproperty,您将看到:

form - 当传递一个对象或查询字符串时,这会将 body 设置为 value 的查询字符串表示,并添加 Content-type: application/x-www-form-urlencoded 标头。当不传递任何选项时,将返回一个 FormData 实例(并通过管道发送到请求)。请参阅上面的“表格”部分。

当您查看Google 安全浏览 API时,您会看到:

POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY HTTP/1.1 内容类型: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
}

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

于 2019-08-06T02:45:08.137 回答