【问题标题】:Simple GET request takes a lot of time to return简单的 GET 请求需要很长时间才能返回
【发布时间】:2017-03-14 15:36:58
【问题描述】:

我正在为这个非常简单的应用程序运行 Node.js、Handlebars 和 Express。该页面包含一个按钮,当单击该按钮时,会触发一个异步 GET 请求,该请求应显示 console.log 消息。当我点击提交按钮时,第一个console.log 会立即弹出,但随后的按下需要很长时间(比如几分钟)。这只是异步 GET 请求的本质,还是我做错了什么?

app.js

var express = require('express');
var app = express();
app.use(express.static('public'));
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 8080);

app.get('/',function(req,res,next){
    var context = {};
    res.render('home', context);
});

app.get('/notify',function(reg,res,next){
    console.log('I got a GET request!');
});

app.listen(app.get('port'), function(){
    console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});

home.handlebars

<input type="submit" id="Submit">

ma​​in.handlebars

<!doctype html>
<html>
<head>
    <title>Test Page</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="scripts/buttons.js" type="text/javascript"></script>
</head>
<body>
    {{{body}}}
</body>
</html>

buttons.js

document.addEventListener('DOMContentLoaded', bindButtons);
function bindButtons(){
    document.getElementById('Submit').addEventListener('click', function(event){
        var req = new XMLHttpRequest();
        req.open("GET", "http://localhost:8080/notify", true);
        req.send(null);
        event.preventDefault();
    });        
}

【问题讨论】:

    标签: javascript html node.js express asynchronous


    【解决方案1】:

    如果您转到http://localhost:8080/notify,您会看到页面一直在加载,并且从未真正加载过。

    这是因为您的请求没有响应。在您的应用中,后续请求花费的时间太长,因为之前的请求仍未得到响应。

    尝试在 console.log 之后添加 /notify GET 处理程序:

    res.send('This is a cool message from server');
    

    【讨论】:

    • 完美!非常感谢!
    猜你喜欢
    • 2016-11-07
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多