Javascript 从 API 获取图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/50248329/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch image from API
提问by Ted Khi
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.
Q1)在我的 reactjs 应用程序中,我试图从我的后端 Nodejs 服务器获取 API。API 根据请求使用图像文件进行响应。
I can access and see image file on http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg
我可以在http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg上访问和查看图像文件
But in my reactjs client side I get this error on console log.
但是在我的 reactjs 客户端,我在控制台日志中收到此错误。
Uncaught (in promise) SyntaxError: Unexpected token ? in JSON at position 0
Uncaught (in promise) SyntaxError: Unexpected token ? 在位置 0 处的 JSON
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); 
});
Is there any better way to do than what I am doing above?
有没有比我上面做的更好的方法?
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.
Q2)另外,我怎样才能给一个空变量赋值(它位于 fetch 函数之外)
jpg = fetchURL + images; 所以我可以在某个地方访问它。
回答by maxpaj
The response from the server is a binary file, not JSON formatted text. You need to read the response stream as a Blob.
来自服务器的响应是一个二进制文件,而不是 JSON 格式的文本。您需要将响应流作为 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)
  })

