首页 > 解决方案 > 从客户端 JS 发送 JSON,服务器 Nodejs 读取为 [object object]

问题描述

您好,我只是想通过 POST 更新欢迎消息,据我所知,我正在从客户端 JavaScript 发送 JSON,在 NodeJS 端它显示为 [object object] I'我试过 req.body 并返回“未定义”。我想知道如何从我发送到 nodejs 服务器的 JSON 中提取我的欢迎消息并保存到 .JSON 以便以后能够从客户端中提取。

我已经尝试过jsonstringify(req),这会在我的 nodejs cmd 中返回一个大错误,如果有必要,我可以粘贴它。

nodejs 服务器 POST,它会写入文件 welcome.json,它会写入[object object]or undefined,这取决于我是否使用req.bodyor req

app.post('/update', function (req, res) {
    fs.writeFile(__dirname + '/rqsts/welcome.json', req.body, function () {
        console.log('We got a Post request' + req.body);
    });
});

这是我的客户端http post请求:

function submit() {
    var text_Input = document.getElementById('textinput').value;
    var testing = document.getElementById('testme');
    var welcome_array = {
        welcome: ""
    };
    welcome_array.welcome = text_Input;
    var welcomeJSON = JSON.stringify(welcome_array);
    var url = 'http://localhost:8080/update';
    var http = new XMLHttpRequest();
    http.open('POST', url, false); // false for synchronous request
    Add_Para(welcomeJSON, testing);
    http.send(welcomeJSON);
}

Add_Para 是我为进行故障排除而制作的一个功能,它使用请求的数据“welcomeJSON”在所述 html 中添加了一个段落

标签: javascriptnode.jspost

解决方案


如果您使用的是 expres 4.16 或更高版本,请使用

app.use(express.json());

没有必要使用bodyParser


推荐阅读