2016-01-27 75 views
1

我是一個新手與node.js,我想輸出一些數據到HTML。 當我使用console.log時,我的代碼有效,但當我使用response.end時沒有。 當我使用我到Response.End只記錄看,而當我使用的console.log我能看到的所有記錄爲什麼console.log輸出所有記錄,而不是response.end - Node.js

見我下面全碼:

var http = require('http'); 
var formOutput; 
var WooCommerceAPI = require('woocommerce-api'); 

// Initialize the WooCommerceAPI class 
var WooCommerce = new WooCommerceAPI({ 
    //url: 'http://example.com', // Your store url (required) 
}); 

function handleRequest(response) { 
    // GET example 
    WooCommerce.get('products', function (err, data, res) { 
     //console.log(res); 

     //var fs = require('fs'); 
     //var jsonContent = JSON.parse(JSON.stringify(res, null, 4)) 
     var jsonContent = JSON.parse(res) 

     for (var i = 0; i < jsonContent["products"].length; i++) { 
      var name = jsonContent["products"][i]; 
      // this works well and I can output all records 
      //console.log(name['title']); 
      //console.log(name['id']); 
      //console.log(name['sku']); 
      //console.log(name['regular_price']); 
      //response.writeHead(200, { 'Content-Type': 'text/html' }); 
      //res.end(name['id']); 
      formOutput = name['regular_price']; 
      //formOutput = '<h1>XYZ Repository Commit Monitor</h1>'; 
      //response.write(); 
      //Only get one record 
      response.end(formOutput); 
      //response.write('<html><head></head><body>'); 
      //response.end("test"); 
      //response.end('</body></html>'); 
     } 
    }); 
     //response.end(formOutput); 
    } 


http.createServer(function (req, response) { 
    if (response.url === '/favicon.ico') { 
     response.writeHead(404); 
     response.end(); 
    } else { 
     response.writeHead(200, { 'Content-Type': 'text/html' }); 
    } 

    //code here... 
    handleRequest(response); 
    // response.end(formOutput); 

}).listen(1337, "localhost"); 
console.log("Server running at http://localhost:1337/"); 

回答

1

隨着快遞,響應。 結束()在一次呼叫後關閉通信信道,因此只有一個元素將被髮送給用戶。不要使用end()發送數據,在你的情況下,使用response.json()(或send())ONCE建立數據數組後。

var dataToSend = []; 
for (var i = 0; i < jsonContent["products"].length; i++) { 
    // build an array of data to send here 

} 

response.json(dataToSend); 

在一個側面說明,除非你想明確地結束通信不使用response.end()。當需要時,response.json()response.send()已經關閉該通道。

+0

感謝杉杉當我使用response.json和response.send我得到錯誤「response.json是不是一個函數」 這是用來磨片使用這我不使用 – naijacoder

+0

我假設你使用快遞express.js 。對於'http'模塊,你可以使用'response.write',你必須調用'end()'(一次)來關閉連接。 – Shanoor

+0

感謝解決它 – naijacoder

相關問題