简体   繁体   中英

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. 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. In short, it seems my ajax is renaming the variable name to the value entered within the text box. So instead of the req.body being

{ hashtag: 'test123' }

The req.body shows:

{ test123: '' }

Eg: In my Jade file:

         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:

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

So, if I enter this into the text box:

test123

The req.body shows:

{ 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.

The problem is the way you submit the posthash . This variable contains the string you enter in the input,but $.ajax is expecting an object as data option. Just change the line like this :

 data: {hashtag: posthash} ,

And since you declare the input with hash as id

input#hash

you have to use

document.getElementById('hash').value;

to get it's value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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