简体   繁体   中英

Axios post request is processed twice by the node server

I have an issue with my backend code which executes a request from Axios twice. I am using react in the frontend and I am sending a simple post request to the backend when the page loads. Please see the code below for the Axios post request to the server.

 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);
      });
  };

and my backend code is

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);
});

When the request is sent to the server, the console.log(5, data[0]); just above the res.send(data) returns undefined and none of the for loops are executed at first so the loop starts here and loop ends here (in the screenshot) is printed in the console log immediately. Then it runs for the second time which returns the expected results. All this is happening for one single post request sent from the frontend. I have added a screenshot of my console log below. Please have a look at it. The log inside the blue color box is executed straight away it doesn't wait for anything and The red box is the actual output that I receive when it runs again for no reason. 我的控制台日志的屏幕截图

I am not sure where I am wrong. Any help is appreciated. Thanks

You can't mix async/await with .then and .catch .First of all, you should change this.

You can also create this function inside the 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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM