繁体   English   中英

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

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

我有一个Node.js系统,它读取二进制文件内容,向它们添加元数据并将生成的数据上传到基于PHP的服务器。 但是,在node.js端执行JSON.stringify并在PHP端读取数据会导致数据损坏。

请注意,我不是将内容类型声明为JSON,而是将所有内容都作为POST数据发送 - 系统还有其他用途,因此我希望保持所有内容均匀。

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方面:

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

在我自己的代码中发现了这个问题:请求体是一个由JSON.stringify(payload)产生的字符串; 它自动被双重编码为​​UTF-8。 更改为缓冲区并明确指定二进制编码修复了doubleencoding:

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

暂无
暂无

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

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