【问题标题】:Express: Image from vue.js is not redirected to backendExpress:来自 vue.js 的图像未重定向到后端
【发布时间】:2021-07-10 19:45:23
【问题描述】:

我有一个通过 express 调用后端的 vue 应用程序。当我将图像添加到请求时,请求不会重定向到后端。但是,当我直接从 vue 应用程序调用后端时,没有 express,请求被正确处理。图像在途中不知何故丢失了。

Vue-代码:

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

【问题讨论】:

    标签: javascript vue.js express file express-fileupload


    【解决方案1】:

    目前您尝试做的是在公用文件夹中找到图像,因为浏览器假定/<path> 使用相同的主机和端口。在您的情况下,您使用的是 express,因此您的 API/Webserver 位于不同的主机和/或端口上。使用您当前的配置,您必须将图像托管在 vue 中的 /public 目录中才能按预期工作。

    因此,您需要告诉您的浏览器在别处寻找图像。由于它在同一个域 (localhost) 上并且在不同的端口上,您可以使用计算属性返回当前主机名。假设您在本地计算机上,它将是 localhost 或者我们可以通过 window.location.hostname 动态获取域。

    在 Vue 中添加一个计算属性来获取您的域/主机名并更改端口号,如下所示:

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

    然后修改您的 URL 以包含我们从计算属性中获得的主机名

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

    现在您的图像应该从正确的服务器加载


    您还可以为您的计算属性添加一些逻辑,假设您的图像 URL 在生产中托管在不同的域中,但是当您在本地开发时,它们是从本地服务器上的 express 运行的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-08
      • 2020-07-15
      • 2018-11-09
      • 2018-02-26
      • 1970-01-01
      • 2021-10-26
      • 2021-09-15
      • 2013-09-06
      相关资源
      最近更新 更多