简体   繁体   English

循环遍历请求体节点 js + express

[英]loop through request body node js + express

Im sending a request with data as an array of objects:我发送一个包含数据作为对象数组的请求:

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

im using JSON.stringify() and my req.body looks like this: { '{"id":"1"},{"id":"2"},{"id":"3"}': '' }我使用JSON.stringify()并且我的 req.body 看起来像这样: { '{"id":"1"},{"id":"2"},{"id":"3"}': '' }

Now i want to loop through req.body and get all the ids so i can delete them from the SQL DB.现在我想遍历 req.body 并获取所有 id,以便我可以从 SQL DB 中删除它们。 Im using Sequelize.我正在使用 Sequelize。 The back end:后端:

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: 
        }
    })
}

The post request (client):发布请求(客户端):

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)
  })

EDIT编辑

We we do is all even easier, by sending and array of ids and using it in the server directly.通过发送 id 数组并直接在服务器中使用它,我们所做的更容易。

Client:客户:

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}
//...

Server:服务器:

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

POST calls body should be a valid JSON, which means that it should be an js object. POST 调用 body 应该是一个有效的 JSON,这意味着它应该是一个 js 对象。

Assuming you use Fetch假设您使用 Fetch

Sending data to server with Fetch API使用 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"} ]})
  });

First, if you get the req.body as an object, there is no reason to use JSON.stringify .首先,如果您将 req.body 作为对象获取,则没有理由使用JSON.stringify if not use JSON.parse or Express's body-parser如果不使用JSON.parseExpress 的 body-parser

Second you probably have a way in the DB library to send multiple IDs to destroy.其次,您可能在 DB 库中有一种方法可以发送多个 ID 进行销毁。

If you use Sequelize.js for example:例如,如果您使用 Sequelize.js:

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

In case this option does not exist, lets loop:如果此选项不存在,让我们循环:

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

Your fixed POST call:您固定的 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)
  })

As another user mentions, req.body should always be valid json, so receiving an array is unlikely.正如另一位用户所提到的,req.body 应该始终是有效的 json,因此不太可能接收数组。

When you receive a valid json request, in Sequelize you can use three methods:当您收到有效的 json 请求时,在 Sequelize 中您可以使用三种方法:

  1. A get() function that determines what you retrieve from the database: https://sequelize.org/master/manual/getters-setters-virtuals.html一个get()函数,用于确定您从数据库中检索的内容: https : //sequelize.org/master/manual/getters-setters-virtuals.html

  2. A set() method on the model that runs a function on what you want to save to the database:模型上的set()方法,它对要保存到数据库的内容运行函数:

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

  1. (Probably my recommendation here) A function directly on the controller, like in this example where I slugify an organization name: (可能是我的建议)直接在控制器上的一个函数,就像在这个例子中,我将一个组织名称插入:
  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.}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM