gpt4 book ai didi

node.js - 如何访问从客户端发送的对象数组中的数据?

转载 作者:行者123 更新时间:2023-12-03 22:26:33 25 4
gpt4 key购买 nike

下面是我如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com