Search code examples
jquerynode.jsexpressbody-parser

issue with jquery $.post


I am running express.js local server. It is sending a html file, where if I press a button it will call an server side api and get the result. But it seems $.post sending empty body ({}) to server.

Server side code

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/', function(req, res) {
    console.log(req.hostname);
    res.sendFile(`${__dirname}/index.html`);
});

app.post("/", urlencodedParser, function(req, res) {
    console.log(req.body);
    res.send(`The sum is ${Number(req.body.num1) + Number(req.body.num2)}`);
});

app.post("/api/sum", jsonParser, function(req, res) {
    console.log(req.body);
    res.send({ data: "success" });
});

app.listen(3000, function() {
    console.log("server started at port 3000");
});

Html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
</head>

<body>
    <h1>Calculator</h1>
    <form action="/" method="POST">
        <input type="text" name="num1" placeholder="first number" id="num1">
        <input type="text" name="num2" placeholder="second number" id="num2">
        <button type="submit" name="submit">submit</button>
    </form>
    <button id="noRefresh">No refresh update</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $("#noRefresh").click(function() {
        console.log("posting " + $("#num1").val() + " " + $("#num2").val());
        $.post("/api/sum", {
                num1: $("#num1").val(),
                num2: $("#num2").val()
            },
            function(data, status) {
                alert("The sum is " + data.data);
            });
    });
</script>

</html>

When I pressing the 'No refresh update' button, I am getting {} empty object at server side. What is wrong?


Solution

  • Client side's http config doesn't match server's. So there are 2 ways to slove.

    1, $.post sent http request with ContentType as application/x-www-form-urlencoded. To match that, code in server side could be:

    var jsonParser = bodyParser.urlencoded()
    

    2, Or you can modify the client side only without changing the server side:

    $.ajax({
        type: "post",
        url: '/api/sum',
        data: JSON.stringify({num1: $("#num1").val(),num2: $("#num2").val()}),
        dataType:"json",
        contentType: "application/json;charset=UTF-8"
        success(data, status) {
           alert("The sum is " + data.data);
        }
    })