【问题标题】:Make Multiple Post Requests In Axios在 Axios 中发出多个 post 请求
【发布时间】:2018-06-16 05:33:34
【问题描述】:

我一直在尝试做的是为我的博客文章找到一个端点,然后使用这些数据删除来自 Wordpress 的额外布局标记。我正在使用 Axios 发出请求,然后转换响应选项以修改数据以从响应中的“post_body”对象中删除额外的标记。这适用于单个博客文章,但是当我尝试执行此操作时,我的所有博客文章都会返回 20 个左右博客文章的对象。我想要做的是循环遍历对象转换我的数据,然后向另一个 API 发出发布请求以发布我的博客文章。一旦我的承诺得到解决,我无法弄清楚这是否可能。我能否在 .then 中创建另一个 for 循环并找到我的“post_body”对象并发出发布请求。不确定我是否以正确的方式考虑这个问题。任何帮助深表感谢。

var fieldName = "et_pb";
var regExp = new RegExp("\\[\/?(" + fieldName + ".*?)\\]", "g");

function getBlogPosts() {
  return axios.get(allPosts, {
    transformResponse: axios.defaults.transformResponse.concat(function(data, headers) {
        // use data I passed into the function and the objects from the API
        // pass in data into the function using forEach this will return an array
        data.objects.forEach(function(i) {
            // use the returned array on Objects.key to find the name of the array
            Object.keys(i).forEach(function(k) {
                // if the key equals execute code
                // console.log(k);
                if (k === "post_body") {
                    // fire Regex
                    data[k] = i[k].replace(regExp, '');
                    // console.log(data[k])

                }
            })
        })
        return data;
    })
})
}


axios.all([getBlogPosts()])
 .then(axios.spread(function(blogResponse) {
    console.log(blogResponse.data);
}));

【问题讨论】:

    标签: javascript node.js axios


    【解决方案1】:

    @James 你是对的。您可以链接多个请求,如下所示,或者您可以选择 async 和 await 选项。

     axios.get(...)  // for allPosts
      .then((response) => {
        return axios.get(...); // using response.data
      })
      .then((response) => {
        console.log('Response', response);
      });
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 2021-06-07
      • 2018-04-25
      • 2020-09-17
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2019-09-07
      • 2018-11-05
      相关资源
      最近更新 更多