我正在尝试使用jquery ajax将另一个对象从React前端发送到Node / express后端。在后端接收数据的问题,它不再遵循对象的语法。相反,它看起来像这样:
{ 'data[name]': 'test name',
'data[size][height]': '123',
'data[size][weight]': '50' }
这是前端ajax调用...
lendItem(){
let id = "5af3348742afc60ab71d7d80"
$.ajax({
url: '/api/items/' + id,
method: 'put',
data: {
'data': {
name: "test name",
size: {
height: 123,
weight: 50
}
}
},
success: (res) => {console.log(res)}
});
}
后端服务器......
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// connect to mongodb
mongoose.connect('mongodb://localhost/promedical');
mongoose.Promise = global.Promise;
const app = express();
const port = process.env.PORT || 5000;
// parsing data that was received
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// initialize routes
app.use('/api', require('./routes/api'));
// error handling
app.use((err, req, res, next)=>{
res.status(422).send({error: err.message});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`)
});
......这是我感兴趣的路线。
router.put('/items/:id', (req, res, next)=>{
console.log(req.body);
res.send("success");
});
我认为这个问题可能与身体解析器有关。是否可以通过jquery ajax在对象内部发送对象并让它在到达后端时保持其形式?如果没有,我应该将所有数据发送到一个对象中,然后在后端解析吗?