Express: Image from vue.js is not redirected to backend

530 views Asked by At

I have a vue app which calls the backend through express. When I add an image to a request the request is not redirected to the backend. However, when I call the backend directly from the vue app, without express, the request is handeled correctly. The image gets lost somehow on the way.

Vue-code:

    uploadImage(){
        this.loadingImage = true
        const url = "/person/"+localStorage.getItem("userUuid")+"/picture";
        var config = {headers: {"Authorization": "Bearer "+localStorage.getItem("token")}};
        const fd = new FormData();
        fd.append('image', this.picture, this.picture.name)
        this.$http.post(url, fd, config)
        .then((response) => {
             console.log(response)
            this.loadingImage = false
             //window.location.reload()
        })
        .catch((error) => {
            console.log(error)
        })

app.js

const proxy = require('express-http-proxy');
const express = require('express')
const fileUpload = require('express-fileupload');
const app = express();

app.post('/person/:id/picture', proxy(config.backendURL, {
    filter: function(req, res) {return checkBearer(req, res)}
}));
1

There are 1 answers

0
Marcello B. On

Currently what you are attempting to do is locate the images in the public folder, as browsers assume that /<path> using the same host and port. In your case, you are using express so your API/Webserver is on a different host and or port. With your current configuration, you would have to have your images hosted in the /public directory in vue for it to work as expected.

Therefore you need to tell your browser to look elsewhere for the image. Since it is on the same domain (localhost) and is on a different port you can use a computed property to return the current hostname. Assuming you are on your local machine it would be localhost or we can get the domain dynamically through window.location.hostname.

In Vue add a computed property to get your domain/hostname and change the port number like so:

computed:{
   baseUri(){
        return `${window.location.hostname}:3000`;
   }
}

Then modify your URL to include the hostname we got from our computed property

const url = `${this.baseUri}/person/${localStorage.getItem("userUuid")}/picture`;

Now your images should load from the correct server


You can also add some logic to your computed property, let's say your image URLs are hosted on a different domain in production, but when you are developing locally they are running from express on your local server.

computed:{
   baseUri(){
        return process.env.NODE_ENV === 'development' ? 
            `${window.location.hostname}:3000`:
            'myimages.mydomain.com'; // <-- you can also change the port here if you need
   }
}