服务器端检索数据?"/>
如何通过前端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方法发送的node.js在服务器端检索数据?
发布评论