2017-05-16 127 views
0

繼續我之前的post,我遇到了另一個問題:我試圖插入一個數組(包含GET,POST等)作爲http方法屬性的值,循環它,以及測試幾個請求。但對於數組,我得到了5個元素(請求方法)和501錯誤。我已經嘗試了幾種解決方案,包括針對數組的特定位置,但不是它的工作原理......任何幫助都會有所幫助。代碼:循環訪問http方法數組

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

什麼是你真正想與循環呢?爲什麼在循環內部有'req.end();' –

回答

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,那不存在,因此是例外。

enter image description here

https://nodejs.org/api/http.html#http_http_request_options_callback