javascript - 单击提交按钮后,如何通过快速节点在当前窗口的框中获取结果?

标签 javascript html express

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

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

最佳答案

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

     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);
});

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

$("#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')));

并将 index.html 放在 express 应用程序根目录下名为 /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>

我只包括最后一部分,因为我再次看不到您是如何设置项目的 - 但这对我有用。

关于javascript - 单击提交按钮后,如何通过快速节点在当前窗口的框中获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53284821/

相关文章:

javascript - 子数组的最大值

javascript - relayjs:使用中继进行身份验证,使用哪个突变?

node.js - ERR_HTTP_HEADERS_SENT : Cannot set headers after they are sent to the client

javascript - Node js paypal rest sdk 401错误

node.js - 连接表的 REST uri 命名约定

javascript - 使用 WebAudio 制作字节节拍

javascript - 我正在尝试使用输入表创建一个表单

javascript - Google 没有正确缓存我的 AJAX 可抓取应用程序?

Javascript 设置浏览器窗口大小

javascript - 移动导航菜单无法正常工作