【问题标题】:How to translate superagent to axios?如何将superagent翻译成axios?
【发布时间】:2017-12-26 11:56:57
【问题描述】:

我为 superagent 上传了一些文件。它涉及发布到云计算的 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
    }

这是超级代理发布请求:

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
      }

【问题讨论】:

    标签: axios superagent


    【解决方案1】:

    您需要按如下方式使用 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

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 2019-03-04
      • 2011-03-09
      • 2011-09-05
      • 2018-06-13
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多