• axios简单使用


    介绍

    我在使用vue的时候使用到了axios,vue 1.0的版本作者推荐使用vue-resource,到了vue 2.0作者建议使用axios,此篇文章只是我在使用axios时候做的笔记,我遇到的一个些坑,如需查看axios详细api的使用文档请看官网https://www.npmjs.com/package/axios

    Get,Delete,Head简单使用

    get(url: string, config?: AxiosRequestConfig): AxiosPromise;
    delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
    head(url: string, config?: AxiosRequestConfig): AxiosPromise

    这三个方法使用方式属于同一类型,Get方法使用示例如下,其他两个同理

     1 // Make a request for a user with a given ID 
     2 axios.get('/user?ID=12345')
     3   .then(function (response) {
     4     console.log(response);
     5   })
     6   .catch(function (error) {
     7     console.log(error);
     8   });
     9  
    10 // Optionally the request above could also be done as 
    11 axios.get('/user', {
    12     params: {
    13       ID: 12345
    14     }
    15   })
    16   .then(function (response) {
    17     console.log(response);
    18   })
    19   .catch(function (error) {
    20     console.log(error);
    21   });

    Post,Put,Patch简单使用

    1 post(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;
    2 put(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;
    3 patch(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise;

    这三个方法使用方式属于同一类型,Post方法使用示例如下,其他两个同理:

     axios.post(url,JSON.stringify(requestdata),{ headers: { 'Content-Type': 'application/json' },data:{}}).then(function (response) {
         console.log(response);
       })
       .catch(function (error) {
         console.log(error);
       });

    这里需要注意的是data:{} 必须添加这个,即使data里面是空,headers是添加http表头的

    axios post上传表单的时候,需要注意的是 headers: { 'Content-Type': 'application/x-www-form-urlencoded'  这个值,否则后台是接收不到值的

     var formData = new FormData();
     formData.append('file', this.$refs.fileData['files'][0], this.$refs.fileData['files'][0].name);
     formData.append('applicationName', this.form.applicationName);
    
     axios.post(url, formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
                        .then(response => {
                            console.log(res.data)
                        })
                        .catch(error => {
                            console.log(error)
                        });
  • 相关阅读:
    python 获取当前时间
    PHP基础
    python 编码
    系统分区表 MBR GPT
    python mysql like查询的写法
    JSP JavaBean
    jsp MVC
    python 正则例子
    Java版A星算法
    linux 部署subversion独立服务器
  • 原文地址:https://www.cnblogs.com/fqybzhangji/p/7295292.html
Copyright © 2020-2023  润新知