我想运行一个网页,每秒将数据发布到 Web 端点。使用下面的 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>
最佳答案
问题是:
app.post('/',function(request,response){
console.log(request.body);
});
这会创建一个无法完成的待处理请求,因为您没有调用 response.send
或 response.end
。
经过一定时间后,浏览器将使待处理的请求超时,并且您将收到错误消息。
关于javascript - 使用 setInterval 循环从网页上的 JavaScript 发布到 Node 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43477740/