}
function show(el){
el.style.display = 'block';
}
function dealResult(responseText){
var ips = [],
result = '';
ips = JSON.parse(responseText).ips;
if(Array.isArray(ips)){
result = ips.length > 0 ? ips.join('<br />') : '没有查询到结果';
}else if({}.toString.call(ips) === '[object Object]'){
result = JSON.stringify(ips);
}
res.innerHTML = result;
}
type.addEventListener('click',function(e){
e.stopPropagation();
show(list);
},!1);
[].slice.call(document.body.querySelectorAll('.item')).forEach(function(el,idx,arr){
el.addEventListener('click',function(e){
type.innerText = this.innerText;
type.dataset.value = this.dataset.value;
},!1);
});
document.body.addEventListener('click',function(e){
if(list.style.display === 'block'){ hide(list); }
},!1);
btn.addEventListener('click',function(e){
var hostname = host.value.trim(),
rrtype = type.dataset.value.toUpperCase();
if(hostname == '') return;
if(hostname.indexOf('http://') === 0) hostname = hostname.replace('http://','');
var xhr = new XMLHttpRequest(),
method = "POST",
url = "/dnslookup";
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
dealResult(xhr.responseText);
}
};
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send('host='+hostname+'&rrtype='+rrtype);
},!1);
</script>
</body>
</html>
接着编写服务端代码,如下:
var http = require('http'),
url = require('url'),
dns = require('dns'),
qs = require('querystring'),
fs = require('fs');function router(req,res,pathname){
switch(pathname){
case '/dnslookup':
lookup(req,res);
break;
default:
showIndex(req,res);
}
}
function showIndex(req,res){
var pagePath = __dirname+'/'+'dns-lookup.html';
var html = fs.readFileSync(pagePath);
res.end(html);
}
function lookup(req,res){
var postData = '';
req.on('data',function(data){
postData+=data;
});
req.on('end',function(data){
var json = qs.parse(postData);
var hostname = json.host;
var rrtype = json.rrtype;
dns.resolve(hostname,rrtype,function(err,adresses){
if(err){
res.end(JSON.stringify({errcode:1,ips:[]}));
}
res.end(JSON.stringify({errcode:0,ips:adresses}));
});









