【问题标题】:how to get an image from flask api in react native如何在本机反应中从烧瓶 api 获取图像
【发布时间】:2019-11-14 00:04:11
【问题描述】:

我正在使用烧瓶发送图像以响应本机,如果我使用邮递员并且我也看到图像,我会得到“200 OK”,但是当我使用本机反应来获取图像并将其显示在屏幕上时我在 JSON 中的位置 0 处收到“错误 Unexpected token �”。

代码如下:

  fetch("http://10.0.2.2:5000/api/echo", {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    x: 0,
    y: 0
  })
})
  .then(response => response.text())
  .then(responseJson => {
    console.log(JSON.parse(responseJson));
  })
  .catch(error => {
    console.error(error);
  });
};

我不知道我应该在 .then() 中具体写什么,我尝试了几个在互联网上找到的解决方案,但都没有奏效。

这是烧瓶代码:

@app.route('/api/echo', methods=['GET', 'POST', 'DELETE', 'PUT'])
def add():
  while(True):
    data = request.get_json()
    img = plt.imread('mapflask.png')
    plt.figure()
    plt.imshow(img)
    plt.scatter(100, 20, s=30, c='red', marker='o')
    plt.scatter(30, 40, s=30, c='blue', marker='o')
    plt.axis('off')
    plt.savefig("test100.png", transparent=True,
                bbox_inches='tight', dpi=150)

    filename = 'test100.png'
    return send_file(filename, mimetype='image/jpg')

【问题讨论】:

    标签: javascript react-native flask fetch-api


    【解决方案1】:

    您正在发送图像作为响应并接受 application/json 作为响应。

    你应该这样做:-

    var image
      fetch("http://10.0.2.2:5000/api/echo", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        x: 0,
        y: 0
      })
    })
      .then(response => response.blob())
      .then(images => {
          // Then create a local URL for that image and print it 
          image = URL.createObjectURL(images)
          console.log(image)
      })  .catch(error => {
        console.error(error);
      });
    }; 
    

    【讨论】:

    • 它说“无法为 blob 创建 URL!”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2018-03-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2019-05-28
    相关资源
    最近更新 更多