[英]expressjs - Fetch an image from url and display it on the page
I have an image API running from a home server, and I'm building a cloud-hosted page that grabs the image in backend and shows it, for a layer of abstraction.我有一个从家庭服务器运行的图像 API,并且我正在构建一个云托管页面,该页面在后端抓取图像并显示它,用于抽象层。
Here's what I'm trying to do:这是我正在尝试做的事情:
index.js index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
// some logic to grab the image and pass it to the HTML page
// var image = fetch("myimageapi.com")
// ?????
res.render('index', {page:'Home', menuId:'home'});
});
and display it with <img id="myimage">
并用
<img id="myimage">
显示它
Or maybe it would be better to:或者可能会更好:
router.get('/', function(req, res, next) {
res.render('index', {page:'Home', menuId:'home'});
});
router.get('/image', function(req, res, next) {
//fetch image
});
and <img src="mywebsite.com/image>
和
<img src="mywebsite.com/image>
I really have no idea how one would go about doing this in node, I am coming from python and this is all very scary我真的不知道 go 如何在节点中执行此操作,我来自 python,这一切都非常可怕
I solved it, just had to come back with a fresh brain:我解决了它,只需要带着一个新鲜的大脑回来:
app.get('/', (req, res) => {
res.render("index")
})
app.get('/image', async (req, res) => {
const url = 'example.com/image.png';
request({
url: url,
encoding: null
},
(err, resp, buffer) => {
if (!err && resp.statusCode === 200){
res.set("Content-Type", "image/jpeg");
res.send(resp.body);
}
});
});
In index.ejs: <image src='/image'>
calls the image route and pulls the image as if it were a static file.在 index.ejs 中:
<image src='/image'>
调用图像路由并拉取图像,就好像它是 static 文件一样。 I feel like it would be cleaner to pass it directly to the page, but this solution works so I'm running with it.我觉得将它直接传递给页面会更干净,但是这个解决方案有效,所以我正在使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.