安全浏览 API 返回'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()文档中查找form属性,您将看到以下内容:

form -

当传递对象或查询字符串时,这会将 body 设置为值的查询字符串表示形式,并添加 Content-type: application/x-www-form-urlencoded 标头。如果未传递任何选项,则返回 FormData 实例(并通过管道传递到请求(。请参阅上面的"表单"部分。

当您查看 Google 安全浏览 API 时,您会看到以下内容:

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

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

最新更新