首页 > 解决方案 > vue axios.get 从 imgur 获取图像

问题描述

在尝试从图库模板中获取所有图像时,我收到以下错误/警告通知:“在渲染期间访问了属性“令牌”,但未在实例上定义“。而不是显示我收到以下的图像:<img src="function link() { [native code] }">我错过了什么?

画廊.vue

<template>
  <div>
    <img v-for="image in allImages" :src="image.link" :key="image.id" />
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "Galleries",
  computed: mapGetters(["allImages"]),
  methods: mapActions(["fetchImages"]),
  created() {
    this.fetchImages();
  }
};
</script>

imgur.js

import qs from 'qs';
import axios from 'axios';

const CLIENT_ID = 'e28971925a8d43c';
const ROOT_URL = 'https://api.imgur.com';

export default {
    login() {
        const querystring = {
            client_id: CLIENT_ID,
            response_type: 'token',
        };
        window.location = `${ROOT_URL}/oauth2/authorize?${qs.stringify(querystring)}`
    },
    fetchImages(token) {
        return axios.get(`${ROOT_URL}/3/account/me/image/`, {
            headers: {
                Authorization: `Bearer ${token}`
            }
        });
    },
    uploadImages(images, token) {
        const promises = Array.from(images).map(image => {
            const formData = new FormData();
            formData.append('image', image);
            return axios.post(`${ROOT_URL}/3/image`, formData, {
                headers: {
                    Authorization: `Bearer ${token}`
                }
            });
        });
        return Promise.all(promises);
    }
};

图像.js

import api from '../../api/imgur';
import { router } from '../../main';

const state = {
    images: []
};

const getters = {
    allImages: state => state.images

};

const mutations = {
    setImages: (state, images) => {
        state.images = images;
    }
};

const actions = {
    async fetchImages({ rootState, commit }) {
        const { token } = rootState.auth;
        const response = await api.fetchImages(token);
        commit('setImages', response.data.data);
    },
    async uploadImages({ rootState }, images) {
        // Get the access token
        const { token } = rootState.auth;
        // Call our API module to do the upload
        await api.uploadImages(images, token);

        // Redirect use to the gallery page
        router.push('/galleries');


    }
};

export default {
    state,
    getters,
    mutations,
    actions
}

auth.js

import api from '../../api/imgur';
import qs from 'qs';
import { router } from '../../main';


const state = {
    token: window.localStorage.getItem('imgur_token')
};

const getters = {
    isLoggedIn: state => !!state.token // turn a value into boolean
};

const actions = {
    login: () => {
        api.login();
    },
    finalizeLogin({ commit }, hash) {
        const query = qs.parse(hash.replace('#', ''));
        commit('setToken', query.access_token);
        window.localStorage.setItem('imgur_token', query.access_token);
        router.push('/');
    },
    logout: ({ commit }) => {
        commit('setToken', null);
        window.localStorage.removeItem('imgur_token');
        router.push('/');
    }
};

const mutations = {
    setToken: (state, token) => {
        state.token = token;
    }
};

export default {
    state,
    getters,
    actions,
    mutations
};

标签: vue.jsaxiosvuejs3imgur

解决方案


// Galaries.vue
// You didn't pass token when calling function `fetchImages`.
created() {
    this.fetchImages(); // missing token here
  }

出于安全原因,我建议使用令牌作为环境变量。永远不要公开你的令牌。不应将其作为函数的参数传递。将您的令牌存储在.env文件中。您可以如下重写您的 fetchImages。

    fetchImages(token) {
        return axios.get(`${ROOT_URL}/3/account/me/image/`, {
            headers: {
                Authorization: `Bearer ${process.env.TOKEN}`
            }
        });
    },
    

推荐阅读