2017-04-18 31 views
0

我想運行一個網頁,將數據發佈到網絡端點〜每秒鐘。通過下面的NodeJS和瀏覽器JS,它似乎能夠在前6個請求中正常工作和同步。在前6個請求後,我可以看到從瀏覽器發出的提交內容很長一段時間沒有記錄到Node中。最終我的瀏覽器會報告一些「net :: ERR_EMPTY_RESPONSE」錯誤。使用setInterval循環在網頁上使用JavaScript在網頁上發佈到節點端點

端點的NodeJS代碼:從網頁

var express = require('express') 
 
var bodyParser = require("body-parser"); 
 
var cors = require('cors'); 
 
var app = express() 
 

 
app.listen(3000, function() { 
 
    console.log('listening on port 3000') 
 
}) 
 

 
app.use(cors({origin: '*'})); 
 

 
app.get('/', function (req, res) { 
 
    res.send('Hello World!') 
 
}) 
 

 
app.use(bodyParser.urlencoded({ extended: false })); 
 
app.use(bodyParser.json()); 
 
app.post('/',function(request,response){ 
 
    console.log(request.body); 
 
});

testPost.JS:

var num = 0; 
 
var theDate; 
 
var theTime; 
 

 
setInterval(function() { 
 
    theDate = new Date(); 
 
    theTime = theDate.toLocaleTimeString(); 
 
    num++ 
 
    send({Time: theTime, Num : num}); 
 
}, 10000); 
 

 
function send(theData) { 
 
    console.log('Send Function Start: ' + JSON.stringify(theData)) 
 
    $.ajax({ 
 
     url: 'http://localhost:3000', 
 
     dataType: 'json', 
 
     type: 'post', 
 
     contentType: 'application/json', 
 
     data: JSON.stringify(theData), 
 
     processData: false, 
 
     success: function (data, textStatus, jQxhr) { 
 
      console.log('success: ' + JSON.stringify(data)); 
 
     }, 
 
     error: function (jqXhr, textStatus, errorThrown) { 
 
      console.log(errorThrown); 
 
     } 
 
    }); 
 
}

的網頁:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
 
    <script src="testPost.js"></script> 
 
    <meta charset="UTF-8"> 
 
    <title>Title</title> 
 
</head> 
 
<body> 
 

 
</body> 
 
</html>

回答

1

的問題是:

app.post('/',function(request,response){ 
    console.log(request.body); 
}); 

這將創建一個懸而未決的要求是不會結束的,因爲你不叫response.sendresponse.end

經過一段時間瀏覽器將超時待處理的請求,並且您將收到錯誤。

+0

感謝您的建議!我添加了response.end,但它根本沒有改變響應。 app.post('/',function(request,response){console.log(request.body); response.end; }); – Ken

+0

@Ken你必須**調用''end'函數,只是寫'response.end;'什麼也不做。 ([express:res.end](http://expressjs.com/de/api.html#res.end)) –

+0

謝謝。更新如下,似乎運作良好。 app.post('/',function(request,response){ console.log(request.body); response.json({'status':'ok'}); response.end(); } ); – Ken