【问题标题】:How to show an image with token with axios in vuejs如何在 vuejs 中使用 axios 显示带有令牌的图像
【发布时间】:2019-06-26 22:08:11
【问题描述】:

我有一个返回与图像关联的文章列表的 api rest,该服务需要一个令牌。

我遇到的问题是在尝试显示文章的图像时,因为它们需要令牌。我展示了部分代码来帮助我提出您的建议。

模板

<div class="col-md-3 d-flex align-items-stretch" v-for="article in listarticles" :key="article.idArticle">
    <div class="main-card mb-3 card">
        <img width="100%" class="card-img-top" :src="'data:image/jpeg;base64,' + getBase64(article.images[0].url)" >
    </div>
</div>

方法

getBase64(url) {
            return this.$http
              .get(url, {
                responseType: 'arraybuffer'
              })
              .then(response => console.log('data:image/jpeg;base64,' + new Buffer(response.data, 'binary').toString('base64')))
          }

我从 axios 的主要语句发送的令牌,当我检查浏览器控制台时,我可以正常看到图像,但是在图像 src 中我得到 src = 'data: image / jpeg; base64, [对象承诺]'

【问题讨论】:

    标签: vue.js axios token base64url


    【解决方案1】:

    这是因为您的 axios 请求返回了一个承诺。

    如果可以,请使用 Async / Await:

    async getBase64(url) {
      return await this.$http.get(url, { responseType: 'arraybuffer' })
    }
    

    如果您不能使用 async / await,您将需要通过在 created 中循环它们并将它们添加到 data () { } 中的数组中来预加载所有图像,然后在模板中引用该图像数组。

    【讨论】:

    • 您是否收到任何 linting 错误?你是用 babel 转译的吗?
    猜你喜欢
    • 2021-02-13
    • 2018-12-05
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2020-11-09
    • 2018-04-23
    • 2020-05-08
    相关资源
    最近更新 更多