首页 文章

NodeJS req.body JSON那里但没有 Value

提问于
浏览 751
0

index.js:

var express = require('express');
var server = express();
var bodyParser = require('body-parser');

server.use(express.static('public'));
server.use(bodyParser.json());

server.post('/saveentry', (req, res) => {
    console.log(req.body);
    res.send("Eintrag gespeichert");
});

server.listen(80, 'localhost');

index.html的:

<html>
    <head>
        <title>Gästebuch</title>
    </head>
    <body>
        <div id="guestbook"></div>
        <input type="text" id="entry" name="entry">
        <button id="submit">Senden</button>

        <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
        <script>
            var formData = {
                entry: $("#entry").val()
            }
            $('#submit').click(function() 
            {
                $.ajax({
                    type: 'POST',
                    url: '/saveentry',
                    data: JSON.stringify(formData),
                    dataType: "text",
                    contentType : "application/json",
                    success: function (data) {
                        console.log(data);
                    }
                });
            });
        </script>
    </body>
</html>

如果我按下“Senden”,这就是控制台中的结果:{entry:''}

如何获取表格中输入的文字?我还能尝试什么?我没有在网上找到解决方案 .

1 回答

  • 1

    您需要从回调函数内的输入接收值:

    $('#submit').click(function() {
        var formData = {
            entry: $("#entry").val()
        };
        $.ajax({
            type: 'POST',
            url: '/saveentry',
            data: JSON.stringify(formData),
            dataType: "text",
            contentType : "application/json",
            success: function (data) {
                console.log(data);
            }
        });
    });
    

相关问题