我是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,但我无法找到可以向我展示完成该操作的良好示例。
编辑 22.11.17
我添加了在命令行中显示的错误和导入组件时的 { }。我仍然没有解决这个问题。
编辑 24.11.17
寻找答案,我添加了更多关于我发布的代码的说明和文件结构的截图,如果可能的话,它可以帮助。
import { getLatest } from '../../../services/articles/getLatest';
- Fredconst getLatestService = new getLatest();
吗?为什么要在这里使用关键字new
?这将尝试实例化对象,而我认为你只是想调用函数。 - Phil