首页 > 解决方案 > 从 API 获取图像

问题描述

Q1)在我的 reactjs 应用程序中,我试图从我的后端 Nodejs 服务器获取 API。API 根据请求使用图像文件进行响应。

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

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

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

反应:

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));

节点:

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

有没有比我上面做的更好的方法?

Q2)另外,如何为空变量(位于 fetch 函数之外)
赋值 jpg = fetchURL + images; 所以我可以在某个地方访问它。

标签: javascriptnode.jsreactjs

解决方案


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

const imageUrl = "https://.../image.jpg";

fetch(imageUrl)
  //                         vvvv
  .then(response => response.blob())
  .then(imageBlob => {
      // Then create a local URL for that image and print it 
      const imageObjectURL = URL.createObjectURL(imageBlob);
      console.log(imageObjectURL);
  });

推荐阅读