【问题标题】:Convert Ajax jquery to Axios将 Ajax jQuery 转换为 Axios
【发布时间】:2019-12-17 15:28:40
【问题描述】:

我的页面使用 ajax 请求,但我们正在将它们移至 axios。 我已更改代码,但响应数据为空。

这是我的旧代码:

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);
        }
    });
}

现在改成 axios 后是:

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; })
}

我做错了什么。是我作为参数传递的数据吗?

这里使用了查询:

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));
            }
        );
    };
}

【问题讨论】:

  • 不应该是 then 和 catch 作为正常的 Promise 吗?
  • 你能解释一下吗

标签: jquery ajax reactjs axios


【解决方案1】:

axios 请求方法如get 接受两个参数,请求url 和request config 对象。在配置对象中,您将需要 data 键来设置请求正文(您的 params)和 headers 键(您的内容类型)。

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

由于 axios 返回一个 Promise,并且上述函数返回 axios 请求,因此您可以使用 .then.catch 链接您的“成功”和“失败”逻辑,而不是将它们作为回调传递。

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

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2016-07-18
    • 1970-01-01
    • 2018-02-16
    • 2013-12-07
    • 2019-01-25
    相关资源
    最近更新 更多