【问题标题】:how to send data from ajax to backend express如何将数据从ajax发送到后端快递
【发布时间】:2022-01-30 04:06:14
【问题描述】:

我想使用 nodejs 将数据从前端发送到后端 nodejs,我该怎么做?

这是我的 ajax 代码


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();

})

后端代码是


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

    }
}

module.exports = newsController;

数据应该通过 get 路由发送到后端,以便我可以在 html 页面上呈现数据。

【问题讨论】:

  • the data should be send to backend on get route so that I can render the data on html page. 为什么不直接在浏览器中生成页面,或者为什么不在服务器上请求数据。在客户端请求并将其发送到服务器以生成 html 页面并没有多大意义。

标签: javascript node.js ajax


【解决方案1】:

您可以尝试此代码,但我从此示例中删除了 userService 和 userRepo 层,它们过多。

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

或者你可以使用官方文档中的快递。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
相关资源
最近更新 更多