Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!