【问题标题】:How to retrieve data on server side with node.js sent by frontend ajax via post method?如何使用前端ajax通过post方法发送的node.js在服务器端检索数据?
【发布时间】:2020-05-14 10:02:41
【问题描述】:

我最近开始用 express 框架学习 node.js,偶然发现了一个问题。

我正在尝试一个简单的查询搜索 webapp,我想传递一段数据(一个名为 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);
});

我的浏览器日志

我的后端日志

【问题讨论】:

    标签: javascript node.js ajax express


    【解决方案1】:

    因为你发送的数据无效:

    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));
    

    【讨论】:

    • 嗨!我通过在发送方法中添加 setRequestHeader 并删除 'data=' 使其工作,但是,我仍然必须保留 JSON.stringify(searchConditions) 而不仅仅是像你提到的 searchConditions,如果你可以详细说明并编辑你的回答,我很乐意接受这个作为解决方案,谢谢。
    • 哦,好的。有一段时间没有处理普通的 XHR 请求了。我纠正了,我的错!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多