1

I created a simple web application that fetches data from an API but when I get a response and render the result to ejs file it seems the route is called multiple times

Here are my codes:-

  • index.js file
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";

const app = express();
const port = 3000;

app.get("/", async (req, res) => {
  console.log("Received a GET request to /");
  try {
    const response = await axios.get("https://api.restful-api.dev/objects");
    const result = response.data;
    console.log(
      "Fetched data from API:",
      result[Math.floor(Math.random() * result.length)]
    );
    res.render("index.ejs", {
      data: result[Math.floor(Math.random() * result.length)],
    });
  } catch (error) {
    console.error("Failed to make request:", error.message);
  }
});
app.listen(port, () => {
  console.log(`Server running on port: ${port}`);
});
  • index.ejs file looks like this:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>API - TEST</title>
  </head>
  <body>
    <h1>Welcome to API TEST</h1>
    <h2>Device Name = <%= data.name %></h2>
    <% console.log("Home Page rendered successfully", data.id) %>
  </body>
</html>

And here are my results in the console when I run the web

Console log results

  • I need help knowing what is happening so that it can run more than once.
2
  • 2
    Consider logging the request and/or check the Network tab in your browser. I don't know how express matches path, but there's a chance that one of those requests is for favicon. Commented Jan 24 at 13:30
  • I checked if it is the favicon request using middleware such as follows: // Middleware to log all requests app.use((req, res, next) => { console.log(Received request: ${req.method} ${req.originalUrl}); next(); }); // Middleware to ignore favicon requests app.use((req, res, next) => { if (req.originalUrl === "/favicon.ico") { res.status(204).end(); } else { next(); } }); But it does not show if it is a favicon request Commented Jan 24 at 15:42

1 Answer 1

0

I got the solution, I found the problem was the extension (Torrent Scanner) in my browser, it refreshed the page and caused the duplication of output objects shown in the console...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.