从API获取图像 [英] Fetch image from API

查看:103
本文介绍了从API获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题1)在我的reactjs应用程序中,我试图从后端Nodejs服务器获取API.该API会根据请求响应一个图像文件.

Q1) In my reactjs application, I am trying to fetch an API from my backend Nodejs server. The API responds with an image file on request.

我可以在 http://192.168.22.124上访问和查看图像文件:3000/source/592018124023PM-pexels-photo.jpg

但是在我的reactjs客户端上,我在控制台日志中收到此错误.

But in my reactjs client side I get this error on console log.

未捕获(承诺)SyntaxError:意外令牌-JSON在位置0

Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0

Reactjs:

let fetchURL = 'http://192.168.22.124:3000/source/';
  let image = name.map((picName) => {
    return picName
  })

  fetch(fetchURL + image)
  .then(response => response.json())
  .then(images => console.log(fetchURL + images));

Nodejs:

app.get('/source/:fileid', (req, res) => {
const { fileid } = req.params;
res.sendFile(__dirname + /data/ + fileid); 
});

有什么比我上面做的更好的事情了吗?

第二季度)另外,如何为空变量(位于提取函数之外)分配值
jpg = fetchURL +图片;所以我可以在某个地方访问它.

Q2) Also, how can I assign a value to an empty variable (which lives outside the fetch function)
jpg = fetchURL + images; So I can access it somewhere.

推荐答案

服务器的响应是一个二进制文件,而不是JSON格式的文本.您需要将响应流读取为Blob.

The response from the server is a binary file, not JSON formatted text. You need to read the response stream as a Blob.

var outside

fetch(fetchURL + image)
  //                         vvvv
  .then(response => response.blob())
  .then(images => {
      // Then create a local URL for that image and print it 
      outside = URL.createObjectURL(images)
      console.log(outside)
  })

这篇关于从API获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