繁体   English   中英

检索服务器上的POST数据

[英]Retrieving POST data on server

以下代码应在单击按钮后将数据从客户端发送到nodejs服务器。 单击提交按钮后,将调用该路由,但似乎未将数据发送到服务器。 问题是:如何将数据从客户端发送到服务器,以及如何在节点js端检索数据?

index.ejs:

<script type = "text/javascript"
            src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <script type = "text/javascript" language = "javascript">

      $(document).ready(function() {
        $("#myButton").bind('click', function() {

          event.preventDefault();

          var data = $('#myEditText').val();
          $.post('/yolo', {textBoxValue: data}, function(callback) {
            document.write("button clicked calling yolo script");
            alert("yolo");
          });

          alert("Button clicked. This button was bind/onClickListener to Jquery: "+data);
        });
      });

    </script>
    <form id = "myForm" action = "http://localhost:3000/yolo" method="post"> <!--action = "http://127.0.0.1/index.js" is for telling the browser which script file will handle the data from this form upon submission -->
      Enter Url: <input id="myEditText" type="text" name="urlEditText"/>
      <br />
      <br />
      Shortened Url:<%= shortenedUrl %> <!--// shortened url passed from the server -->
      <br />
      <br />
      <button id="myButton" type="button" value="Submit" onclick="fetchData()"> Submit </button>
    </form>

index.js:

router.post('/yolo', function(req, res, next) {

    req.on('textBoxValue', function(data) {
        console.log("data recieved: "+ data);
    });

    console.log("yolo post called: "+ req.data + " fromBody: "+ req.body.urlEditText);
    res.render('index', { title: 'NewTitle', shortenedUrl: shortenedUrl});
    console.log("hello inside index.js method 1");
});

首先,请检查浏览器的控制台网络选项卡以查看发送了什么:它可能是url形式编码的,这不是您想要的。 您可以使jQuery使用以下方式将其作为JSON发送:

$.ajax({
  type: 'POST',
  url: '/yolo',
  data: JSON.stringify({textBoxValue: data}),
  contentType: 'applicatio/json'
})

然后确保在服务器端( ref )中使用主体解析器,例如body-parser

需求主体

包含在请求正文中提交的键/值数据对。 默认情况下,它是未定义的,并且在使用主体解析中间件时进行填充[...]

代码为:

var bodyParser = require('body-parser');

var jsonParser = bodyParser.json();

router.post('/yolo', jsonParser, function(req, res, next) {
    // here req.body should be the object {textBoxValue: data}
});

首先:req和res对象是node.js和express / koa中的流。 关于流的好东西: https : //github.com/substack/stream-handbook

因此,您需要先使用诸如body-parser之类的“解析”您的数据。 然后在req对象中,您将在req.body.{key: value, keyn: valuen}找到发布数据req.body.{key: value, keyn: valuen}

另外,由于可写流中没有此类事件,因此将重新触发textBoxValue事件。 但是您总是可以创建事件发射器并触发自己的事件。

暂无
暂无

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

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