axios

129 阅读7分钟

1、json-server:这个包可以快速搭建http服务,使用axios的时候需要向服务端发送请求。
JSON-Server是一个用于模拟RESTful API的工具,该服务器可以处理GET、POST、PUT、DELETE等HTTP请求,并相应地操作JSON数据。
使用JSON-Server,可以快速搭建一个API服务器,用于开发和测试前端应用程序,而无需实际的后端服务器,只需要定义一个包含你希望的数据的JSON文件,然后在本地启动JSON-Serve,它将根据JSON文件提供相应的API接口

2、axios的基本使用

<script>
    // 此时使用的是json-server
    // 发送 GET 请求
    btns[0].onclick = function () {
        axios({
            // 请求类型
            method:'GET',
            // 请求地址 URL
            // 指向id为2的posts
            url:'http://localhost:3000/posts/2'
        }).then((response)=>{
            // 返回的是一个Promise对象,所以使用 then 方法来指定处理的回调
            console.log(response);
        })
    }

    // 发送 POST 请求
    // 添加一篇新的文章
    btns[1].onclick = function () {
        axios({
            // 请求类型
            method:'POST',
            // 请求地址 URL
            url:'http://localhost:3000/posts',
            // 设置请求体
            data:{
                title:'sunny',
                author:'张三'
            }
        }).then((response)=>{
            // 返回的是一个Promise对象,所以使用 then 方法来指定处理的回调
            console.log(response);
        })
    }

    // 发送 PUT 请求,需要传递id
    // 更新数据
    btns[2].onclick = function () {
        axios({
            // 请求类型
            method:'PUT',
            // 请求地址 URL
            // 指向id为3的posts
            url:'http://localhost:3000/posts/3',
            data:{
                title:'sunny',
                author:'李四'
            }
        }).then((response)=>{
            // 返回的是一个Promise对象,所以使用 then 方法来指定处理的回调
            console.log(response);
        })
    } 

    // 删除数据
    // 发送 DELETE 请求,不需要设置请求体的,传递 id 即可
    btns[3].onclick = function () {
        axios({
            // 请求类型
            method:'DELETE',
            // 请求地址 URL
            // 指向id为3的posts
            url:'http://localhost:3000/posts/3',
        }).then((response)=>{
            // 返回的是一个Promise对象,所以使用 then 方法来指定处理的回调
            console.log(response);
        })
    } 
</script>

3、axios其他方式发送请求

<script>
    // 使用 axios 的一些其他方法来发送 http 请求
    // 不仅可以使用axios函数来发送请求,还可以使用axios对象身上的方法来发送请求
    btn[0].onclick = function () {
        // axios.request 来发送请求
        // 发送 GET 请求
        axios.request({
            method:'GET',
            url:'http://localhost:3000/comments',
            // 返回的结果也是一个Promise对象,使用 then 语法
        }).then((response)=>{
            console.log(response);
        })
    }

    // 发送 POST 请求
    // 还可以发送 DELETE、PUT、PATCH等
    btn[1].onclick = function () {
        // 第一个参数是 URL 地址
        // 第二个参数是data请求体
        // 第三个参数是config(二、三都是可选的)
        axios.post('http://localhost:3000/comoents',{
            // 第二个参数是添加的数据
            "body":"xdddw",
            "postId":2
        }).then((reponse)=>{
            console.log(response);
        })
    }
</script>

4、axios配置对象详细说明

<script>
   const a = {
        url: '/user',

        method: 'get', // default

        // 设定 URL 的基础结构
        baseURL: 'https://some-domain.com/api/',

        // 可以对请求的数据进行处理,将处理完的结果再传给服务器
        transformRequest: [function (data, headers) {
        // Do whatever you want to transform the data
            return data;
        }],

        // 对响应的结果作出处理
        transformResponse: [function (data) {
        // Do whatever you want to transform the data
            return data;
        }],

        // headers:对请求头信息做配置
        // 在有些项目中,进行身份校验的时候,要求在请求头信息中加入标识
        // `headers` are custom headers to be sent
        headers: {'X-Requested-With': 'XMLHttpRequest'},

        // params:来设定 URL 参数
        params: {
            ID: 12345
        },

        // paramsSerializer:参数序列化的配置项
        //  使用的较少,作用:对请求的参数做一个序列化,转换成一个字符串
        paramsSerializer: {
            //Custom encoder function which sends key/value pairs in an iterative fashion.
            encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, 

            // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
            serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 

            //Configuration for formatting array indexes in the params. 
            indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).    
        },

        // data:请求体设置,一种是对象形式(传递的时候axios会转为JSON格式字符串),一种是字符串格式
        data: {
            firstName: 'Fred'
        },
        data: 'Country=Brasil&City=Belo Horizonte',

        // 超时时间,如果超过这个时间,请求就会取消,单位毫秒
        timeout: 1000, // default is `0` (no timeout)

        // 跨域请求时对cookie的携带做设置,携带or不携带
        withCredentials: false, // default

        // 对请求的适配器做设置
        adapter: function (config) {
            /* ... */
        },

        // 设置用户名和密码的
        // 使用比较少
        auth: {
            username: 'janedoe',
            password: 's00pers3cret'
        },

        // 对响应体结果的格式做设置
        responseType: 'json', // default

        // UTF-8 字符集设置
        responseEncoding: 'utf8', // default

        // 跨域
        xsrfCookieName: 'XSRF-TOKEN', // default

        xsrfHeaderName: 'X-XSRF-TOKEN', // default

        // 安全设置
        withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),

        // 上传的时候一些回调
        onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
            // Do whatever you want with the Axios progress event
        },

        // 下载的时候做的一些回调
        onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
            // Do whatever you want with the Axios progress event
        },

        maxContentLength: 2000,

        maxBodyLength: 2000,

        // 对响应结果的成功做设置
        validateStatus: function (status) {
            return status >= 200 && status < 300; // default
        },

        maxRedirects: 21, // default
        beforeRedirect: (options, { headers }) => {
            if (options.hostname === "example.com") {
                options.auth = "user:password";
            }
        },

        socketPath: null, // default

        transport: undefined, // default

        httpAgent: new http.Agent({ keepAlive: true }),
        httpsAgent: new https.Agent({ keepAlive: true }),

        proxy: {
            protocol: 'https',
            host: '127.0.0.1',
            // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
            port: 9000,
            auth: {
                username: 'mikeymike',
                password: 'rapunz3l'
            }
        },

        cancelToken: new CancelToken(function (cancel) {
        }),

        signal: new AbortController().signal,

        decompress: true, // default

        insecureHTTPParser: undefined, // default

        transitional: {
            silentJSONParsing: true, // default value for the current Axios version

            // try to parse the response string as JSON even if `responseType` is not 'json'
            forcedJSONParsing: true,

            // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
            clarifyTimeoutError: false,
        },

        env: {
            // The FormData class to be used to automatically serialize the payload into a FormData object
            FormData: window?.FormData || global?.FormData
        },

        formSerializer: {
            visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
            dots: boolean; // use dots instead of brackets format
            metaTokens: boolean; // keep special endings like {} in parameter key
            indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
        },

        // http adapter only (node.js)
        maxRate: [
                100 * 1024, // 100KB/s upload limit,
                100 * 1024  // 100KB/s download limit
            ]
        }
