0
我正在爲這個非常簡單的應用程序運行Node.js,Handlebars和Express。該頁面包含一個單擊按鈕,單擊該按鈕時會觸發一個異步GET請求,該請求應該會顯示一條console.log
消息。當我點擊提交按鈕時,第一個console.log
馬上彈出,但隨後的印刷需要很長時間(如分鐘)。這只是異步GET請求的性質,還是我做錯了什麼?簡單的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();
});
}
完美!非常感謝! –