【问题标题】:Axios post request is processed twice by the node serveraxios post请求被节点服务器处理两次
【发布时间】: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 hereloop ends here(在屏幕截图中)立即打印在控制台日志中。然后它第二次运行,返回预期结果。所有这一切都发生在从前端发送的一个帖子请求中。我在下面添加了我的控制台日志的屏幕截图。请看一看。蓝色框内的日志会立即执行,它不会等待任何内容,红色框是我在无缘无故再次运行时收到的实际输出。

我不确定我错在哪里。任何帮助表示赞赏。谢谢

【问题讨论】:

    标签: node.js reactjs axios


    【解决方案1】:

    您不能将 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]);
    

    【讨论】:

    • 嗨@gabriel Tiso,它不工作,它提供与以前相同的输出。此外,我尝试不使用 async 并在 .then 块中等待,但它给了我相同的输出。此外,您提到我不能将 async 和 await 混合使用,还有其他方法可以实现吗?请让我知道,与此同时,我将尝试使用 Promises 并看看它是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2016-09-29
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多