简体   繁体   English

jQuery Ajax请求已完成,但Axios失败

[英]Jquery ajax request done and fail with Axios

I have a custom API setup as: 我有一个自定义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);
  }
}

Then I can make an API request from any file in my application as: 然后,我可以从应用程序中的任何文件发出API请求,如下所示:

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

I am trying to replace this with axios and I replaced the $.ajax request with the following: 我试图用axios替换它,并用以下内容替换$.ajax请求:

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

But it doesn't call the response or error callback. 但是它不会调用响应或错误回调。 Is there a way I can update this class to handle that or do I have to replace every request with an axios request instead and use the axios defined res and xhr ? 有没有一种方法可以更新此类以处理该类,还是必须将每个请求替换为axios请求并使用axios定义的resxhr

Axios by default posts data as application/json whereas jQuery defaults to application/x-www-form-urlencoded . 默认情况下,Axios将数据发布为application/json而jQuery默认为application/x-www-form-urlencoded See https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format . 参见https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

Also, while jQuery uses data as the query parameters for GET requests, Axios separates request body payloads and query parameters into the data and params properties, respectively. 同样,虽然jQuery使用data作为GET请求的查询参数,但Axios分别将请求正文有效负载和查询参数分为dataparams属性。

With that in mind, to drop-in-replace jQuery with Axios, you would need to do the following... 考虑到这一点,要使用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)

The Object.entries(params).reduce(...) thing is just a simplified example of producing an application/x-www-form-urlencoded string from a flat object. Object.entries(params).reduce(...)只是从平面对象生成application/x-www-form-urlencoded字符串的简化示例。 Axios itself recommends the qs library . Axios本身建议使用qs库

Also keep in mind that Object.entries() is not available in any version of Internet Explorer. 还要记住, Object.entries()在任何版本的Internet Explorer中都不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM