下面是我如何使用 React JS 和 Fetch 将我的数据发布到我的 NodeJS API。我的问题是我不知道如何在我的 nodejs api 路由中访问从客户端发送的对象数组。如果您对我的代码有任何其他问题,请在下面评论。
fetch('http://localhost:5000/api/testSub', {
method: 'POST',
body: JSON.stringify(teamSheet),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`
}
}).then(res => {
this.props.history.push('/Login');
});
这就是我目前尝试访问对象数组的方式
router.post('/testSub', auth, async function(req, res) {
//GET ARRAY
const sheet = {
teamsheet.playerNumber = req.body.playerNumber,
teamsheet.playerName = req.body.playerName,
teamsheet.playerPosition = req.body.playerPosition
};
next();
});
最佳答案
首先,确保您的 teamSheet 变量是一个对象,其中包含一个数组。您的 fetch 函数看起来有效。在 Node 端,您应该能够在请求正文中访问它。
// Client Fetch
var players = [{
name: 'John',
number: '11',
position: 'Pitcher',
},{
name: 'Mary',
number: '22',
position: 'Catcher',
}]
var teamSheet = { players: players }
// Fetch...
fetch('http://localhost:5000/api/testSub', {
method: 'POST',
body: JSON.stringify(teamSheet),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`
}
}).then(res => {
this.props.history.push('/Login');
});
// Server
var players = req.body.players
关于node.js - 如何访问从客户端发送的对象数组中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58001089/