【发布时间】: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