import axios from 'axios'
import qs from 'qs'
import {
getToken
} from '@/utils/auth'
import {Message} from 'element-ui'
import {
getBaseUrl
} from '@/utils/request'
import router from "@/router";
import store from "@/store";
export const request = {
req(req_type, url, data) {
let baseUrl = url.indexOf('http') == 0 ? url : getBaseUrl() + url
let header = {
token: getToken()
}
let Mydata = data
let prom = new Promise((resolve, reject) => {
let req
if (req_type == 'get') {
req = this.get(baseUrl, Mydata, header)
}
if (req_type == 'post') {
req = this.post(baseUrl, data, header)
}
if (req_type == 'del') {
req = this.delete(baseUrl, data, header)
}
if (req_type == 'put') {
req = this.put(baseUrl, data, header)
}
req.then((res) => {
let s_info = this.get_statusInfo(res.status)
if (s_info.run) {
Message.success(s_info.info)
resolve(res.data)
} else {
Message.error(s_info.info)
resolve(s_info)
}
})
})
return prom
},
get(url, data, header) {//查询
return axios.get(url, {
headers: header,
params: data
})
},
post(url, data, header) {//增加
return axios.post(url,
data,
{
headers: header
}
)
},
put(url, data, header) {//修改
return axios.put(url,
data,
{
headers: header
})
},
delete(url, data, header) {//删除
return axios.delete(url,
{
headers: header,
data:data,
})
},
get_statusInfo(status) {
switch (status) {
case 200:
return {
info: '响应成功',
run: true
}
case 201:
return {
info: '资源创建成功',
run: true
}
case 204:
return {
info: '请求已成功,但无返回内容',
run: true
}
case 304:
return {
info: '缓存有效',
run: true
}
case 400:
return {
info: '语义有误,当前请求无法被服务器理解,请求参数错误',
run: false
}
case 401:
return {
info: '当前请求需要用户认证(登录)',
run: false
}
case 403:
return {
info: '用户已认证(登录),但权限不足',
run: false
}
case 404:
return {
info: '请求源未在服务器上被发现',
run: false
}
case 405:
return {
info: '请求方法不能被用于请求相应的资源,如使用PUT方法访问只接受POST方法的API',
run: false
}
case 500:
return {
info: '服务端内部错误',
run: false
}
case 502:
return {
info: '网关错误',
run: false
}
case 504:
return {
info: '网关超时',
run: false
}
}
},
}
RESTful 规范网络层
最新推荐文章于 2024-09-04 20:18:34 发布