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 contains data. What am I doing wrong?
Axios POST Request:
var body = {
userName: 'Fred',
userEmail: 'Flintstone@gmail.com'
}
axios({
method: 'post',
url: '/addUser',
data: body
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Browser Response:
If I set headers as:
headers:{
Content-Type:'multipart/form-data'
}
The request throws the error
Error in posting multipart/form-data. Content-Type header is missing boundary
If I make the same request in postman it's working fine and sets values to my POJO class.
Can anyone explain how to set boundary or how can I send form data using axios.
You can post axios data by using FormData() like :
var bodyFormData = new FormData();
And then add the fields to the form you want to send :
bodyFormData.set('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,
config: { 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
Check out querystring.
You can use it as follows:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
In my case I had to add the boundary to the header like the following:
const form = new FormData();
formData.append(item.name, fs.createReadStream(pathToFile));
const response = await axios({
method: 'post',
url: 'http://www.yourserver.com/upload',
data: form,
headers: {
'content-type': `multipart/form-data; boundary=${form._boundary}`,
},
});
This solution is also useful if you're working with React Native.
Upload (multiple) binary files
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 concat = require('concat-stream')
const formData = new FormData()
formData.append('json', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('attachment', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
formData.pipe(concat({ encoding: 'buffer' }, async data => {
const r = await rc.post('/restapi/v1.0/account/~/extension/~/fax', data, {
headers: formData.getHeaders()
})
console.log(r.data)
}))
- Instead of
headers: {'Content-Type': 'multipart/form-data' }
I preferheaders: formData.getHeaders()
- I need to use
concat-stream
to concat multiple file streams - I use
async
andawait
above, you can change them to plain Promise statements if you don't like them
Even More straightforward:
axios.post('/addUser',{
userName: 'Fred',
userEmail: 'Flintstone@gmail.com'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT
packageData: (data) => {
const form = new FormData()
for ( const key in data ) {
form.append(key, data[key]);
}
return form
}
Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following
packageData: (obj, form, namespace) => {
for(const property in obj) {
// if form is passed in through recursion assign otherwise create new
const formData = form || new FormData()
let formKey
if(obj.hasOwnProperty(property)) {
if(namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File, use recursion.
if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
objectToFormData(obj[property], formData, property);
} else {
// if it's a string or a File
formData.append(formKey, obj[property]);
}
}
}
return formData;
}
来源:https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data