如何实现嵌套式请求两个API

使用axios请求两个API,且其中一个依赖于第一个API的返回值进行请求

Posted by BY on July 12, 2023

背景说明

  • 有时候会存在服务数据不完善,需要聚合的情况,后端不便于做独立的聚合操作API。这种时候就可能存在需要在前端做多次请求来获取数据做聚合展示

示例代码

          let loginToken = '';// 存储生成的token,用于第二次请求API时追加到对象中
          this.$axios.post('api/app/...', JSON.stringify(data))
            .then(response1 => {// 第一个请求API的返回体
              // debugger
              //const data2 = { /* data for endpoint 2, using response1 */ }
              if (response1.status === 200 || response1.status === 204) {

                loginToken = response1.data.token;
                const response1Data = {
                  userName: response1.data.userName
                }
                // 将第一个API的返回数据传递给第二个API并请求
                return this.$axios.post('.../UserDetail', JSON.stringify(response1Data))
              } else {
                this.$message.error(response1.statusText);
              }
            })
            .then(response2 => {// 第二个请求API的返回体
              // debugger
              // handle success
              if (response2.status === 200 || response2.status === 204) {
                response2.data.token = loginToken;// 追加token属性到对象中,再进行commit
                this.$store.commit('setLogin', response2.data);

                this.$store.commit('mqttOption', {
                  clientId: `${this.ruleForm.username}_${timestamp}`,
                  username: this.ruleForm.username,
                  password: md5(this.ruleForm.password)
                });

                this.$message.success('登陆成功');
                //登陆成功,跳到index页面
                this.$router.push({
                  name: 'index'
                })
              } else {
                this.$message.error(response2.statusText);
              }
            })
            .catch(error => {
              // debugger
              // handle error
              console.log('error: ' + JSON.stringify(error));
              this.$message({
                showClose: true,
                message: '登录失败,请检查账户密码是否正确!',
                type: 'error'
              })
              console.log('登陆异常.')
              this.loading = false
            })