-1

i want to pass formdata and data in body parameter in axios post request, i tried some way but its not working. //code

const form = new FormData();


    form.append("file", this.state.selectedFile);

    const data={
       token:localStorage.getItem('token'),

    }

    axios.post('http://localhost:3000/api/upload',form, {
            onUploadProgress: ProgressEvent => {
            this.setState({
                loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
            })
        }, 
    })
    .then(response=>{
        console.log(response)
    }).then(res => { 
        toast.success('upload success')


    })
    .catch(err => { 
        toast.error('upload fail')
    })
John
  • 55
  • 1
  • 10
  • Does this answer your question? [axios post request to send form data](https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data) – layonez Apr 01 '20 at 13:56

2 Answers2

0

You need to provide valid headers for respective content type

axios({
    method: 'post',
    url: 'http://localhost:3000/api/upload',
    data: form,
    headers: {'Content-Type': 'multipart/form-data' }
    })
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

You are trying to pass a file in FormData which is not possible and you need to use FormUrlEncoded. To do so you also need to install a npm package named query-string and then your data property would look something like this:

import qs from 'query-string';
...
axios.post(..., data:qs.stringify({
  file: this.state.selectedFile
})
CallMeArta
  • 161
  • 8
  • my formData is working fine, i need to send some data in body as well which is creating problem – John Apr 01 '20 at 14:45