Ted*_*Khi 9 javascript node.js reactjs
Q1)在我的reactjs应用程序中,我试图从我的后端Nodejs服务器获取API.API根据请求响应图像文件.
我可以访问http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg查看图像文件
但在我的reactjs客户端,我在控制台日志中收到此错误.
未捕获(在promise中)SyntaxError:位于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));
Run Code Online (Sandbox Code Playgroud)
的NodeJS:
app.get('/source/:fileid', (req, res) => {
const { fileid } = req.params;
res.sendFile(__dirname + /data/ + fileid);
});
Run Code Online (Sandbox Code Playgroud)
有什么比我上面做的更好的方法吗?
Q2)另外,如何为空变量赋值(它存在于fetch函数之外)
jpg = fetchURL + images; 所以我可以在某个地方访问它.
max*_*paj 15
服务器的响应是文件,而不是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)
})
Run Code Online (Sandbox Code Playgroud)
eri*_*gor 11
相当于@maxpaj的解决方案,但使用async和await。
async function load_pic() {
const url = '<REPLACE-WITH-URL>'
const options = {
method: "GET"
}
let response = await fetch(url, options)
if (response.status === 200) {
const imageBlob = await response.blob()
const imageObjectURL = URL.createObjectURL(imageBlob);
const image = document.createElement('img')
image.src = imageObjectURL
const container = document.getElementById("your-container")
container.append(image)
}
else {
console.log("HTTP-Error: " + response.status)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16710 次 |
| 最近记录: |