So I have an array of urls that I want to host in my backend. I couldn't find anything related to hosting images with their urls in express so I thought of an idea. I would get the image's buffer with axios and send that
const images = [
{ name: "cow", url: "https://somewhere.com/cow.png" },
{ name: "chicken", url: "https://somewhere.com/chicken.png" }
]
const express = require("express")
const app = express()
const port = 4000
const axios = require("axios")
app.listen(port, () => { console.log("Online") })
images.forEach(image => {
app.get(`/${image.name}.png`, (res, req) => {
const getBuffer = async (url) => {
return new Promise(async (resolve, reject) => {
try {
const response = await axios({
method: 'GET',
url: url,
responseType: 'stream',
});
const buffer = response.data
resolve(buffer)
} catch (err) {
console.log(err);
}
})
}
res.sendFile(getBuffer(res.url))
})
})
But I think there is a better way of doing this
When you use responseType as stream, you can forward the data stream to express response object directly:
const express = require("express")
const axios = require("axios")
const app = express()
const port = 4000
const images = [
{ name: "cow", url: "https://somewhere.com/cow.png" },
{ name: "chicken", url: "https://somewhere.com/chicken.png" }
]
app.get('/images/:name', async (req, res) => {
const { name } = req.params
const image = images.find(img => img.name === name);
if (!image) {
return res.status(404).send()
}
try {
const response = await axios({
method: 'GET',
url: image.url,
responseType: 'stream',
});
response.data.pipe(res)
} catch(error) {
res.status(500).send(error.message)
}
});
app.listen(port, () => { console.log("Online") })
Now you can try with http://localhost:4000/images/cow