Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything works fine. It seems like the image is somehow getting lost along the way.

Here's the 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)
        })

And here's my app.js setup:

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

Answer №1

If you're trying to access images in the public folder, browsers assume that /<path> is using the same host and port. However, with Express, your API/Webserver might be on a different host or port. To make this work, you'll need to have your images hosted in the /public directory in Vue.

To direct your browser to the correct location for the image, especially when it's on the same domain (localhost) but a different port, you can create a computed property to return the current hostname. You can do this by using window.location.hostname.

In Vue, add a computed property to get the domain/hostname and adjust the port number accordingly:

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

Then update your URL to include the hostname obtained from the computed property:

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

By making these changes, your images should load correctly from the server.


You can also incorporate some logic into your computed property. For instance, if your image URLs are hosted on a different domain in production but locally served by Express on your local server during development:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

unable to install npm package on Azure cloud platform

My attempt to deploy my website to Azure has hit a roadblock as npm install is failing with the following error: 2498 silly fetchPackageMetaData error for interactjs@git+https://github.com/taye/interact.js.git#v1.3.0-alpha.4 Command failed: D:\Prog ...

"Escaping from the typeahead feature in Angular-UI Bootstrap results in the input field value becoming

Having some difficulty solving a particular edge case scenario. When I select a value from the dropdown of the typeahead using either the keyboard or mouse, the ng-model in the input field is populated correctly. However, if I type a few letters and then ...

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

The jQuery .ajax() function encountered a 405 error stating "Method Not Allowed" when attempting a cross

Despite searching extensively on SO, I am unable to pinpoint the issue in my code. To avoid using JSONP, I am implementing CORS. I understand that this is a preflighted request and believe I have included the correct headers. The problem lies in the web ...

How can I extract the selected sorting parameters in Vuetify datatables?

Currently, I am developing an export tool specifically for a Vuetify datatable. One of the key requirements is to pass on to the generator the columns by which the datatable has been sorted along with their respective directions. I have been searching fo ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

The Position of the WebGL Globe Within the Environment

I've been experimenting with the WebGL Globe, and I have successfully made it rotate. However, I'm struggling to figure out how to adjust its position so that it's not centered in the scene. After making changes to the code found at https:/ ...

What is the best way to display multiple files in a vertical stack when choosing a file?

<div class="selected-file-container align-items-center justify-content-between d-none"> <div class="selected-file d-flex align-items-center"> <img id="selectedImage" class="hidden" src="&qu ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

What are the benefits of storing dist in both a GitHub repository and on npm?

I'm curious about why some repositories include a dist folder. Shouldn't repositories just store source code and not any builds or compiled files? Let's take a look at an example with ES6 code. package.json { "files": [ "dist", ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

NodeJS tutorial on obtaining the Instagram username and access token

How do I retrieve the username and access token after a user logs in using Instagram-passport for my app login? I'm having trouble accessing the 'profile' in the middleware section. //serialize user in the session passport.serializeUser(fun ...

What is the best way to extract styled HTML tags from I18N properties files using the Makara module in conjunction with Express and Kraken.js?

I'm currently utilizing Makara, an I18N module designed for Kraken.js and Express.js. Imagine a scenario where I need to format a specific word within a sentence, but its placement varies based on different languages. I want to ensure that this can b ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

There seems to be a lack of definition for Angular within the angular

Currently, I am in the process of developing an Angular application. The modules I have created contain services and controllers that are all working as intended. Recently, I added angular-animate to my list of scripts, which are loaded from a cshtml file ...

Building a framework for combined frontend and backend plugins using Vue and Express

Currently, I am facing a challenge with my repository which contains a Vue CLI-generated frontend application and an Express backend application. The setup involves a standard Vue CLI app with a top-level backend src folder. The Express app defines various ...