第一步:先安装axios
cnpm install axios --save
第二步:src文件夹下新建文件夹http(想叫什么名字自己开心就好),新建2个js(叫啥同样自己开心就好)
api.js(接口)
http.js(封装axios)
http.js
'use strict'
import axios from 'axios'
let apiUrl = '//xxx.xxxx.xxx' // 要请求的后台地址
function checkCode (response) {
let result = {code: 0, data: null}
if (response.data.code !== 0) {
result.code = 'message: ' + response.data.message + 'code:' + response.data.code
} else {
result.data = response.data.data
}
return result
}
封装get,post
export default {
post (url, params) {
params = params || {}
return axios.post(apiUrl + '/' + url, params).then(function (response) {
return checkCode(response)
}).catch(function (error) {
console.log(error)
})
},
get (url, params) {
params = params || {}
return axios.get(apiUrl + '/' + url, {params: params}).then(function (response) {
return checkCode(response)
}).catch(function (error) {
console.log(error)
})
}
}
api.js
接口统一写在api.js
export default {
// 获取 banner
getBanner: 'banners',
// 获取courseList Data
getCourseList: 'course/list',
// 获取单个课程信息
getCourseDetail: 'course',
}
第三步:在需要的页面引入调用
import http from '../http/http'
import api from '../http/api'
getBannerList: async function () {
let that = this
const res = await http.get(api.getBanner)
if (res.code !== 0) {
alert(res.code)
} else {
that.banner = res.data.banners
}
}
———————— END ——————————
网友评论