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>

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);

http get request has no request body. jQuery will convert data to url params automatically, so you need get that value in req.query.

In your sever side to change req.body with req.query.number and in your $.ajax you can add the number as data property like this:

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

For POST request we use req.body and for GET request we use req.query for queryStrings.

  • notice that req.query.number is a string because its GET request