我的后端代码有问题,该代码两次执行Axios的请求。我在前端使用react,并且在页面加载时向后端发送一个简单的post请求。请参阅下面的代码以向服务器发送Axios发布请求。
useEffect(() => {
loadPopularDest();
}, [latlong]);
const loadPopularDest = async () => {
await axios
.post("http://localhost:5000/nearbyplaces", { ll: latlong })
.then(async (res) => {
setDestination(res.data);
})
.then(() => {
console.log(destination);
setLoading(false);
})
.catch((err) => {
console.log(err);
});
};
我的后端代码是
router.route("/nearbyplaces").post(async (req, res) => {
console.log(req.body.ll);
const data = [];
const placeDetail = [];
await axios
.get("https://maps.googleapis.com/maps/api/place/nearbysearch/json", {
params: {
key: process.env.GOOGLE_PLACE_API_KEY,
location: req.body.ll,
radius: 20000,
keyword: "popular destinations near me",
},
})
.then((response) => {
console.log(1, "for loop starts here");
response.data.results.forEach((value, i) => {
if (!value.hasOwnProperty("photos")) {
data.push({
name: value.name,
photoUrl: "N/A",
address: value.formatted_address,
location: value.geometry.location,
rating: value.rating,
status: value.business_status,
tags: value.types,
placeId: value.place_id,
});
} else {
data.push({
name: value.name,
photoUrl: `https://maps.googleapis.com/maps/api/place/photo?maxwidth=800&photoreference=${value.photos[0].photo_reference}&key=${process.env.GOOGLE_PLACE_API_KEY}`,
address: value.formatted_address,
location: value.geometry.location,
rating: value.rating,
status: value.business_status,
tags: value.types,
placeId: value.place_id,
});
}
});
console.log(1, "for loop ends here");
})
.then(async () => {
console.log(2, "for loop starts here");
for (let i = 0; i < data.length; i++) {
await axios
.get(
`https://maps.googleapis.com/maps/api/place/details/json?place_id=${data[i].placeId}&fields=name,rating,url,website,formatted_phone_number&key=${process.env.GOOGLE_PLACE_API_KEY}`
)
.then((response) => {
placeDetail.push(response.data.result);
})
.catch((err) => {
console.log(err.response.data);
});
}
console.log(2, "for loop ends here");
})
.catch((err) => {
console.log(err.response);
});
console.log(3, "map starts here");
data.map((value, index) => {
return (value["place_details"] = placeDetail[index]);
});
console.log(3, "map ends here");
console.log(5, data[0]);
res.send(data);
});
将请求发送到服务器时,位于console.log(5, data[0]);
上方的res.send(data)
返回undefined
,并且首先不执行任何for循环,因此loop starts here
和loop ends here
(在屏幕截图中)立即打印在控制台日志中。然后它第二次运行,返回预期结果。所有这些都是从前端发送的单个帖子请求发生的。我在下面添加了控制台日志的屏幕截图。请看看。蓝色框内的日志立即执行,它不等待任何东西,红色框是我无故再次运行时收到的实际输出。
我不确定我哪里错了。任何帮助表示赞赏。谢谢
答案 0 :(得分:0)
您不能将async / await与.then和.catch混合使用。首先,您应该对此进行更改。
您也可以在useEffect中创建此功能
useEffect(() => {
async function loadPopularDest() {
try {
const response = await axios
.post("http://localhost:5000/nearbyplaces", { ll: latlong })
setDestination(response.data);
setLoading(false)
} catch(err) {
console.log(err)
}
}
loadPopularDest();
}, [latlong]);