小编Nic*_*nev的帖子

在Vue.js中使用带有单独服务的axios?

我想将axios请求逻辑移至Vue.js应用程序中的单独服务。Axios始终返回promise,如何在组件中从中获取响应数据?还是为此有其他解决方案?

UserService.js

class UserService {
    getUser() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(function (response) {
            return response.data;
        }).catch(function (error) {
            console.log(error);
        });
    }
    getUserTasks() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user/task', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(response => {
            return response;
        }).catch(function (error) {
            console.log(error);
        });
    }
    get currentUser() {
        return this.getUser();
    }
}
export default new UserService();
Run Code Online (Sandbox Code Playgroud)

javascript vue.js axios

5
推荐指数
1
解决办法
2556
查看次数

标签 统计

axios ×1

javascript ×1

vue.js ×1