以下是我如何使用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变量是一个Object,其中包含一个数组。您的提取函数看起来有效。在节点侧,您应该能够在请求正文中对其进行访问。
// 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句