使用jQuery ajax发送包含空数组的对象失败

时间:2018-09-04 07:46:43

标签: jquery node.js ajax express

我想使用jQuery Ajax PUT将如下对象发送到Node.js快递服务器:{value: {tags: []}}问题是,在快递app.put()处理程序中,req.body.value来了未定义。经过一些测试,我倾向于指责jQuery,但是我不确定。我发现的唯一解决方法是将空数组更改为具有在服务器中删除的不可能值的数组。 这是客户:

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>MWE empty array problem</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<button>Push me!</button>
<script>
$("button").on("click", () => {

    $.ajax("http://localhost:4321/", {

        // dataType: "json", // This does not change the result
        // contentType: 'application/json', // Also this does not change the result
        data: {value: {tags: []}},
        // data: {value: {tags: [""]}}, // This works, but it is not what I want
        // data: {value: {tags: [], dummy: ""}}, // This gives an undefined req.body.value.tags
        // data: {value: JSON.stringify({tags: []})}, // This gives an undefined req.body.value.tags
        method: "PUT"
    });
});
</script>
</body>
</html>

和服务器:

"use strict";

// > Load required modules
const express = require("express");
const bodyParser = require("body-parser");

// Initialize application
const app = express();

// PUT Updating document: the action is given as parameter
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

app.put("/", function(req, res) {

    console.log(req.body.value.tags);

    res.sendStatus(200);
});

// > Serve static pages
app.use("/", express.static(__dirname));

// Start the server
app.listen(4321, () => console.log("Server running on port: 4321"));

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

这可能是因为[]等于0,因此它表示“未定义”

我只找到一个humourus Picture to describe it

解决此问题的最佳方法可能是检查reg.body.value是否等于null