javascript - 如何使用 Fetch 在前端显示通过 HTTP (Node.js) 发送的图像?
问题描述
我正在尝试使用 Node.js 通过 HTTP 获取将返回图片(此时,扩展名无关紧要)的 URL( http://localhost )。
前端
let image = await fetch('http://localhost:3031', {
mode: 'cors',
method: 'GET'
})
后端
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.setHeader('Content-Type', 'image/png');
fs.readFile('image.png', (err, data) => {
res.write(data, "binary");
res.end();
});
}).listen(3031)
我想拍下那张照片,然后将其显示到网站上。
我正在获取文件,而不是 SRC
解决方案
直接在 HTML 中为:
<img id="loadedimage" src="http://localhost:3031/"/>
或与fetch
, 使用createObjectURL
:
var element = document.getElementById('loadedimage');
var response = await fetch('http://localhost:3031');
var image = await response.blob();
element.src = URL.createObjectURL(image);
推荐阅读
- javascript - 关于使用 CustomHooks 测试 React 组件的问题
- javascript - 过滤反应产品页面
- syntax - 如何在主要模式下获取与语法对应的字符
- javascript - Firebase 云功能 - 通过提供的字段名称获取文档
- list - 使用 AppleScript 访问嵌套属性
- postgresql - Postgres 插入/删除触发器
- html - 如何通过 django 用户身份验证数据来响应应用程序?
- java - 比较字符值与字符数组值
- azure - 是否存在不以明文形式保存凭据的 Azure 脚本 API?
- python - 为什么执行 sys.exit() 时 mu-editor 中有这样的退出代码?