我正在使用安全浏览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。
答案 0 :(得分:1)
如果您查看request()
doc for the form
property,将会看到以下内容:
form-传递对象或查询字符串时,会将主体设置为值的查询字符串表示形式,并添加Content-type:application / x-www-form-urlencoded标头。如果不传递任何选项,则将返回FormData实例(并将其通过管道传递给请求)。请参阅上方的“表单”部分。
当您查看Google safe browsing 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
}
无论哪种方式,都会自动设置content-type以匹配生成的正文的格式,因此您无需进行设置。