weixin_33736649 2018-07-21 15:42 采纳率: 0%
浏览 7

Node.JS AJAX空主体

Can't get data on server side from AJAX-request because req.body is empty (console logs it's {}).
script.js:

$("#button").click(function(){
    var number = $("#number").val();
        $.ajax({
            url: "/multiply",
            type: "get",
            data: number,
            cache: false,
            success: function(data){
                $("#result").html(data);
            }
        });
});

server side:

app.get('/multiply', urlencodedParser, function(req, res, next){
    console.log(req.body); //logs {}
    res.send('ok');
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test AJAX</title>
</head>
<body>

    <input type="text" name="number" id="number">
    <button type="button" id="button">Multiply</button>

    <div id="result">

    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="/script.js"></script>
</body>
</html>
  • 写回答

3条回答 默认 最新

  • weixin_33725126 2018-07-21 16:43
    关注

    You should add the number to the URL as a parameter:

    $.ajax({
        url: "/multiply?number=" + number,
        type: "get",
        cache: false,
        success: function(data) {
            $("#result").html(data);
        }
    });
    

    And on the server side, you can get that value using the req.query object:

    console.log(req.query.number);
    
    评论

报告相同问题?