简体   繁体   English

如何在 React JS 中发送表单数据中的对象数组?

[英]How to send an array of objects inside form data in React JS?

I have been trying to send an array of objects inside a form data using React JS at the backend.我一直在尝试在后端使用 React JS 在表单数据中发送一组对象。 When I am pushing the data inside form data using its append method, it is showing my array as this当我使用其 append 方法将数据推送到表单数据中时,它显示我的数组如下

SurveyAnswers: [object object, object, object]

in browsers.network tab but we have been receiving null at the backend.在 browsers.network 选项卡中,但我们在后端收到 null。 We have checked the backend API it is working fine when we are sending data using postman, But, when data is being sent through frontend, it is having a problem.我们已经检查了后端 API 当我们使用 postman 发送数据时它工作正常,但是,当通过前端发送数据时,它有问题。 Following is my code snippet:以下是我的代码片段:

const answers = [ 
  {
    Answer: "Hello World",
    QuestionId: 26,
    UserId: 190
  },
  {
    Answer: "Document",
    File: file,
    UserId: 190,
    QuestionId: 23
  }
]

const onSubmit = () => {
  const data = new FormData();
  data.append("SurveyAnswers", answers);
  const res = await executeAddSurveyFormAnswers({ data: data });     
  console.log('response, res);
}

If you're trying to pass an object, you will need to "stringify" the object如果您尝试传递 object,则需要“字符串化”object

data.append("SurveyAnswers", JSON.stringify(answers))

Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object. I don't know what language you are using for server side, but you can do a search for "parse json string in XXX" <-XXX is the language (ie.. C#)然后在后端,您需要“解析”或“反序列化”字符串以转换回 object。我不知道您在服务器端使用的是什么语言,但您可以搜索“解析 json 字符串in XXX" <-XXX 是语言(即.. C#)

Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object.然后在后端,您需要“解析”或“反序列化”字符串以转换回 object。

If you're using Node.js, you'd use JSON.parse() in order to deserialize the stringified object to a native javascript object.如果您使用的是 Node.js,您将使用 JSON.parse() 以将字符串化的 object 反序列化为本机 javascript object。

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

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