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

标签 node.js reactjs sequelize.js

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

相关文章:

sql - Sequelize - 获得零售商后将商店并入零售商

javascript - 使用 Sequelize 运算符获取日期

mysql - 在连接表中插入附加数据

node.js - 使用 graphql 文件编译 Typescript 时出错

javascript - Webpack 热模块替换,react 18 ReactDOMClient.createRoot() 在之前已经传给 createRoot() 的容器上

javascript - 连接 redux-store 后,React-Router <Link> 组件未应用 activeStyle

node.js - Sequelize getter 方法中的异步表查询

javascript - 将 bcrypt 哈希/验证函数转换为异步函数

node.js - Cloudrail-OneDrive API : Advanced search request fails

javascript - useEffect 不会在路由更改时更新状态