【发布时间】:2020-09-03 22:37:11
【问题描述】:
我的后端代码执行两次来自 Axios 的请求时遇到问题。我在前端使用反应,当页面加载时我向后端发送一个简单的发布请求。向服务器发送 Axios 的 post 请求请参见下面的代码。
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);
});
当请求发送到服务器时,res.send(data) 正上方的 console.log(5, data[0]); 返回 undefined 并且一开始没有执行任何 for 循环,因此 loop starts here 和 loop ends here(在屏幕截图中)立即打印在控制台日志中。然后它第二次运行,返回预期结果。所有这一切都发生在从前端发送的一个帖子请求中。我在下面添加了我的控制台日志的屏幕截图。请看一看。蓝色框内的日志会立即执行,它不会等待任何内容,红色框是我在无缘无故再次运行时收到的实际输出。
我不确定我错在哪里。任何帮助表示赞赏。谢谢
【问题讨论】: