jQuery ajax请求已完成,并因Axios而失败

时间:2019-01-15 00:01:30

标签: javascript jquery ajax request axios

我的自定义API设置为:

export default class API {

  static send(verb, resource, raw_params, callback, errcallback) {

    let org_id = window.localStorage._organization_id,
      params = Object.keys(raw_params).reduce(function(o, k) {
      o[k] = raw_params[k];
      return o;
    }, {});

    errcallback = typeof errcallback === 'function' ? errcallback : function() {};

    if (!!org_id && !params.hasOwnProperty('organization_id')) {
      params.organization_id = org_id;
    }

    $.ajax({
      url: URL + '/' + resource,
      type: verb,
      data: params
      xhrFields: { withCredentials: true }
    })
    .done(callback)
    .fail(errcallback);
  }

  static get(resource, params, callback, errcallback) {
    API.send('GET', resource, params, callback, errcallback);
  }

  static post(resource, params, callback, errcallback) {
    API.send('POST', resource, params, callback, errcallback);
  }

  static put(resource, params, callback, errcallback) {
    API.send('PUT', resource, params, callback, errcallback);
  }

  static del(resource, params, callback, errcallback) {
    API.send('DELETE', resource, params, callback, errcallback);
  }
}

然后,我可以通过以下方式从应用程序中的任何文件发出API请求:

API.post('x/y', {params}, res => {
  this.setState(res);
}, (xhr) => {
  const errorMessage = JSON.parse(xhr.responseText).message;
  alert('error', 5000, errorMessage);
}

我正尝试将其替换为axios,并用以下内容替换了$.ajax请求:

axios({
  method: verb,
  url: `${URL}/${resource}`,
  data: params,
  xhrFields: { withCredentials: true }
})
 .then(callback)
 .catch(errcallback)

但是它不会调用响应或错误回调。是否可以通过更新此类来处理该类,还是必须将每个请求替换为axios请求并使用定义的resxhr的axios?

1 个答案:

答案 0 :(得分:1)

Axios默认将数据发布为application/json,而jQuery默认将其发布为application/x-www-form-urlencoded。参见https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

此外,虽然jQuery使用data作为GET请求的查询参数,但Axios将请求正文有效负载和查询参数分别分为dataparams属性。

请记住,要使用Axios替换jQuery,您需要执行以下操作...

const request = {
  method: verb,
  url: `${URL}/${resource}`,
  withCredentials: true      //  are you sure you need this?
}
if (verb === 'GET' || verb === 'DELETE') {
  request.params = params // query params, no request body
} else {
  /// set appropriate request content-type
  request.headers = { 'content-type': 'application/x-www-form-urlencoded' }

  // convert "params" object into request body string
  request.data = Object.entries(params).reduce((data, [key, value]) => {
    data.append(key, value)
    return data
  }, new URLSearchParams())
}
axios(request).then(callback).catch(errcallback)

Object.entries(params).reduce(...)只是从平面对象生成application/x-www-form-urlencoded字符串的简化示例。 Axios本身建议使用qs library

还要记住,Object.entries()在任何版本的Internet Explorer中都不可用。