大家好我正在尝试使用SubDb api。此API需要设置一些用户代理标头才能工作。
文档:
我尝试以这种方式设置标头:
var request = new XMLHttpRequest();
request.open('GET', 'http://api.thesubdb.com/?action=search&hash=edc1981d6459c6111fe36205b4aff6c2');
request.setRequestHeader('User-Agent','SubDB/1.0 (testapp/0.0.1; https://github.com/maantje)');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
obj = JSON.parse(this.responseText);
console.log(obj);
}
};
request.send();
但我拒绝设置不安全的标题" User-Agent"'并且像文档说我得到了412,因为它拒绝设置标题。 GET http://api.thesubdb.com/?action=search&hash=edc1981d6459c6111fe36205b4aff6c2 412(先决条件失败)
如何正确设置标题?
以下是工作代码:
var http = require('http');
var options = {
hostname: 'api.thesubdb.com',
path: '/?action=search&hash=edc1981d6459c6111fe36205b4aff6c2',
method: 'GET',
headers: {
'Content-length':0,
'User-Agent': 'SubDB/1.0 (testapp/0.0.1; https://github.com/maantje)'
}
};
var req = http.get(options, function(res) {
//console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
obj = JSON.parse(body);
console.log(obj);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
答案 0 :(得分:0)
XMLHttpRequest不允许您设置User-Agent标头,因为它是forbidden headers之一。
为了能够使用SubDb api,您可以编写自己的脚本来发送请求。然后,脚本将正确的标头发送到SubDb api,然后将响应传递给客户端。