【发布时间】:2019-09-22 19:38:55
【问题描述】:
是否可以在 PHP 中 gzcompress 数据然后让 Axios 请求它?
我试过这样做,但一直收到此错误:“格式错误的 UTF-8 字符,可能编码不正确。”
我的 Axios 请求如下所示:
axios({
method: 'get',
url: 'https://someapi.com/api/test',
data: { },
config: { headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip' }}
})
.then(response => {
response.data.forEach(el => {
this.transactions.push(JSON.parse(el));
this.transactionsFull = this.transactions;
});
this.loading = false;
console.log(this.transactions);
})
.catch(e => {
this.errors.push(e)
})
$result = openssl_decrypt($cipher_text, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $auth_tag);
$json = json_decode($result);
$channel = Channel::where('uuid', $json->payload->authentication->entityId)->first();
$gzencode = gzencode(json_encode(array('transaction' => $json, 'relation' => json_decode($channel))), 8);
Redis::lpush('transactions_gzencode', $gzencode);
$length = 0;
$transactions = Redis::lrange('transactions_gzencode', 0, -1);
foreach($transactions as $item) {
$length += strlen($item);
}
header('Content-Encoding: gzip');
header('Content-Type: application/json');
header('Content-Length: ' . $length);
return $transactions;
【问题讨论】:
-
您确定要完全在 PHP 中执行此操作吗?通常,它是通过适当的设置(Nginx 或 Apache)在 Web 服务器端完成的。
-
嗨@Ruslan 但是发送压缩的数据因为它的大小更小然后解压缩它是否有意义?
-
你说的是对的。但是 PHP 和 Web 服务器之间没有实际的“流量”。因此,使用 PHP 压缩数据没有任何好处(也许有一些例外,但不确定它是否适用于对 REST API 的常规 JS 查询)。您可以尝试这样的操作 - php.net/manual/ru/function.gzcompress.php,但如果您在 Web 服务器级别进行压缩,您还可以控制静态资产(JS、CSS、HTML、图像)的 gzip,并在一处管理您的压缩策略。跨度>
-
gzcompress 正是我正在做的。我正在做的是压缩大型 JSON 对象并将它们放入 Redis。然后我从 Redis 中检索所有内容并将其发送到我的 VueJS 前端应用程序。我遇到的问题是 Axios 没有解压缩数据。
标签: java php http vue.js axios