各种方式包括: GET请求, POST表单请求, POST以JSON方式请求
function getAxiosParameter (url, params, type) {
// 如果 accessToken 是 null, Flag = false
const flag = !!store.state.common.accessToken // 判断 有无令牌的 标记
const accessToken = store.state.common.accessToken // 令牌 本牌
let axiosParam = {} // axios 用来发送 AJAX 的参数
/*
* 判断 accessToken令牌 是否存在
*/
// accessToken 存在
if (flag) {
// get 方式
if (type === 'get') {
axiosParam = {
url: rebuildUrl(url),
method: 'get',
params,
headers: {
Authorization: `Bearer ${accessToken}`
}
}
}
// post 方式
if (type === 'post') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
data: params,
headers: {
Authorization: `Bearer ${accessToken}`
}
}
}
// POST 请求, 以表单形式
if (type === 'postForm') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
headers: {
Authorization: `Bearer ${accessToken}`,
// 以表单方式提交, 必须加一层以下代码
'Content-Type': 'application/x-www-form-urlencoded'
},
data: params
}
}
// POST 请求, 以 JSON 形式发送
if (type === 'postJson') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
headers: {
Authorization: `Bearer ${accessToken}`,
// 以 JSON 形式提交, 必须加一层以下代码
'Content-Type': 'application/json; charset=UTF-8'
},
data: params
}
}
}
// accessToken 不存在
else {
// get 方式
if (type === 'get') {
axiosParam = {
url: rebuildUrl(url),
method: 'get',
params
}
}
// post 方式
if (type === 'post') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
data: params
}
}
// POST 请求, 以表单形式
if (type === 'postForm') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: params
}
}
// POST 请求, 以 JSON 形式发送
if (type === 'postJson') {
axiosParam = {
url: rebuildUrl(url),
method: 'post',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
data: params
}
}
}
return axiosParam
}
/*
* 将 axiosParam 设置 axios发送AJAX请求 用的参数 传给 getAxiosParameter
*/
// GET 请求
export const httpGet = (url, params) => axios(getAxiosParameter(url, params, 'get'))
.then(({ data }) => {
console.log(`httpGet: ${url}`, data)
return data
})
.catch((error) => {
console.log(`httpGet: ${url}_ERROR`, error)
})
// POST 请求
export const httpPost = (url, params) => axios(getAxiosParameter(url, params, 'post'))
.then(({ data }) => {
console.log(`httpPost: ${url}`, data)
return data
})
.catch((error) => {
console.log(`httpPost: ${url}_ERROR`, error)
})
// POST 请求, 以表单形式
export const httpPostForm = (url, params) => axios(getAxiosParameter(url, params, 'postForm'))
.then(({ data }) => {
console.log(`httpPostForm: ${url}`, data)
return data
})
.catch((error) => {
if (typeof (error.response) !== 'undefined') {
return error.response.data
}
return error
})
// POST 请求, 以 Json 形式
export const httpPostJson = (url, params) => axios(getAxiosParameter(url, params, 'postJson'))
.then(({ data }) => {
console.log(`httpPostJson: ${url}`, data)
return data
})
.catch((error) => {
console.log(`httpPostJson: ${url}_ERROR`, error)
})