如何将 superagent 翻译成 axios?

How to translate superagent to axios?

我有一些为 superagent 工作的上传。它涉及 posting 到 cloudinary 的 api。我的问题是如何使用 axios 做同样的事情。我不确定 superagent.attachsuperagent.field 在 axios 中有什么关系。

基本上,当我发出 post 请求时,我需要将所有这些字段附加到请求中,否则我会收到错误的请求,我想在 axios 中执行此操作,而不是 superagent,因为我正在切换到 axios。

以下是所有参数:

    const image = files[0];

    const cloudName = 'tbaustin';
    const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;

    const timestamp = Date.now()/1000;
    const uploadPreset = 'cnh7rzwp';

    const paramsStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}ORor-6scjYwQGpNBvMW2HGMkc8k`;

    const signature = sha1(paramsStr);
    const params = {
      'api_key': '177287448318217',
      'timestamp': timestamp,
      'upload_preset': uploadPreset,
      'signature': signature
    }

这是超级代理 post 请求:

let uploadRequest = superagent.post(url)
    uploadRequest.attach('file', image);

    Object.keys(params).forEach((key) => {
      uploadRequest.field(key, params[key]);
    });

    uploadRequest.end((err, res) => {
      if(err) {
        alert(err);
        return
      }

您需要按如下方式使用 FromData:

  var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  var fd = new FormData();
  fd.append("upload_preset", unsignedUploadPreset);
  fd.append("tags", "browser_upload"); // Optional - add tag for image admin in Cloudinary
  fd.append("signature", signature);
  fd.append("file", file);
  const config = {
    headers: { "X-Requested-With": "XMLHttpRequest" },
    onUploadProgress: function(progressEvent) {
      // Do something with the native progress event
    }
  };
  axios.post(url, fd, config)
            .then(function (res) {
              // File uploaded successfully
              console.log(res.data);
            })
            .catch(function (err) {
              console.error('err', err);
            });

查看完整示例here