首页 > 解决方案 > 单击提交按钮后,如何通过快速节点在当前窗口中的框中获取结果?

问题描述

当我单击提交按钮时,我无法通过 node 和 express 获得响应。我对节点和表达相当陌生。这是我尝试过的。你能告诉我我的代码有什么问题吗?请指导我如何在当前 html 的框中获得即时响应,或者有什么其他方式来获得响应而不是异步功能?

<p class="borderBox"></p>

标签: javascripthtmlexpress

解决方案


没有看到你所有的代码就很难说。但我认为第一个问题是你没有足够防御性地检查你的 req.headers kvps。某些标头并不总是出现在请求中,因此您需要提供它们未按预期到达的情况

     if (req['x-forwarded-for']) {
         var ip = req['x-forwarded-for'].split(',')

或者

     req['x-forwarded-for'] = req['x-forwarded-for'] || ''

更新

根据您提供的代码判断,首先对您的 server.js 代码进行以下更改:

app.get('/headers', function(req, res) {
    if (req.headers['x-forwarded-for'])
        var ip = req.headers["x-forwarded-for"].split(',')[0];
    if (req.headers['accept-language'])
        var lang  = req.headers['accept-language'].split(',')
    if (req.headers['user-agent'])
        var sys = req.headers['user-agent'].match(/\((.+?)\)/)[1]


    var obj = {
        "IP Address": ip,
        "Language" : lang,
        "Operating System": sys
    }

    // res.json(obj);
    res.set('Content-Type', 'application/json');
    res.status(200).send(obj);
});

然后,您必须更改您调用的 URI,fetch()以便它到达您在上面指定的端点app.get()(即“/headers”)。我在端口 3000 上使用 localhost。

$("#submit").submit(async function(event) {
    event.preventDefault();
    // const response = await fetch(window.location.href);
    const response = await fetch('http://localhost:3000/headers');
    const data = await response.json();
    document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
});

最后,我对您的项目设置了解不多,但这是我通过使用 express 提供 index.html 文件的方法

app.use(express.static(path.join(__dirname, 'public')));

并放置在以 express 应用程序的根目录index.html命名的目录中。/public该文件index.html如下:

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<p>
    Please click to get the IP address, language, and operating system for your 
device.
</p>

<form id="submit">
    <button type="submit">Submit</button>
</form>


<p class="borderBox">    </p>

<script>
    $("#submit").submit(async function(event) {
        event.preventDefault();
        // const response = await fetch(window.location.href);
        const response = await fetch('http://localhost:3000/headers');
        const data = await response.json();
        document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
    });
</script>

我只包括最后一部分,因为我看不出你是如何设置项目的——但这对我有用。


推荐阅读