簡體   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