【Vue Shop】API请求构建

Fork Me On Github

API请求构建

本次使用 axios 作为网络请求底层

 
npm i axios
1

请求头

post 数据为json格式

接受json格式的数据

   
Content-Type: application/vnd.api+json

Accept: application/json
123

GET 请求

ts
            
export function fetch<T>(url: string, params = {}): Promise<T> {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params,
        }).then((response) => {
            resolve(response.data)
        }).catch((err) => {
            reject(err)
        })
    })
}
123456789101112

POST 请求

ts
          
export function post<T>(url: string, data = {}): Promise<T> {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then((response) => {
                resolve(response.data)
            }, (err) => {
                reject(err)
            })
    })
}
12345678910

DELETE 请求

ts
           
export function deleteRequest<T>(url: string): Promise<T> {
    return new Promise<T>((resolve, reject) => {
        axios.delete(url)
            .then((response) => {
                resolve(response.data)
            }, (err) => {
                reject(err)
            })
    })
}
1234567891011
点击查看全文
0 265 0