简体   繁体   English

如何使用XMLHttpRequest将数据从客户端Javascript传递到node.js?

[英]How to pass data from client side Javascript to node.js using XMLHttpRequest?

I have HTML inputs in my index.html file. 我的index.html文件中有HTML输入。

<input type="text" id="handle" >
<input type="text" id="message" >
<button id="send">send</button>

When I fill up data and click send, I want to send them to my node script where I can do something with passed data. 当我填写数据并单击发送时,我想将它们发送到我的节点脚本,在这里我可以对传递的数据做些事情。

My index.html 's script: 我的index.html的脚本:

$("#send").on("click", function() {
    var message = $("#message").val();
    var handle = $("#handle").val();


    var xhr = new XMLHttpRequest();
    var data = {
        param1: handle,
        param2: message
    };
    xhr.open('POST', '/data');
    xhr.onload = function(data) {
        console.log('loaded', this.responseText);
    };
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(data));

});

And how I have tried to recieve data in my serverside test.js file. 以及如何尝试在服务器端test.js文件中接收数据。

app.post('/data', function(req, res){

    var obj = {};
    console.log('body: ' + req.body);
    res.send(req.body);

});

In this case, the output shows: body: undefined 在这种情况下,输出显示: body:undefined

How can I send the data from my client side pages to server side so that I can use them to perform my other operations? 如何将数据从客户端页面发送到服务器端,以便可以使用它们执行其他操作?

You just need to use a JSON body parser in Express like so: 您只需要在Express中使用JSON正文解析器,如下所示:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(express.static('./'));
/* Parse JSON data using body parser. */
app.use(bodyParser.json());

app.post('/data', function(req, res){
    console.log('body: ',  req.body);
    res.send(req.body);
});

app.listen(port);

Just do an npm install for this module if not already present: 只需为此模块执行npm安装(如果尚不存在):

npm install body-parser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM