uniapp中向后端发出请求时,第二个请求里的参数是第一个请求中返回的结果,但第二个请求返回数据错误。
created() {
// 在组件创建时获取查询参数
this.pinpai = this.$route.query.name;
http({
url: '/get_rating',
method: 'GET',
data: {
productName: this.pinpai,
}
}).then((res) => {
console.log(res);
this.productId = res.data.productId;
this.score = res.data.rating/2;
});
http({
url: '/show_word_cloud',
method: 'GET',
data:{
productId: this.productId,
}
}).then((res)=>{
console.log(res);
console.log(this.productId);
this.wordList = res.data.list;
console.log(this.wordList);
});
},
问题出在两个HTTP请求是异步执行的,这意味着第二个请求不会等待第一个请求完成就会发送,因此this.productId
可能还没有被设置就已经被使用了。
所以需要确保第二个请求在第一个请求成功后再发送。可以在第一个请求的回调函数中触发第二个请求(将第二个请求封装为一个函数放在methods里,在第一个请求的最后调用),或者使用Promise链来确保它们按顺序执行:
created() {
// 在组件创建时获取查询参数
this.pinpai = this.$route.query.name;
http({
url: '/get_rating',
method: 'GET',
data: {
productName: this.pinpai,
}
}).then((res) => {
console.log(res);
this.productId = res.data.productId;
this.score = res.data.rating / 2;
// 在第一个请求成功后,触发第二个请求
return http({
url: '/show_word_cloud',
method: 'GET',
data: {
productId: this.productId,
}
});
}).then((res) => {
console.log(res);
console.log(this.productId);
this.wordList = res.data.list;
console.log(this.wordList);
}).catch((error) => {
console.error('Error:', error);
});
}