首页 > 解决方案 > 如何解压缩 Gunzip 以及如何将对象解析为 Json?

问题描述

我需要将个人资料图片上传到个人资料。我需要获取 ID,因此我将图片上传到正确的个人资料。API 的响应是一个 Gunzip 对象。

.then(resp => JSON.parse(resp)).then(data => {console.log(data.Gunzip.read(5)} )

我已经尝试过了,但出现错误:(node:16100) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1

const fetch = require("node-fetch");
const userID = '12345'
const EXAMPLE_PUT_URL = `https://backend.example.com/api/users/${userID}`
const EXAMPLE_GET_URL = `https://backend.example.com/api/users/?limit=5`

const ACCESS_TOKEN = 'NWNmNmYyOWMzNTk5YTA3YjU3MGZkN2Y2OmV6UXo1TiZnXmVtWmJfKzRsOFJ5LWFMLShUUzFzbno7dDNpLV5KX0dOLFIwT1dkTFh1VFZWalE2LFNtKX4pV3U='

var fs = require('fs');

var contents = fs.readFileSync('images/profile1.jpg', 'utf8');

fetch(EXAMPLE_GET_URL, {
    method: 'GET',
    headers: {
      "Authorization": `Basic ${ACCESS_TOKEN}`,
      "Content-type": "application/json",
      "Accept": "application/json",
      "Accept-Charset": "utf-8",
    }, 
  })
    .then(response => { 
          fetch(EXAMPLE_PUT_URL, {
            method: 'PUT',
            headers: {
              "Authorization": `Basic ${ACCESS_TOKEN}`,
              "Content-type": "application/json",
              "Accept": "application/json",
              "Accept-Charset": "utf-8",
            },
            body: JSON.stringify({
                  avatar:contents,
              })      
          })
          console.log(response)})
    ;

使用此代码,我得到了压缩对象而不是对象,所以我看不到我需要的 ID。

标签: javascriptnode.jsjson

解决方案


推荐阅读