【问题标题】:Format of data received through ajax request?通过ajax请求接收的数据格式?
【发布时间】:2016-03-31 07:31:04
【问题描述】:

我的客户端代码如下所示:

<form name="sendCoordinates" action="http://localhost:8080/geodata" method="post"> 
        <label> MinLat: </label>
        <input type="text" name="MinLat" value="0"><br>
        <label> MaxLat: </label>
        <input type="text" name="MaxLat" value="1"><br>
        <label> MinLong: </label>
        <input type="text" name="MinLong" value="0"><br>
        <label> MaxLong: </label>
        <input type="text" name="MaxLong" value="1"><br>

        <input type="submit" value="submit" id="s1">
        </form> 

<script>


        $("#sendCoordinates")
            .on('submit', function(e) {

                e.preventDefault();

                var $form    = $(e.target),
                    formData = new FormData();
                    params   = $form.serializeArray();

                $.each(params, function(i, val) {
                    formData.append(val.name, val.value);
                });

                $.ajax({
                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function(result) {
                        console.log(result + "you");
                    }
                });
            });
    </script>

我正在将此表单数据发送到端点/geodata

app.post("/geodata", function(req, res) {
    console.log(req.body);
});

我的问题是,在一个成功的帖子下,console.log(req.body) 会在服务器端打印什么?我还不能说,因为我的客户由于一些错误还没有发送任何信息。这将帮助我根据我在发布请求中收到的数据编写我的服务器端代码。

【问题讨论】:

  • 没有人会知道。服务器可以发送任何格式的数据——json、xml,甚至是纯文本。除非他们告诉你,否则你不会知道。

标签: javascript jquery ajax node.js


【解决方案1】:

看起来您正在使用 Express。在一般实践中,请求正文被解析为 JSON(请参阅Express req.body docs),但这取决于您使用的解析中间件(body-parser 是 Express 应用中常见的中间件)。

它还取决于请求的 Content-Type 标头。从我上面提到的 Express 文档中,他们举了一个例子:

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

看起来您当前在 AJAX 请求中设置了 contentType: false,这样只会将原始数据发送到您的服务器。

更具体地回答你的问题

我的问题是,在一个成功的帖子下,console.log(req.body) 会在服务器端打印什么?

这取决于Content-Type 以及您使用解析请求正文的中间件(如果有)。

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多