Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
How to handle AJAX resquest with express js

I am trying to handle a ajax request using ExpressJS, but when I click on any anchor tag, the page fully reloads and do not get the hand ajax request on client side.

I need that when I click on any of these links, it should handle by client side using fetch api.

This is html stucture

<header id="main-header">
  <nav>
    <ul>
      <li class="nav-bar"><a data-urlid="" href="/">Home</a></li>
      <li class="nav-bar"><a data-urlid="about" href="/about">About</a></li>
      <li class="nav-bar"><a data-urlid="achievements" href="/achievements">Achievements</a></li>
      <li class="nav-bar"><a data-urlid="gallery" href="/gallery">Gallery</a></li>
      <li class="nav-bar"><a data-urlid="contact" href="/contact">Contact</a></li>
    </ul>
  </nav>  
</header>

This is controller

const home = (req, res) => {
   res.json({message:"success"})
};

This is router for get home page

router.get("/", danceController.home);

Trying to handle ajax request using vanilla js

const navBars = document.querySelectorAll(".nav-bar");

async function head(event) {
  event.preventDefault();
  const url = event.target.dataset.urlid;

    const responseData = await fetch(`/${url}`, {
        method: "GET",
        headers: {"Content-Type":"text/html"}}).then((response) => {
            console.log(response);
        });
    
    // console.log(responseData);
};

for (const navBar of navBars) {
    navBar.addEventListener("click", head)
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try replacing the hrefs with '#', then you'll need to parse the response from JSON before logging it to the console, ie responseData should look something more like this:

const responseData = await fetch(`/${url}`)
                           .then(response => response.json())
                           .then(response => {
                               console.log(response);
                           });

If it's still not working, make sure the expected version of the JS is being loaded by the browser.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda