weixin_33681778 2019-08-09 22:11 采纳率: 0%
浏览 251

将Ajax jQuery转换为Axios

My page was using ajax requests but we are moving them to axios. I have changed the code but the response data is coming empty.

This was my old code:

export function getMList(params, onSuccess, onFailure) {
    const url = `/admin/list`;
    const {
        name,
        type
    } = params;

    return $.ajax({
        type: 'GET',
        url,
        processData: false,
        contentType: 'application/x-www-form-urlencoded',
        data: $.param({name, type}),
        success: (response) => {
            onSuccess(response);
        },
        error: (error) => {
            onFailure(error);
        }
    });
}

Now after changing it to axios it is :

export function getMList(params) {
    const {
        name,
        type
    } = params;

    axios.get(`/admin/list`,params,{
        headers : {'contentType': 'application/x-www-form-urlencoded' 
        }
    }).then((res) => { return res; }, (err) => { return err; })
}

What am I doing wrong. Is it the data I am passing as params ?

The query is used here :

export function getMList(id, name, type) {
    const encodedName = encodeURI(name);

    return (dispatch) => {
        dispatch(requestMList({ id }));
        admin.getMList({ name: encodedName, type },
            (response) => {
                dispatch(receivedMList({ id, name, type, response }));
            },
            (error) => {
                dispatch(failedMList(id));
            }
        );
    };
}
  • 写回答

1条回答 默认 最新

  • weixin_33724570 2019-08-09 23:48
    关注

    axios request methods such as get accepts two parameters, the request url and a request config object. Inside the config object you will need the data key to set the request body (your params) and the headers key (your content-type).

    export const getMList = (params) => {
      return axios.get('/admin/list', {
        data: params,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
    }
    

    Since axios returns a Promise, and the above function returns the axios request, you can then chain your "success" and "failure" logic using .then and .catch rather than passing them in as callbacks.

    admin
      .getMList({ name: encodedName, type })
      .then((response) => dispatch(receivedMList({ id, name, type, response })))
      .catch((err) => dispatch(failedMList(id, err)));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献