Ajax请求运行运行bash脚本的NodeJS函数



这个bash脚本制作了一个JSON文件,我需要解析该文件,并将数据发送到客户端java脚本以显示它。我试图在不刷新页面的情况下完成这项工作,我也不想使用jquery。我试过Axios,但可能不明白。

这是我的Ajax请求,我无法用它访问NodeJs函数,也无法加载文件,因为即使这是一个直接路径。如果我能运行这个函数,我想这会起作用。

我已经做了一个星期了,我只是不理解这些AJAX请求。如果你能帮忙,请做一个深入的解释。

function digIt() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('mapSection').innerHTML = xhr.responseText;
} else {
alert(xhr.statusText);
}
};
xhr.open('GET', "./../../middleware/index.js", true);
console.log("done");
canYouDigIt(domain);
xhr.send();
};

这是我的HTML,这是用Jade/Pug写的。

section(id="digToolWrapper")
form(id="digToolInput")
ul
li #[input(id="digTool" name="domain" type="text" placeholder="Can you dig it?")]#[input(id="whois" value="whois" type="button" onclick="digIt(domain)")]

这是我的中间件/index.js文件。

const shell = require('shelljs');

function loggedOut(req, res, next) {
if (req.session && req.session.userId) {
return res.redirect('/profile');
}
return next();
}
function checkForbidden(req, res, next) {
if(! req.session.userId) {
var err = new Error("You are not authorized to view this page.");
err.status = 403
return next(err);
}
return next();
}

// Whois Bash Script!!!
function canYouDigIt(domain) {
shell.env["domain"] = domain;
shell.exec(digIt.sh)
console.log("here")
};

module.exports.canYouDigIt = canYouDigIt;
module.exports.checkForbidden = checkForbidden;
module.exports.loggedOut = loggedOut;

这是我试图运行的脚本,以供参考,以了解我试图做什么

domain=google.com
aRecord=$(dig -t a +short $domain)
ipWhois=$(whois $aRecord | awk '/NetRange/,0'| cut -d# -f 1)
server=$(host $aRecord)
mxRecord=$(dig -t mx +short $domain)
nsRecord=$(dig -t ns +short $domain)
txtRecord=$(dig -t txt +short $domain)
ptrRecord=$(dig -x ptr +short $aRecord)
whoisRecord=$(whois $domain | awk '/Domain Status|Registrant Organization|Registry Expiry Date|Registration Expiration Date|Registrar:/')

serverType=$(curl -iA . -s $domain | awk  '/Server:/ {print $2}')
echo -e "{n
t "domain" :n"$domain",n
t "aRecord" :n"$aRecord",n
t "ipWhois" :n"$ipWhois",n
t "server" :n"$server",n
t "mxRecord" :n"$mxRecord",n
t "nsRecord" :n"$nsRecord",n
t "txtRecord" :n"$txtRecord",n
t "ptrRecord" :n"$ptrRecord",n
t "whoisRecord" :n"$whoisRecord",n
}" > ./whoisJson/whois$domain.json

由于您正在尝试使用Ajax,我假设您打算在服务器上运行此脚本,并将输出传递到客户端以进行显示?如果是这样,基本的误解是,您必须在服务器端实际设置一个web服务器(使用node?(,它可以从客户端接收GET请求,调用脚本,收集其输出,并将其发送到客户端。Ajax"只是"允许您将请求打包到服务器,以便为您完成这项工作,并将答案提供给您。

OTOH,您的代码看起来像是在尝试将Javascript下载到客户端,然后在客户端执行canYouDIgIt((。Ajax不是这样工作的(您不能只在客户端调用一个在服务器上神奇运行的方法,而不是在没有大量管道的情况下(。

最新更新