I’m having trouble with data transformation when sending nested objects from my React app to an Express server. When I send a POST request with jQuery, the nested object structure gets flattened by the time it reaches my backend route.
What I’m sending:
updateProduct() {
let productId = "5bf4459853bfc70bc82e8e91"
$.ajax({
url: '/api/products/' + productId,
method: 'post',
data: {
'product': {
title: "sample product",
dimensions: {
width: 200,
length: 75
}
}
},
success: (response) => {console.log(response)}
});
}
What arrives at the backend:
{ 'product[title]': 'sample product',
'product[dimensions][width]': '200',
'product[dimensions][length]': '75' }
My Express setup:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/inventory');
mongoose.Promise = global.Promise;
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api', require('./routes/api'));
app.use((err, req, res, next) => {
res.status(422).send({error: err.message});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Route handler:
router.post('/products/:id', (req, res, next) => {
console.log(req.body);
res.send("received");
});
Is there a way to preserve the original nested object structure when it gets to my Express route? Should I modify my body-parser configuration or handle this differently on the frontend?