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);
    
    评论
  • 胖鸭 2018-07-21 16:54
    关注

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

    评论
  • YaoRaoLov 2018-07-21 16:55
    关注

    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
    评论

报告相同问题?

悬赏问题

  • ¥15 存储过程或函数中的结果集类型变量如何使用。
  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信