如何在node.js中从req.body获取一个json的数组?

How to obtain an array of json back from req.body in node.js?

我想post一个json的数组到node js。我在服务器端使用 ajax post method.On 做了同样的事情,我试图用 req.body 访问它。但是结果是字符串的形式。所以我无法通过 one.How 遍历 json 数组元素,我可以这样做吗?JSON.parse 或 stringyfy 一切都显示为对象。这是在 req.body

      req.body: '[{"img_id":"img_1","name":"abc","source":"img/Icon_ABc.
  png"},{"img_id":"img_0","name":"flower","source":"img/Icon_flower.png"}, 
  {"img_id":"img_5","name":"panda","source":"img/Icon_panda.png"
  }]'

我使用的post方法是ajax。

     Dataform.append("finalAray",JSON.stringify(finalArray))
 $.ajax({
    url: '/api/upload/',
    type: 'POST',
    processData: false,
    contentType: false,
    dataType : 'application/json; charset=utf-8',
    data: Dataform,

    success: function(data){
       //................
    },
    error: function(exception){
        alert('error:'+exception);
    }
});

感谢您的测试和更新。我以为您只发布 JSON,而您发布的是表单数据,其中包括 JSON。

我认为在这种情况下最好的方法是使用 multer 模块来解析上传的数据,如下所示:

server.js

const express = require("express");
const app = express();
const port = 3000;
const multer  = require('multer')
const upload = multer();

app.use(express.static("./"));


app.post('/', upload.any(), function(req,res){
    console.log('Received files from client: ', req.files);
    console.log('Received form data from client: ', req.body);

    console.log('Iterating array:');
    let array = JSON.parse(req.body.finalAray);
    array.forEach((element, index) => {
        console.log(`Element at [${index}]: ${element}`)
    });
    res.json( { "status": "ok" } );
})


app.listen(port, function(){
    console.log(`Example app listening at http://localhost:${port}`)
})

客户端

{     
Dataform.append("finalAray",JSON.stringify(finalArray))
 $.ajax({
    url: '/api/upload/',
    type: 'POST',
    processData: false,
    contentType: false,
    data: Dataform,

    success: function(data){
       //................
    },
    error: function(exception){
        alert('error:'+exception);
    }
});

由于我无法从 req.body 获取数组,我已将 JSON 数组作为查询参数发送到 ajax 的 url post。所以我在服务器的 req.query 中得到了数组作为字符串。然后我解析它并能够迭代。

  $.ajax({
    url: '/api/upload/?finalArray='+JSON.stringify(finalArray),
    type: 'POST',
    processData: false,
    contentType: false,
    dataType : 'application/json; charset=utf-8',
    data: fileform,
     success: function(data){
      // ........
    },
    error: function(exception){
        alert('error:'+exception);
    }
});

在服务器中,

 array=req.query.finalArray;
 JSON.parse(array);
 array.forEach(function(element,index){
        console.log(element);
        console.log(index);
 });