简体   繁体   English

通过HTTP将JSON从node.js传递给PHP

[英]Passing JSON from node.js to PHP via HTTP

I have a Node.js system which reads binary file contents, adds metadata to them and uploads the generated data to a PHP-based server. 我有一个Node.js系统,它读取二进制文件内容,向它们添加元数据并将生成的数据上传到基于PHP的服务器。 However, doing JSON.stringify on the node.js end and reading data back on the PHP side results in data being corrupted. 但是,在node.js端执行JSON.stringify并在PHP端读取数据会导致数据损坏。

Note that I'm not declaring content type as JSON, but rather sending everything as POST data - the system has other uses, so I want to keep everything uniform. 请注意,我不是将内容类型声明为JSON,而是将所有内容都作为POST数据发送 - 系统还有其他用途,因此我希望保持所有内容均匀。

Node.js side: Node.js方面:

const chunks = [];
fs
    .createReadStream(GR.dataFolder + 'output/' + file, {
        start: from,
        end: from + size - 1,
        autoClose: true
    })
    .on('data', function(chunk) {
        chunks.push(chunk);
    })
    .on('end', function() {
        let data = Buffer.concat(chunks);
        let hash = crypto.createHash('md5').update(data).digest('hex');
        processUploadFilePart(hash, data);
    })
;

function processUploadFilePart(hash, data) {
    let payload = {
        hash: hash,
        data: data.toString('binary'),
    };

    // verify - this results in a correct hash, so node.js does not lose data in JSON.stringify
    let tmp = JSON.stringify(payload);
    tmp = JSON.parse(tmp);
    let hashed = crypto.createHash('md5').update(Buffer.from(tmp.data, 'binary')).digest('hex');
    console.log(hashed);

    request
        .post({
            url: server,
            body: JSON.stringify(payload),
            encoding: null, // does not seem to have any effect
            }, function(err, response, body) {
                // PHP responds with a different data hash
            }
        )
    ;
}

PHP side: PHP方面:

$request = file_get_contents('php://input');
$json = json_decode($request, true);
$md5 = md5($json['data']);
if ($md5 !== $json['hash']) {
    $this->output['error'] = 'hash mismatch';
}

Found the issue in my own code: request body was a string as resulting from JSON.stringify(payload) ; 在我自己的代码中发现了这个问题:请求体是一个由JSON.stringify(payload)产生的字符串; it got automatically doubleencoded into UTF-8. 它自动被双重编码为​​UTF-8。 Changing to a buffer and explicitly specifying binary encoding fixes doubleencoding: 更改为缓冲区并明确指定二进制编码修复了doubleencoding:

body: Buffer.from(JSON.stringify(payload), 'binary'),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM