axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload conta
Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:
const FormData = require('form-data')
const fs = require('fs')
const path = require('path')
const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
headers: formData.getHeaders()
})
headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()async and await above, you can change them to plain Promise statements if you don't like themheaders: { ...yourHeaders, ...formData.getHeaders() }Newly added content below:
Browser's FormData is different from the NPM package 'form-data'. The following code works for me in browser:
HTML:
JavaScript:
const formData = new FormData()
// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')
// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)