【发布时间】: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">
main.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