javascript - 使用 setInterval 循环从网页上的 JavaScript 发布到 Node 端点

标签 javascript jquery node.js ajax

我想运行一个网页,每秒将数据发布到 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.sendresponse.end

经过一定时间后,浏览器将使待处理的请求超时,并且您将收到错误消息。

关于javascript - 使用 setInterval 循环从网页上的 JavaScript 发布到 Node 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43477740/

相关文章:

javascript chop 字符串而不包括标点符号或空格

javascript - 带有可关闭选项卡的 ExtJs Tabpanel 关闭事件

javascript - 数据表中的小数点四舍五入

javascript - 单击原始div时输出可滚动div,并自动滚动到div底部

javascript - 提交后,确认消息将粘贴在联系表单的底部

javascript - NODEJS 无法发送 json 格式的响应?

javascript - 如何在 Jquery 中搜索数组,如 SQL LIKE value% 语句

javascript - 如何访问有序列表的所有元素

node.js - 在 ubuntu 21.10 上的 nodejs 上安装特定版本

javascript - 快速应用程序中未捕获的语法错误