我最近开始用 express 框架学习 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 = {"all": true }'
这甚至不是有效的变量声明。你的服务器应该得到的是:
{"all": true}
尝试发送没有变量声明的纯 JSON 对象,并将“Content-Type”-header 设置为 json:
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(searchConditions));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句