简体   繁体   中英

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. When I am pushing the data inside form data using its append method, it is showing my array as this

SurveyAnswers: [object object, object, object]

in browsers.network tab but we have been receiving null at the backend. 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. 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

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

Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object.

If you're using Node.js, you'd use JSON.parse() in order to deserialize the stringified object to a native javascript object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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