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

93
Vistas
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 Respuestas
Responde la pregunta

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 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