reactjsaxiosinternal-server-errorstrapi

axios POST request to strapi image upload [Internal Server Error]


I'm uploading an image to strapi using axios but the response is 500 error. However in Postman the request is 200

POSTMAN

POSTMAN Request

AXIOS CODE

let bodyFormData = new FormData();

      bodyFormData.append('files', this.state.avatar, this.state.avatar.name)
      bodyFormData.append('ref', 'user')
      bodyFormData.append('refId', getId())
      bodyFormData.append('field', 'avatar')
      bodyFormData.append('source', 'users-permmissions')

      axios({
        method: 'post',
        url: `${strapi}/upload`,

        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${withToken()}`,

          },
          data: bodyFormData,
      }).then(res=>console.log(res.data)).catch(err=>{console.log(err.response.data.message)})

what's supposed to be the issue here?

Here's part of the strapi user model

{
     "avatar": {
      "model": "file",
      "via": "related",
      "plugin": "upload",
      "required": false
    }
}


Solution

  • The solution is to throw Axios in the trash. I struggled with this for a day of my life that I will never get back. There's a longish, years-old thread at https://github.com/axios/axios/issues/318 with people complaining about being unable to get multipart form uploads to work with Axios.

    I switched to the request-promise module and got it to work within minutes, using the following simple code:

    const fs = require("fs-extra");
    const rp = require('request-promise');
    let out = await rp({
        method: 'POST',
        uri: 'http://mystrapihost/upload',
        formData: {
            // Like <input type="text" name="ref">
            'ref': "customer",  // name of the Strapi data type, singular
            'field': "attachments", // a field named "attachments" of type "Media"
            'refId': "838e238949ewhd82e8938299e289e99", // strapi ID of object to attach to
            // Like <input type="file" name="files">
            "files": {  // must be called "files" to be "seen" by Strapi Upload module
                name: "myfile.pdf",
                value: fs.createReadStream("/path/to/myfile.pdf"),
                options: {
                    filename: "myfile.pdf",
                    contentType: 'application/pdf'
                },
            },
        },
        headers: {Authorization: 'Bearer myjwtgobbledygook123456'}  // put your JWT code here
    });
    console.log(out);
    

    Enjoy!!