axios+promise封装请求以及使用

import axios from 'axios';
/*能发送 ajax 请求的函数模块
包装 axios
函数的返回值是 promise 对象
axios.get()/post()返回的就是 promise 对象
返回自己创建的 promise 对象:
统一处理请求异常
异步返回结果数据, 而不是包含结果数据的 response
*/
export default function ajax(url, data={},method='GET'){
    return new Promise((resolve,reject)=>{
        let promise;
        if(method == 'GET'){
            promise = axios.get(url,{params:data});
        }else{
            promise = axios.post(url,data);
        }
        promise.then(res=>{
            resolve(res.data);
        }).catch(err=>{
           reject(err)
        })
    })
}

使用

import ajax from './ajax';
const BASE_URL = '/api';

//获取热门文章
export const getHotArticle = (limitcount)=> ajax(BASE_URL+'/getHotArticle',{limitcount});
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Axios、Vue和TypeScript的封装Ajax请求示例: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { Vue } from 'vue-property-decorator'; // 定义全局配置 axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.timeout = 5000; // 定义请求拦截器 axios.interceptors.request.use((config: AxiosRequestConfig) => { // 在请求发送前做一些处理,例如添加token等 const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { return Promise.reject(error); }); // 定义响应拦截器 axios.interceptors.response.use((response: AxiosResponse) => { // 在响应返回后做一些处理,例如判断是否登录失效等 const data = response.data; if (data.code === 401) { Vue.prototype.$message.error('登录失效,请重新登录!'); localStorage.removeItem('token'); location.href = '/login'; } return response; }, (error) => { return Promise.reject(error); }); // 定义请求方法 export const ajax = { get<T>(url: string, params?: any): Promise<T> { return axios.get(url, { params }).then((res: AxiosResponse) => res.data); }, post<T>(url: string, data?: any): Promise<T> { return axios.post(url, data).then((res: AxiosResponse) => res.data); }, put<T>(url: string, data?: any): Promise<T> { return axios.put(url, data).then((res: AxiosResponse) => res.data); }, delete<T>(url: string, params?: any): Promise<T> { return axios.delete(url, { params }).then((res: AxiosResponse) => res.data); } }; ``` 使用时可以直接引入`ajax`对象调用相应的请求方法: ```typescript import { ajax } from './ajax'; // 发送GET请求 ajax.get('/users', { page: 1, limit: 10 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); // 发送POST请求 ajax.post('/users', { name: '张三', age: 18 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值