Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Content-Type in axios header to fix a 415 error

I am trying to send a file to my back-end through an axios post request.

This is the error I currently have:

cherrypy._cperror.HTTPError: (415, 'Expected an entity of content type application/json, text/javascript')

From what I have read I need to change the Content-Type in my post request, I looked around I am currently attempting to do so like this:

handleUploadButton(e){
            const upload_file = this.state.file;
            const formData = new FormData();
            formData.append('file', upload_file);
            const request = axios.post(someUrl, formData, {headers: {
                "Content-Type": "application/json"}
            })
                .then(function (response) {
                    console.log('successfully uploaded', upload_file);
                });
    }

Not sure if relevant, but all this is happening through a reactjs form. This is my current Content-Type: Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBwjjjGuJEySeXdRU

I have no idea where to go from here. Any help would be greatly appreciated.

like image 254
theJuls Avatar asked Jan 04 '17 16:01

theJuls


2 Answers

SignIn = () => {
    console.log('login clicked')
    let data = JSON.stringify({
        password: this.state.password,
        username: this.state.email
    })

    axios.post('url', data, {
        headers: {
            'Content-Type': 'application/json',
        }
    }
    )
}
like image 61
Ben Ahlander Avatar answered Sep 22 '22 06:09

Ben Ahlander


This worked for me:

const formData = new FormData();
formData.append('data', new Blob([JSON.stringify(data)], { type: 'application/json'}));
formData.append('file', file);

return axios.put(`${url}`, formData)
  .then((response) => { console.log(response) })
  .catch((error) => { console.log(error) })

I took this from another answer of a similar issue. You can check the original answer here.

like image 35
Daniel Cortes Avatar answered Sep 25 '22 06:09

Daniel Cortes