[英]How do I send image data from a url using express?
我希望我的应用程序的/image
返回一个随机图像,我该怎么做?
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
res.send(/**/); // How do I send the image binary data from the url?
});
在 HTML 中,此图像实际上显示了图像的内容https://example.com/images/test.jpg
<img src="https://my-app.com/image" />
Express API中有res.sendFile
app.get('/image', function (req, res) {
// res.sendFile(filepath);
});
我们有同样的问题,这是我使用request
包的解决方案,所以你必须先使用yarn add request
或npm i request
。 你的代码应该是这样的
const request = require('request');
const express = require('express');
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
request({
url: url,
encoding: null
},
(err, resp, buffer) => {
if (!err && resp.statusCode === 200){
res.set("Content-Type", "image/jpeg");
res.send(resp.body);
}
});
});
您可以将所有此类图像链接保存在 json 或您选择的任何数据文件中,并随机从中获取并转发并通过变量传递它们以作为响应。 喜欢: res.send(imgURL: 'https://example.com/images/test.jpg');
或者您可以在 init 中传递 url 变量。
const express = require("express");
const https = require("node:https");
const app = express();
const port = 3000
app.get("/", function(req, res){
const url = "https://api.openweathermap.org/data/2.5/weather?q=Paris&units=metric&appid=65441206f989bc53319e2689fccdc638";
https.get(url, function(response){
response.on("data", function(data){
const weatherData = JSON.parse(data)
const icon = weatherData.weather[0].icon
const imageUrl = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
res.write("<img src=" + imageUrl + " ></img>")
res.send();
})
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.