When i have an object with a nested object within, whose keys are numbers and send it to my node.js server, then the nested object is converted to an array. How can i prevent this ?
Client:
JavaScript
x
11
11
1
$.ajax({
2
url : `/cctool/report`,
3
method : "PUT",
4
data : {
5
new : {
6
10 : "Test",
7
20 : "Hello",
8
}
9
}
10
});
11
Server:
JavaScript
1
4
1
router.put("/cctool/report", (request, response) => {
2
console.log(request.body);
3
}
4
{ new: [ ‘Test’, ‘Hello’ ] }
When i add a not numeric key, everything works fine. Also when the keys are at the first level.
My settings:
JavaScript
1
16
16
1
const express = require('express');
2
const CookieParser = require('cookie-parser');
3
const Sessions = require('express-session');
4
const crypto = require('crypto');
5
const router = express.Router();
6
7
router.use(express.json());
8
router.use(express.urlencoded({extended : true}));
9
router.use(CookieParser());
10
router.use( Sessions({
11
secret : crypto.randomBytes(64).toString('hex'),
12
saveUninitialized : false,
13
cookie : {maxAge : 1000 * 60 * 60 * 8}, // 8 hours
14
resave : false
15
}));
16
Advertisement
Answer
Try adding the contentType
header and using JSON.stringify
to serialize the object before passing to $.ajax
:
JavaScript
1
33
33
1
const express = require("express");
2
const app = express();
3
4
const html = `<!DOCTYPE html>
5
<head>
6
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
7
</script>
8
</head>
9
<body>
10
<script>
11
$.ajax({
12
url: "/cctool/report",
13
method: "PUT",
14
contentType: "application/json",
15
data: JSON.stringify({
16
new: {
17
10: "Test",
18
20: "Hello",
19
}
20
}),
21
success: data => console.log(data),
22
});
23
</script></body></html>`;
24
25
app
26
.use(express.json())
27
.get("/", (req, res) => res.send(html))
28
.put("/cctool/report", (req, res) => {
29
console.log(req.body);
30
res.json(req.body);
31
})
32
.listen(3000);
33
See jQuery posting JSON.