admin管理员组文章数量:815052
如何通过前端ajax通过post方法发送的node.js在服务器端检索数据?
我最近开始使用快速框架学习node.js,偶然发现了一个问题。
我正在尝试一个简单的查询搜索网络应用,我想传递一条数据(一个名为all的布尔值)
从前端普通javascript通过ajax到服务器端,但使用当前代码
我到目前为止已经写过,看来我的数据没有传递到服务器端,
我全部植入的3 console.log返回{}。
我在这里想念什么概念?我究竟做错了什么?
如果需要任何其他信息,请让我知道,谢谢。
前端js
window.onload=function(){
console.log("window loaded");
const xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:3000/search", true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status==200){
// code later to be implemented
}
}
let searchConditions = new SearchConditions(true);
console.log('data='+JSON.stringify(searchConditions));
xhr.send('data='+JSON.stringify(searchConditions));
}
class SearchConditions{
constructor(all) {
this.all = all;
}
}
后端node.js
// only partial code
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/search', (req, res) => {
console.log(req.body);
console.log(req.query);
console.log(req.params);
});
我的浏览器日志
我的后端日志
回答如下:因为您发送的数据无效:
xhr.send('data='+JSON.stringify(searchConditions));
JSON对象没有变量声明。您的服务器得到的是:
data = [ some Object contenct];
尝试发送纯JSON对象:
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(searchConditions);
本文标签: 如何通过前端ajax通过post方法发送的nodejs在服务器端检索数据
版权声明:本文标题:如何通过前端ajax通过post方法发送的node.js在服务器端检索数据? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1715210584a822569.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论