簡體   English   中英

使用Ajax處理POST到Node.js&Express中的req.body

[英]Handling POST to req.body in Node.js & Express using Ajax

我在Node.js&Express網站中使用Ajax,以便將值從文本框發送到服務器端。 現在,它正在工作; req.body具有我需要的文本值,但是JSON的格式對我來說很難獲取。 簡而言之,看來我的ajax正在將變量名稱重命名為在文本框中輸入的值。 所以不是req.body是

{ hashtag: 'test123' }

req.body顯示:

{ test123: '' }

例如:在我的Jade文件中:

         form
            input#hash(type='text', name='hashtag[hash]', placeholder='#Hashtag')
            input#submit.btn.btn-primary(name='submit', type='submit', value='Send', onclick='return chk()')

    p#msg


script.
  function chk(){
    var posthash = document.getElementById('hashtag').value;
    console.log(posthash);
    $.ajax({
        type:"post",
        url: "/api/hash",
        data:posthash,
        cache:false,
        success: function(html){
            console.log("Successfully posted");
            $('#msg').html(html);
        },
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
            console.log(error);
        }
    })
  return false;
  }

然后,在我的server.js中:

app.post("/api/hash", function (req, res) {
  console.log(req.body);
});

因此,如果我在文本框中輸入以下內容:

測試123

req.body顯示:

{ test123: '' }

如您所見,變量名本身就是文本框的值。 因此,如果我嘗試說console.log(req.body.hashtag)console.log(req.body.hash) ,它就會以未定義的形式出現-因為那不是變量名。

問題是您提交posthash的方式。 此變量包含您在輸入中輸入的字符串,但是$.ajax期望使用對象作為data選項。 只需像這樣更改行:

 data: {hashtag: posthash} ,

而且由於您將輸入聲明為hash作為id

input#hash

你必須使用

document.getElementById('hash').value;

獲得價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM