Vue2JS中的服务 - 在created钩子中出现错误

7

我是vue2JS的新手,目前正在尝试创建我的第一个vue2服务。

我已经创建了基本文件api.js,其中包含以下代码:

import axios from 'axios';

export default () => {
    return axios.create({
        baseURL: 'http://localhost:8080/',
        timeout: 10000,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
}

上面的代码是基本的axios配置,将在整个应用程序中的每个服务中使用。

我将此文件导入到我的服务中:

import api from '../api.js';

export default {
    getLatest () {
        return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            console.log(error);
        });
    }
}

以上代码负责向后端rest API发出http请求,以获取JSON响应。

最后,我想在我的组件<script></script>标签中使用此服务:

<script>
    import { getLatest } from '../../../services/articles/getLatest';

    export default {
        data () {
            return {
                articles: []
            }
        },
        created () {
            const getLatestService = new getLatest();
            console.log(getLatestService);
        }
    }
</script>

在这里,我想从服务中执行代码,并实际执行此http请求,然后将响应保存在 getLatestService 常量中,然后使用 console.log 进行记录,我应该能够在浏览器控制台中看到JSON。

这不起作用,并在chrome控制台中给我这个错误:

[Vue警告]:created钩子中的错误:“TypeError:WEBPACK_IMPORTED_MODULE_0__services_articles_getLatest .a不是构造函数”

并在命令行中显示此错误:

39:35-44“未找到'../../../services/articles/getLatest'中的'getLatest'导出

请帮助我解决这个问题。另外,我想重构我的服务代码(第二个),以使用async await,但我无法找到可以向我展示完成该操作的良好示例。

files structure

编辑 22.11.17

我添加了在命令行中显示的错误和导入组件时的 { }。我仍然没有解决这个问题。

编辑 24.11.17

寻找答案,我添加了更多关于我发布的代码的说明和文件结构的截图,如果可能的话,它可以帮助。


你的打包工具是否需要在导入时加上 .js 后缀?import { getLatest } from '../../../services/articles/getLatest'; - Fred
我认为是的,这是我的webpack.base.conf.js配置文件:https://gist.github.com/anonymous/8cfe140faaa9f3e79805db56d7cb8902 - BT101
在你的脚本标签中,你确定要调用 const getLatestService = new getLatest(); 吗?为什么要在这里使用关键字 new?这将尝试实例化对象,而我认为你只是想调用函数。 - Phil
1个回答

1
我已经检查了你的代码,我看到的是,在你的api.js文件中,你使用了
baseURL: 'http://localhost:8080/',

并且在您的服务文件中

return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`

在您的服务文件中,您没有定义本地主机端口,我认为应该像这样:
返回api().get(http://localhost:8080/obiezaca/ob_serwer/api/article/getLatest.php
如果以上不是您的问题,则应尝试。
const getLatestService = getLatest();

因为getLatest()是一个函数而不是对象。

这可能会解决您的错误问题。


这不是我的问题。API完全独立于前端,并由apache xampp运行。URL是正确的。 - BT101

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接