[英]How to make a chain of requests with axios in js
I struggle with making 3 requests in such a way: I need an info from the first to send next two.我很难以这种方式提出 3 个请求:我需要第一个的信息来发送接下来的两个。
const order_id = this.$route.params.order_id
axios
.get(`/api/v1/orders/${order_id}/`)
.then(response => {
this.order_main_info = response.data
})
.catch(err => {
// console.log(err)
})
In this.order_main_info subject and worktype are stored.在this.order_main_info中存储主题和工作类型。
I need to send requests:我需要发送请求:
first_response = axios.get(`/api/v1/subjects/${this.order_main_info.subject}/`)
second_response = axios.get(`/api/v1/worktype/${this.order_main_info.worktype}/`)
and write results into this.order_main_info like this:并将结果写入this.order_main_info ,如下所示:
this.order_main_info["worktype_name"] = first_response.data.name
this.order_main_info["subject_name"] = second_response.data.name
I've tried a lot of times but still something wrong with syntax.我已经尝试了很多次,但语法仍然有问题。 Other questions on stackoverflow did not help me ((
关于stackoverflow的其他问题对我没有帮助((
I've tried both async/await and我已经尝试过 async/await 和
.get ()
.then (
response => { axios.all() }
)
Have you tried nested axios calls?您是否尝试过嵌套的 axios 调用?
Sample:样本:
axios.get('https://jsonplaceholder.typicode.com/posts').then((response) => { const posts = response.data; axios.get(`https://jsonplaceholder.typicode.com/posts/${posts[0].id}`).then((response => { console.log(response.data) })) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js"></script>
There were some troubles with axios spread construction. axios spread 构造存在一些问题。
the final working code looks like:最终的工作代码如下所示:
const order_id = this.$route.params.order_id
axios
.get(`/api/v1/orders/${order_id}/`)
.then(response => {
this.order_main_info = response.data
const subject_id = response.data.subject
const worktype_id = response.data.work_type
axios.all([axios.get(`/api/v1/subjects/${subject_id}`),
axios.get(`/api/v1/worktypes/${worktype_id}`)
])
.then (
axios.spread((firstResponse, secondResponse) => {
this.order_main_info["subject_name"] = firstResponse.data.name
this.order_main_info["worktype_name"]= secondResponse.data.name
}))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.