2017-03-14 217 views
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(); 
    });   
} 

回答

2

如果你去http://localhost:8080/notify你會看到頁面加載不斷永遠沒有真正的負載。

這是因爲有沒有迴應您的要求。在你的應用程序中,隨後的請求會花費太長時間,因爲之前的請求還沒有響應。

嘗試增加這個給你/通知GET處理程序的console.log後:

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

完美!非常感謝! –

相關問題