Reputation: 7460
I need to do a PATCH to the server which expects a very specific body format. Something like this:
{
file: MY_FILE_OBJECT
name: 'Name',
nestedObject: {
nestednestedObject1: {
name: 'Some other name'
},
nestednestedObject2: {
name: 'Yet another name'
},
}
}
Because I need to be able to pass in a file, I have to make this into a FormData
object. So, for the main fields it is nice and easy to form the body of the request
const data = new FormData()
data.append('file', file, file.name)
data.append('name', 'Name')
However, how can I do the nested translation
object? I have seen in another thread the suggestion of me doing a blob. Which should be something like this:
const fullPatchObject = {
nestedObject: {
nestednestedObject1: { name: 'Some other name' }
nestednestedObject2: { name: 'Yet another name' }
}
}
const blob = new Blob([JSON.stringify(fullPatchObject)], { type: 'application/json' })
data.append('nestedObject', blob)
This however does not work. I am using multer in the server to handle the file, and I get the following error object:
name: 'MulterError',
message: 'Unexpected field',
code: 'LIMIT_UNEXPECTED_FILE',
field: 'nestedObject'
Keep in mind that if I do not use the nested object, it all works as expected, for both the file and the fields I am attempting to PATCH. The issue seems to be that multer thinks my nestedObject
is perhaps also a file? The thing is... Well... It isn't, I just want it to be passed in as field like the name
field.
Am I missing something? What is a way I can send a nested object using the FormData
?
Upvotes: 4
Views: 6965
Reputation: 780879
Try using array-style names:
data.append("nestedObject[nestedNestedObject1][name]", "Some other name");
data.append("nestedObject[nestedNestedObject2][name]", "Yet another name");
Upvotes: 13