继续我以前的post,我遇到了另一个问题:我试图插入一个数组(包含GET,POST等)作为http方法属性的值,循环遍历它,然后测试几个要求。但是对于数组,我得到了带有501错误的5个元素(请求方法)。我已经尝试了几种解决方案,包括针对阵列的特定位置,但不能正常工作......任何帮助都会有所帮助。代码:
var http = require('http');
const options = {
hostname: 'www.google.com',
protocol: 'http:',
method: ['GET', 'POST', 'DELETE', 'PUT', 'STARDUST']
}
var callback = function (response) {
var exportJson = JSON.stringify(response.headers);
var arrayData = [];
response.on('data', function (data) {
arrayData += data;
});
response.on('end', function () {
console.log('THE DATA IS ' + arrayData);
});
}
var x;
var req;
function test() {
x = options.method;
console.log(x[0]); //This works, I can read the GET
for (var i = 0; i < x.length; i++) {
req = http.request(x, callback);
//req.x[0]; The console says that doesn't know the 0 property...
req.x;
req.end();
}
}
test();
编辑:控制台错误:
<h2>HTTP Error 500.19 - Internal Server Error</h2>
<h3>The requested page cannot be accessed because the related configuration da
ta for the page is invalid.</h3>
答案 0 :(得分:1)
这里有一个错误:
x = options.method;
console.log(x[0]); //This works, I can read the GET
for (var i = 0; i < x.length; i++) {
req = http.request(x, callback);
//req.x[0]; The console says that doesn't know the 0 property...
req.x;
req.end();
}
x是一个数组,您尝试将数组作为参数传递给request
方法,但文档声明它必须是键值对对象或字符串。
然后你试图获得不存在的req字段x,因此是例外。
https://nodejs.org/api/http.html#http_http_request_options_callback