</script>

5、axios的默认配置(可以把一些重复性的操作设为默认,简化代码)
<script>
    // 设置 axios 的默认配置
    // 设置默认请求类型为 GET
    axios.defaults.method = 'GET'
    // 设置基础地址
    axios.defaults.baseURL = 'http://localhost:3000'
    // 还可以设置默认的请求头信息,默认的参数
</script>

6、axios创建实例对象发送请求
<script>
    // 创建 axios 实例对象
    // 这样做的好处是可以向多个服务器发送 axios 请求
    // 这里 abc 与 axios 对象的功能几近是一样的
    const abc = axios.create({
        baseURL:'https://api.apiopen.top',
        timeout:'2000'
    })

    // 发送请求
    abc({
        method:'POST',
        url:'/getJoke'
    }).then((response)=>{
        console.log(response);
    })

    // 借助封装好的方法去发送请求
    // 只打印响应体
    abc.get('/getJoke').then((response)=>{
        console.log(response.data);
    })
</script>

7、axios拦截器

<script>
    // 与 Promise 相关
    // axios 拦截器:就是一些函数
    // 请求拦截器:在发送请求之前,借助一些函数来对请求的参数和内容做处理和检测
    // 响应拦截器:当服务器返回结果之前,对结果进行预处理
    // axios 的 github 仓库里面设置了例子

    // 设置一个请求拦截器
    // 当有多个请求拦截器时,先执行最后一个
    // use 里面设置了两个回调
    // 这里面的 config 就是配置对象,可以对 config 进行处理
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        // 修改 config 里面的参数
        config.params = {a:100}
        console.log('请求拦截器成功');
        return config;
    }, function (error) {
        console.log('请求拦截器失败');
        // Do something with request error
        return Promise.reject(error);
    });

    // 设置一个响应拦截器
    // 当有多个响应拦截器时,先执行第一个,按顺序执行
    // 这里面的 response 是默认的响应结果
    axios.interceptors.response.use(function (response) {
        console.log('响应拦截器成功');
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
        // 处理 response 里面的某部分
        return response.data
    }, function (error) {
        console.log('响应拦截器成功');
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
    });

    // 发送请求
    axios({
        method:'GET',
        URL:'http://localhost:3000/posts'
    }).then((response)=>{
        console.log(response);
    }).catch((reason)=>{
        console.log('自定义函数失败的回调');
    })
</script>

8、axios取消请求

<script>
    // axios 取消请求
    // 2、声明一个全局变量
    let cancel = null;
    btns[0].onclick = function () {
        axios({
            method:'GET',
            url:'http://localhost:3000/posts',
            // 1、首先要添加配置对象的属性
            cancelToken:new axios.cancelToken(function (c) {
                // 3、将 c 的值赋值给 cancel
                cancel = c
            })
        }).then((response)=>{
            console.log(response);
        })
    }
    // 绑定第二个事件取消请求
    btns[1].onclick = function (){
        // 执行 cancel 函数
        cancel()
    }
</script>
// 用户点击很多次来发送请求,那么就会给服务器造成压力
// 解决
<script>
    // axios 取消请求
    // 2、声明一个全局变量
    let cancel = null;
    btns[0].onclick = function () {
        // 检测上一次请求是否完成
        if(cancel !== null){
            // 取消上一次的请求
            cancel()
        }
        axios({
            method:'GET',
            url:'http://localhost:3000/posts',
            // 1、首先要添加配置对象的属性
            cancelToken:new axios.cancelToken(function (c) {
                // 3、将 c 的值赋值给 cancel
                cancel = c
            })
        }).then((response)=>{
            console.log(response);
            // 请求完成之后,将cancel的值初始化
            cancel = null
        })
    }
    // 绑定第二个事件取消请求
    btns[1].onclick = function (){
        // 执行 cancel 函数
        cancel()
    }
</script>