javascript - 从 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; 所以我可以在某个地方访问它。
解决方案
服务器的响应是二进制文件,而不是 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);
});
推荐阅读
- java - Javafx ExceptionInInitializerError
- c - 将 pthread.h 添加到 nds 项目 makefile
- php - 相同布局的两个页面不同的文本
- assembly - 在 x86-64 中仅使用 16 个寄存器跟踪调用者和被调用者函数
- android - React Native 应用程序崩溃:无法从资产“index.android.bundle”加载脚本
- mongodb - 如何在 MongoDB 中将数组位置 $ 与聚合投影一起使用
- networking - 办公室网络设置
- android - Unity 到 Android - apk 安装但不运行
- java - 将 java.time.LocalDate 与 postgres 日期进行比较的问题
- php - php用参数调用python脚本但没有输出