Home  >  Q&A  >  body text

Get and render image from API in (Vue)JS?

I have a website running VueJS at localhost:3000 and it does something that calls 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 that includes:

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)
})

Record response.data gives

����JFIF���
!.%+!&8&+/1555$;@;4?.4514+$+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 very simple things:

  1. Image to render correctly
  2. Picture name

P粉966335669P粉966335669206 days ago411

reply all(1)I'll reply

  • P粉786432579

    P粉7864325792024-03-27 15:05:27

    This is a very simple fix. I don't actually need to send the file itself, just the link to the file (just app.send(imagePath) ). When clients make a GET call to the server, they get a url, which can be enclosed in an img tag like this: <img source="imagePath">.

    reply
    0
  • Cancelreply