最近开始了解nodeJS。做了如下的一个功能:
使用nodeJS开启一个服务,然后调用XXX后台接口的数据,返回的数据格式如下,然后以表格的形式在页面中展示出来。
代码如下:
var http = require('http');
var request = require('request');
function handleData(arr){
var content = '';
for (var i = 0; i < arr.length; i++){
content += '<tr><td>' + arr[i].id + '</td><td>' + arr[i].productLine + '</td><td>' + arr[i].demand + '</td><td>' + arr[i].feBug + '</td><td>' + arr[i].bsBug + '</td><td>' + arr[i].bug + '</td><td>' + arr[i].feCode + '</td><td>' + arr[i].bsCode + '</td><td>' + arr[i].feCount + '</td><td>' + arr[i].bsCount + '</td><td>' + arr[i].productScore + '</td><td>' + arr[i].compressibility + '</td><td>' + arr[i].bsCompressibility + '</td><td>' + arr[i].feSubmit + '</td></tr>'
}
var htm = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><table style="border-width: 1px;border-color: #666666;border-collapse: collapse;" ><tr><th>id</th><th>productLine</th><th>demand</th><th>feBug</th><th>bsBug</th><th>bug</th><th>feCode</th><th>bsCode</th><th>feCount</th><th>bsCount</th><th>productScore</th><th>compressibility</th><th>bsCompressibility</th><th>feSubmit</th></tr>' + content + '</table></body></html>';
return htm;
}
var getJSON = function(url) {
var promise = new Promise(function(resolve, reject){
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
}
});
});
return promise;
};
http.createServer(function (request, response) {
var str = '11' ;
response.writeHead(200, {'Content-Type': 'text/html;charset:utf-8'});
getJSON("http://XXX:8006/api/status").then(function(body) {
str = handleData(JSON.parse(body).data.status);
response.write(str);
response.end();
});
}).listen(8080);