【问题标题】:How to pass data from client side Javascript to node.js using XMLHttpRequest?如何使用 XMLHttpRequest 将数据从客户端 Javascript 传递到 node.js?
【发布时间】:2019-01-09 15:57:01
【问题描述】:

我的 index.html 文件中有 HTML 输入。

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

当我填写数据并单击发送时,我想将它们发送到我的节点脚本,在那里我可以对传递的数据做一些事情。

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

});

以及我如何尝试在服务器端 test.js 文件中接收数据。

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

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

});

在这种情况下,输出显示:body: undefined

如何将数据从客户端页面发送到服务器端,以便我可以使用它们执行其他操作?

【问题讨论】:

  • 您的浏览器(前端)是否有任何控制台错误?
  • 既然您使用 jquery 为什么不使用 $.ajax( ... 还有什么是您的端点在做 post .. "/data" ?通常 node.js 位于与您的正常端口不同的端口上如果不使用本机站点,请参阅:stackoverflow.com/questions/4295782/…
  • 你用的是什么版本的快递?
  • @madalinivascu 我目前在前端控制台中没有错误。
  • @wscourge 我目前使用 Express v. 6.4.1

标签: javascript node.js express xmlhttprequest


【解决方案1】:

您只需要像这样在 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);

如果该模块不存在,只需执行 npm install 即可:

npm install body-parser

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    相关资源
    最近更新 更多