我想使用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"));
有什么主意吗?
答案 0 :(得分:0)