【问题标题】:loop through request body node js + express循环通过请求体节点 js + express
【发布时间】:2020-09-16 22:26:34
【问题描述】:

我正在发送一个包含数据作为对象数组的请求:

 [
  {id: "1"},
  {id: "2"},
  {id: "3"}
 ]

我使用JSON.stringify(),我的 req.body 看起来像这样: { '{"id":"1"},{"id":"2"},{"id":"3"}': '' }

现在我想遍历 req.body 并获取所有 ID,以便我可以从 SQL DB 中删除它们。 我正在使用续集。 后端:

exports.deleteIds = (req, res, next) => {
    console.log(req.body)
//here should be loop so i can delete all the ids one by one.
    Model.destroy({
        where: {
            id: 
        }
    })
}

发布请求(客户端):

let ids = []
//maybe here is the problem?
for (var i = 0; i < selectedRow.length; i++) {
   ids.push({id:selectedData[i].id})          
}

let Url = "/admin/deleteIds"
let data = JSON.stringify(ids)

event.preventDefault();

$.post(Url, data, function (data, status) {

  }).done(function (res) {
     if (res.ids.length == 0) {
        $('#mainContent').html('<h1>0 users found</h1>')
     }
  })
  .fail(function (err) {
    console.log(err.responseJSON.message)
  })

【问题讨论】:

  • 您使用的是哪个数据库库?,它可能是一个内置选项
  • @Itamar 我正在使用 Sequelize
  • 在下面查看我的答案

标签: javascript node.js loops express


【解决方案1】:

编辑

通过发送 id 数组并直接在服务器中使用它,我们所做的一切都变得更加简单。

客户:

let ids = []
for (var i = 0; i < selectedRow.length; i++) {
   ids.push(selectedData[i].id)  // <-- this is the change         
}

let Url = "/admin/deleteIds"
let data = {items: ids}
//...

服务器:

exports.deleteIds = (req, res, next) => {
   const ids = req.body.items; // <-- no mapping needed
   Model.destroy({
      where: {id: ids}
   })
}

POST调用body应该是一个合法的JSON,也就是说它应该是一个js对象。

假设您使用 Fetch

使用 Fetch API 向服务器发送数据

 const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({items:  [ {id: "1"}, {id: "2"}, {id: "3"} ]})
  });

首先,如果你把 req.body 作为一个对象,没有理由使用JSON.stringify。如果不使用JSON.parseExpress's body-parser

其次,您可能在 DB 库中有一种方法可以发送多个 ID 进行销毁。

如果你使用 Sequelize.js 为例:

exports.deleteIds = (req, res, next) => {
   const ids = req.body.items.map(({id}) => id); 
   Model.destroy({
      where: {id: ids}
   })
}

如果这个选项不存在,让我们循环:

exports.deleteIds = (req, res, next) => {
   req.body.items.forEach(({id}) => {
      Model.destroy({
        where: {id}
      })
  }) 
}

您的固定 POST 电话:

let ids = []
for (var i = 0; i < selectedRow.length; i++) {
   ids.push({id:selectedData[i].id})          
}

let Url = "/admin/deleteIds"
let data = {items: ids} // <-- this is the change

event.preventDefault();

$.post(Url, data, function (data, status) {

  }).done(function (res) {
     if (res.ids.length == 0) {
        $('#mainContent').html('<h1>0 users found</h1>')
     }
  })
  .fail(function (err) {
    console.log(err.responseJSON.message)
  })

【讨论】:

  • 我已经在使用正文解析器作为中间件了。当我尝试使用没有 JSON.stringify [ {id: "1"}, {id: "2"}, {id: "3"}] 的对象数组发送发布请求时,我得到 { undefined: [ '', '', '' ] }(当 console.log req.body 时)
  • 您可以在问题中添加客户端 post call 和 post server handler 吗?
  • 谢谢,我会试试的,所以只是为了确保我可以更改我的代码这一行,这样我就会有和你一样的代码来获取有效的 json 数据let data = JSON.stringify({items: ids})
  • 我在上面做了解决方案。但我改变了一件事,它的工作完美。我在没有 JSON.stringify 的情况下发布数据:{items: [ {id: "1"}, {id: "2"}, {id: "3"} ]} 及其工作
  • 编辑您的答案并从解决方案中删除 JSON.stringify。我选择用const ids = req.body.items.map(({id}) =&gt; id); 来做这件事,它工作得很好,谢谢。
【解决方案2】:

正如另一位用户提到的,req.body 应该始终是有效的 json,因此不太可能接收到数组。

当你收到一个有效的 json 请求时,在 Sequelize 中你可以使用三种方法:

  1. 一个get() 函数,用于确定您从数据库中检索的内容:https://sequelize.org/master/manual/getters-setters-virtuals.html

  2. 模型上的 set() 方法运行一个函数,用于处理您想要保存到数据库的内容:

const User = sequelize.define('user', {
  username: DataTypes.STRING,
  password: {
    type: DataTypes.STRING,
    set(value) {
      this.setDataValue('password', hash(value));
    }
  }
});

  1. (可能是我的推荐)直接在控制器上的一个函数,就像在这个例子中,我对一个组织名称进行了 slugify:
  try {
    const result = await Organization.create({
      name: req.body.name,
      type: req.body.type,
      slug: slugify(req.body.name, { lower: true, remove: /[*+~.()'"!:@]/g, strict: true }),
      fields: allowedFields
    }) catch(err) { etc.}

【讨论】:

  • 对象键不起作用,因为它是问题中的数组
  • 对不起 Itamar,我错过了。会更新。我建议的 create 函数只是关于如何在 Sequelize 中使用内联 Model 控制器功能可能性的一个示例
猜你喜欢
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
相关资源
最近更新 更多