简体   繁体   English

在Axios中发出多个发布请求

[英]Make Multiple Post Requests In Axios

What I have been trying to do is hit an endpoint for my blog posts and then with this data remove extra layout markup that came in from Wordpress. 我一直想做的事情是为我的博客文章打一个端点,然后使用此数据删除Wordpress带来的额外布局标记。 I am using Axios to make the request and then transform response option in order to modify the data to remove the extra markup from the "post_body" object inside my response. 我使用Axios发出请求,然后转换响应选项,以便修改数据以从响应中的“ post_body”对象中删除多余的标记。 This works on a single blog post but when I try to do this all my blog blog posts it return an object of 20 or so blog posts. 这对单个博客文章有效,但是当我尝试执行所有我的博客博客文章时,它将返回20个左右博客文章的对象。 What I want to do is loop through the objects transform my data and then make a post request back to another API to publish my blog post. 我要做的是遍历对象,转换数据,然后向另一个API发出发布请求,以发布我的博客文章。 What I can't figure out if this will be possible once my promise is resolved. 一旦我的诺言得到解决,我不知道这是否有可能。 Would I be able to create another for loop within the .then and find my "post_body" object and make the post request. 我能否在.then中创建另一个for循环并找到我的“ post_body”对象并发出发布请求。 Not sure if I am thinking about this in the right way or not. 不知道我是否在考虑正确的方法。 Any help is much appreciated. 任何帮助深表感谢。

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);
}));

@James you are correct . @詹姆斯,你是正确的。 you can chain multiple requests as below or you can go for asyn and await options . 您可以按以下方式链接多个请求,也可以使用asyn和await选项。

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

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

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