如何通过前端ajax通过post方法发送的node.js在服务器端检索数据?

编程入门 行业动态 更新时间:2024-10-09 20:29:54

如何通过前端ajax通过post方法发送的node.js在<a href=https://www.elefans.com/category/jswz/34/1771251.html style=服务器端检索数据?"/>

如何通过前端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在服务器端检索数据?

本文发布于:2024-05-07 14:08:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器端   方法   数据   ajax   post

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!