vueパッケージaxios
4171 ワード
1、まずaxiosをインストールする
2、パッケージjs
書き終わったらmain.jsに導入
ここで終わりです....どうやって呼び出すの?
バックエンドコード
2、パッケージjs
import axios from 'axios'
var root = 'http://127.0.0.1:8081'
axios.defaults.headers.post['content-Type'] = 'application/json;charset=UTF-8';
// 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
}
/** headers, header */
function setHeaders(headers) {
axios.defaults.headers.school_id = headers.school_id;
axios.defaults.headers.token = headers.token;
}
// success failure ,
function apiAxios(method, url, headers, params, success, failure) {
if (headers) {
headers = filterNull(headers);
setHeaders(headers)
}
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.error_code === 1000) {
if (success) {
// success(data)
success(res.data)
}
} else {
failure(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, headers, params, success, failure) {
return apiAxios('GET', url, headers, params, success, failure)
},
post: function (url, headers, params, success, failure) {
return apiAxios('POST', url, headers, params, success, failure)
},
put: function (url, headers, params, success, failure) {
return apiAxios('PUT', url, headers, params, success, failure)
},
delete: function (url, headers, params, success, failure) {
return apiAxios('DELETE', url, headers, params, success, failure)
}
}
書き終わったらmain.jsに導入
ここで終わりです....どうやって呼び出すの?
バックエンドコード