• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

136
Views
Axios and fetch both in Reactjs are making continuous localhost network request

This is the route code form express backend and MongoDB database and normal call from frontend with fetch("/") it was returning index.html code and on adding fetch("http://localhost:9000") it was returning CORS Error so I added app.use(cors()).

router.get("/", async (req, res) => {
  Journal.find({}, function (err, journals) {
    if (err) {
      res.send("Something went wrong");
    }
    res.json(journals);
  });
});

This is the axios and fetch request made from reactjs frontend, on making fetch and axios call on "/" as at the backend nothing was coming up only index.html code was being returned so therefore I started using "http://localhost:9000" then data was coming but this localhost problem came up.

const [journals, setJournals] = useState([
    { title: "Day 1", content: content_string },
  ]);

  useEffect(() => {
    getJournalData();
  });

  // const getJournalData = async () => {
  //   try {
  //     const res = await fetch("http://localhost:9000/");

  //     const data = await res.json();

  //     setJournals(data);
  //     console.log(data);
  //   } catch (err) {
  //     console.error(err);
  //   }
  // };

  const getJournalData = () => {

    axios
      .get("http://localhost:9000/")
      .then((res) => {
        setJournals(res.data);
      })
      .catch((err) => console.error(err));
  };

This is chrome-dev-tools network tab:

Chrome-dev-tools network tab

Console Content

Console Content

React is working at localhost:3000 Express is working on locahost:9000

proxy:http://localhost:9000 is added in package.json in frontend react app

Please tell me what is goind and how can I fix it. Thankyou

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Without using an array of dependencies, every change will trigger your useEffect to run again.

So every re-render, every changing state will cause you to create another Api calls.

Let's talk about variant useEffect:

useEffect(() => {
  // invoking on every re-render
})

useEffect(() => {
  // invoking on component did mount (once)
}, [])

useEffect(() => {
  // invoking on component did mount and with every change on counter
}, [counter])

So, change your code:

  useEffect(() => {
    getJournalData();
  }, []);
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error