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

87
Views
how to send data from ajax to backend express

I want to send the data from frontend to backend nodejs using nodejs, how do i do that?

here is my ajax code


const news = document.getElementById("news");
news.addEventListener('click',(e) =>{
    e.preventDefault();
    let data = " ";
    const xhttp = new XMLHttpRequest();
        const url = 'https://newsapi.org/v2/top-headlines?category=technology&apiKey=<api_key>';

        xhttp.open('GET',url, true);
        xhttp.onreadystatechange = function(){
            if(this.status === 200 && this.readyState === 4){
                let data = JSON.parse(this.response);
            }
        }

        xhttp.send();

})

and the backend code is


const newsController = () => {
    return{
        getNews(req, res){
          console.log(res)
        },
        

    }
}

module.exports = newsController;

the data should be send to backend on get route so that I can render the data on html page.

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

0

You can trying this code, but layers userService and userRepo I'm removing from this example, they're excessive.

App.js

import express from "express";
import { userRouter } from "./routes/userRoutes.js";

const PORT = process.env.PORT || 8080;
const app = express();

app.use(express.json());
app.use('/api', userRouter);

app.listen(PORT, () => console.log(`http://localhost:${PORT}`));

userRoutes.js

import userController from "../controller/userController.js";
import { Router } from "express";
const router = new Router();

router.get('/users', userController.getUsers.bind(userController));

export {router as userRouter}

userController.js

import userService from "../service/userService.js";

class UserController {

    constructor(userService) {
        this.userService = userService;
    }
           
    async getUsers(req, res) {
        res.json(await this.userService.getUsers());
    }

}

export default new UserController(userService);

Or you may using from official documentation express.

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!