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/");
感謝杉杉當我使用response.json和response.send我得到錯誤「response.json是不是一個函數」 這是用來磨片使用這我不使用 – naijacoder
我假設你使用快遞express.js 。對於'http'模塊,你可以使用'response.write',你必須調用'end()'(一次)來關閉連接。 – Shanoor
感謝解決它 – naijacoder