https://blog.csdn.net/zhaohaixin0418/article/details/68488136
import axios from 'axios' axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.baseURL = '后台接口公共前缀'; export function fetch(url, params) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response.data); }) .catch((error) => { reject(error); }) }) } export default { // 获取我的页面的后台数据 mineBaseMsgApi() { // alert('进入api.js') return fetch('/api/getBoardList'); }, commonApi(url, params) { return fetch(url, params) }
export default { Carrie(url, params) { return fetch(url, params); } }}
import api from './../../fetch/api';
methods:{
setNewsApi: function() { api.Carrie('/news/index', 'type=top&key=123456') .then(res => { console.log(res); this.newsListShow = res.articles; }); }, }
https://blog.csdn.net/huangshulang1234/article/details/78993592
Vue项目实战(五)配置 Axios api 接口调用文件
还记得我们在第三篇博文中整理的系统结构吗?我们新建了一个 src/api/index.js 这个空文本文件,就那么放在那里了。这里,我们给它填写上内容。
// 配置API接口地址
var root = 'https://cnodejs.org/api/v1'
// 引用axios
var axios = require('axios')
// 自定义判断元素类型JS
function toType (obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
for (var key in o) {
if (o[key] === null) {
delete o[key]
}
if (toType(o[key]) === 'string') {
o[key] = o[key].trim()
} else if (toType(o[key]) === 'object') {
o[key] = filterNull(o[key])
} else if (toType(o[key]) === 'array') {
o[key] = filterNull(o[key])
}
}
return o
}
/*
接口处理函数
这个函数每个项目都是不一样的,我现在调整的是适用于
https://cnodejs.org/api/v1 的接口,如果是其他接口
需要根据接口的参数进行调整。参考说明文档地址:
https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
主要是,不同的接口的成功标识和失败提示是不一致的。
另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert
*/
function apiAxios (method, url, params, success, failure) {
if (params) {
params = filterNull(params)
}
axios({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
baseURL: root,
withCredentials: false
})
.then(function (res) {
if (res.data.success === true) {
if (success) {
success(res.data)
}
} else {
if (failure) {
failure(res.data)
} else {
window.alert('error: ' + JSON.stringify(res.data))
}
}
})
.catch(function (err) {
let res = err.response
if (err) {
window.alert('api error, HTTP CODE: ' + res.status)
}
})
}
// 返回在vue模板中的调用接口
export default {
get: function (url, params, success, failure) {
return apiAxios('GET', url, params, success, failure)
},
post: function (url, params, success, failure) {
return apiAxios('POST', url, params, success, failure)
},
put: function (url, params, success, failure) {
return apiAxios('PUT', url, params, success, failure)
},
delete: function (url, params, success, failure) {
return apiAxios('DELETE', url, params, success, failure)
}
}
但就是这样,我们还不能再 vue 模板文件中使用这个工具,还需要调整一下 main.js 文件。
调整 main.js 绑定 api/index.js 文件
这次呢,我们没有上来就调整 main.js 文件,因为原始文件就配置得比较好,我就没有刻意的想要调整它。
原始文件如下:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
我们插入以下代码:
// 引用API文件
import api from './api/index.js'
// 将API方法绑定到全局
Vue.prototype.$api = api
也就是讲代码调整为:
import Vue from 'vue'
import App from './App'
import router from './router'
// 引用API文件
import api from './api/index.js'
// 将API方法绑定到全局
Vue.prototype.$api = api
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
好了,这样,我们就可以在项目中使用我们封装的 api 接口调用文件了。
测试一下看看能不能调通。
我们来修改一下 src/page/index.vue 文件,将代码调整为以下代码:
<template>
<div>index page</div>
</template>
<script>
export default {
created () {
this.$api.get('topics', null, r => {
console.log(r)
})
}
}
</script>
好,这里是调用 cnodejs.org 的 topics 列表接口,并且将结果打印出来。
看过axios的官方文档后配置变得简单:
在main.js 做如下配置:
import axios from 'axios'
axios.defaults.baseURL = 'http://10.202.42.24:8080/sf-cloud-web'
Vue.prototype.axios = axios
最后一行是将axios配置到Vue原型中,使用方法为:
this.axios.get('/test/1').then(function (response) {})
可能会遇到下面的报错:
isURLSameOrigin.js?cf95:57 Uncaught (in promise) TypeError: Cannot
read property 'protocol' of undefined
这是因为axios不是VUE插件,不能使用 Vue.use(axios) 方式引用,需要使用上述原型方式引入