我想运行一个网页,每秒都会将数据发布到网络端点。使用下面的NodeJS和浏览器JS,它似乎可以很好地同步前6个请求。在前6个请求之后,我可以看到从浏览器发生的提交已经很长时间没有登录Node。最终我的浏览器会报告一些“net :: ERR_EMPTY_RESPONSE”错误。
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>
答案 0 :(得分:1)
问题是:
app.post('/',function(request,response){
console.log(request.body);
});
这会创建一个无法完成的待处理请求,因为您不会调用response.send
或response.end
。
在一段时间后,浏览器将超时待处理的请求,您将收到错误。