简体   繁体   English

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

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

I'm using Ajax in my Node.js & Express website in order to send a value from a text box to the server side. 我在Node.js&Express网站中使用Ajax,以便将值从文本框发送到服务器端。 Right now, it is working; 现在,它正在工作; the req.body has the text value that I need, however the JSON is formatted in a way that is difficult for me to get the value. req.body具有我需要的文本值,但是JSON的格式对我来说很难获取。 In short, it seems my ajax is renaming the variable name to the value entered within the text box. 简而言之,看来我的ajax正在将变量名称重命名为在文本框中输入的值。 So instead of the req.body being 所以不是req.body是

{ hashtag: 'test123' }

The req.body shows: req.body显示:

{ test123: '' }

Eg: In my Jade file: 例如:在我的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;
  }

Then, within my server.js: 然后,在我的server.js中:

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

So, if I enter this into the text box: 因此,如果我在文本框中输入以下内容:

test123 测试123

The req.body shows: req.body显示:

{ test123: '' }

As you can see, the variable name itself is the value of the text box. 如您所见,变量名本身就是文本框的值。 Thus, if I try to say console.log(req.body.hashtag) or console.log(req.body.hash) , it comes up as undefined - because that's not the variable name. 因此,如果我尝试说console.log(req.body.hashtag)console.log(req.body.hash) ,它就会以未定义的形式出现-因为那不是变量名。

The problem is the way you submit the posthash . 问题是您提交posthash的方式。 This variable contains the string you enter in the input,but $.ajax is expecting an object as data option. 此变量包含您在输入中输入的字符串,但是$.ajax期望使用对象作为data选项。 Just change the line like this : 只需像这样更改行:

 data: {hashtag: posthash} ,

And since you declare the input with hash as id 而且由于您将输入声明为hash作为id

input#hash

you have to use 你必须使用

document.getElementById('hash').value;

to get it's value. 获得价值。

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

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