如何在不刷新页面的情况下发出向PostJS发送/获取请求的请求

时间:2018-07-30 14:53:15

标签: javascript node.js ajax express

我想在单击按钮后运行NodeJS函数,我很难理解这一点。我已经尝试过Ajax请求,但似乎无法使用Ajax运行NodeJS函数。

此bash脚本生成一个JSON文件,我将需要解析该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)")]

这是我的middleware / 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

1 个答案:

答案 0 :(得分:0)

在客户端上运行的代码无法直接运行在服务器上运行的功能

Ajax是正确的方法。您需要对URL发出HTTP请求。

该URL需要使用Express路由提供。该路由可以调用您的函数。

相关问题