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
Check out querystring.
You can use it as follows:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
You can post axios data by using [FormData()][1] like :
var bodyFormData = new FormData();
And then add the fields to the form you want to send :
bodyFormData.append('userName', 'Fred');
If you are uploading images, you may want to use .append
bodyFormData.append('image', imageFile);
And then you can use axios post method (You can amend it accordingly)
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
You can read more here -
https://developer.mozilla.org/en-US/docs/Web/API/FormData https://github.com/axios/axios/issues/318
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:
<input type="file" id="image" accept="image/png"/>
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)