gpt4 book ai didi

php - 从 nodejs 向 php 发送请求时输入意外结束

转载 作者:搜寻专家 更新时间:2023-11-01 00:30:46 25 4
gpt4 key购买 nike

因此,我查看了具有相同错误的其他答案,但他们的解决方案都没有回答我的问题。

我有一个 mysql 表,里面有大约 10k 个名字,我有一个 nodejs 文件的 25 个实例(监听不同的端口),每个实例都发送一个请求,通过一个 php 文件从数据库中获取 400 个名字。如果我将请求设置为 100 - 150有效 但如果我告诉它获取超过 200,我得到错误 '输入的意外结束'。

这是我的 nodejs 请求:

function user_acquire()
{
var request = require('request');
var http = require('http');

var post_options = {
host: 'localhost',
path: '/name_request.php?pos1=50&pos2=150', //this is where the amount to request is set & range
method: 'POST',
headers: {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded',
}
};


// Set up the request
var post_req = http.request(post_options, function (res) {
res.on('data', function (chunk) {
usernames = JSON.parse(chunk);
});
});
post_req.end();
}

这是 nodejs 与之通信的 php 文件:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname, '3306');
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}

$start = $_GET['pos1'];
$end = $_GET['pos2'];

$sql = mysqli_query($conn, "SELECT * FROM preliminary_tests WHERE ID BETWEEN '$start' AND '$end'");
$array = mysqli_fetch_all($sql, MYSQLI_ASSOC);
print_r(json_encode($array,JSON_UNESCAPED_UNICODE));

?>

使用 JSON_UNESCAPED_UNICODE 无法解决问题。我知道 mysql 是用 utf-8 编码的。 这两个这两个函数都适用于较小的请求,但增加请求大小会破坏一个,我不确定为什么

最佳答案

超过 200 个用户名后,响应变得太大,在发送到 Node 时被分成多个 block 。看起来您在到达时解析每个 block ,但可能是该 block 过早地切断了 JSON,这就是您收到错误的原因。您应该能够在到达响应的“数据”事件时附加每个 block ,并在响应的“结束”事件中解析它们。

这看起来像:

// Set up the request
var post_req = http.request(post_options, function (res) {
// create an enclosure for usernames
// so it's in scope in both callbacks,
// and instantiate it as an empty string:
var usernames = "";

// append each chunk on arrival:
res.on('data', function (chunk) {
usernames += chunk;
});

// at the end of the response, parse the full set of chunks:
res.on('end', function() {
usernames = JSON.parse(usernames);
// do something with the parsed usernames
});
});
post_req.end();

看看 MDN 或 CodeSchool 上的闭包,因为当您想在回调之间共享范围时,它们是一个有用的工具。

此外,请查看 Node 文档中有关 HTTP 响应的“ block ”和“结束”事件的信息,以了解更多使用它们的方法。


更新:这是一个很棒的 explanation on closures在 SO 上。

关于php - 从 nodejs 向 php 发送请求时输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com