'Get and render image from API in (Vue)JS?
I have a website running VueJS at localhost:3000
which does some stuff to call this.nextImage()
.
methods:
// content //
async nextImage() {
console.log("In nextImage from App.vue"); // keeping track of location
try {
const response = await axios.get('http://localhost:5050/images');
console.log(response.data);
[how to make an image?]
} catch (error) {
console.error(error);
}
}
// content //
<template>
<!-- stuff -->
<div class="picture"><img :src="[what should go here?]" :alt="imageName"></div>
<!-- more stuff -->
<template
on localhost:5050
is an express server, which includes this:
const path = require('path')
// content //
app.get('/images', (req, res) => {
console.log("Express server: /images"); // tracking location
let imageName = 'myImage'
let imagePath = path.join(__dirname, '/images/' + imageName + '.jpeg')
res.sendFile(imagePath)
})
Logging the response.data gives
����JFIF���
!.%+!&8&+/1555$;@;4?.4514+$+44444444444444444444444444444444444444444444444444���"����B !1AQ2aq���"BR�����b�#3CSr���D��$%4����&1Q!Aa�2q�"��?�Z�UyEZL�>��ˀ��@�'G
��YU�U�$RlX�d<ǜ
(... abbreviated because I had too much code)
I need two pretty straightforward things:
- The image to render properly
- The name of the image
Solution 1:[1]
This was a pretty easy fix. I didn't actually need to send the file itself, just a link to the file (just app.send(imagePath)
). When the client makes a GET call to the server, they get a url that can just be included in the img
tag like so: <img source="imagePath">
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | grepgrok |