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