Express无法读取分块数据

时间:2019-08-27 08:19:01

标签: typescript express body-parser

我正在从Campbell科学数据记录器收集数据。该数据记录器使用Express和BodyParser将信息发布到以Typescript编码的应用程序。该请求获取了应用程序(可以对其进行调试),但主体/查询为Object {}

为了确保数据记录器发送数据,我做了另一个程序,一个简单的PHP代码,用于转储发布数据及其标头:

$json_params = file_get_contents("php://input");
$log->lwrite($json_params); 
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
      $log->lwrite('header:'.$header.' Value:'.$value);
}

结果是:

[26/Aug/2019:17:10:59] (test - 12452) {"head": {"transaction": 0,"signature": 11786,"environment": {"station_name": "idtest","table_name": "Tabla1","model": "CR300","serial_no": "1646","os_version": "CR310.Std.08.01","prog_name": "CPU:19014_Badajoz_Inundacion_Dev1.CR300"},"fields": [{"name": "Voltage","type": "xsd:float","units": "Volts","process": "Avg","settable": false},{"name": "Temp","type": "xsd:float","units": "Grados C","process": "Avg","settable": false},{"name": "HR","type": "xsd:float","units": "%HR","process": "Smp","settable": false},{"name": "Lluvia","type": "xsd:float","units": "mm","process": "Tot","settable": false},{"name": "Distancia","type": "xsd:float","units": "cm","process": "Avg","settable": false},{"name": "Calado","type": "xsd:float","units": "cm","process": "Avg","settable": false}]},"data": [ {"time": "2019-08-26T17:09:00","no": 0,"vals": [12.26,"NAN","NAN",0,"NAN","NAN"]}]}

`[26/Aug/2019:17:10:59] (test - 12452) header:User-Agent Value:CR310.Std.08.01`

`[26/Aug/2019:17:10:59] (test - 12452) header:Host Value:192.168.1.33`

[26/Aug/2019:17:10:59] (test - 12452) header:Transfer-Encoding Value:chunked

  • 请注意,在““数据”之后,json中有换行符:['也许是个问题?还是传输编码类型?

这意味着我在打字稿应用程序中做错了事。

this.app = express();
this.port = port;
this.app.use(bodyParser.urlencoded({ extended: true }));
this.app.use(bodyParser.json());
this.router = express.Router();
this.router.post(this.path_campbellStation  
this.updateCampbellStationPost);

在同一应用程序中,我从另一个数据记录器收集信息,该数据记录器发送数据但发送GET请求并且工作正常(相同的代码)。 我不知道是否必须以其他方式(带有特殊选项的BodyParser)对其进行处理,因为在调试打字稿应用程序时,我只能在主体,参数,原始,查询...为空的情况下读取标头(对象{})

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:0)

大家好消息!

我找到了解决方案。处理分块请求的方法(因此,PHP代码中的行制动)是实现其“ on”事件:

updateCampbellStationPost = (request: express.Request, response: express.Response) => {
    var data: string = '';

    const _this = this;
    request.on('data', function(chunk) {
        data += chunk;
    });

    request.on('end', function() {
        request.body = JSON.parse(data);
        const _data = data;
        // DEAL WITH THE DATA
        response.set('Cache-Control', 'no-store, no-cache, must-revalidate, private').status(200).send('IS ALL RIGHT');
    });

    request.on('error', function (error){
        response.set('Cache-Control', 'no-store, no-cache, must-revalidate, private').status(400).send('IS FUCKED');
    });
}

谢谢!

相关问题