axios POST 请求 strapi 图片上传 [内部服务器错误]

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

我正在使用 axios 将图像上传到 strapi,但响应是 500 错误。但是在 Postman 中请求是 200

邮递员[=3​​0=]

AXIOS 代码

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)})

这里应该是什么问题?

这是 strapi 用户模型的一部分

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

解决办法是把Axios扔进垃圾桶。我为此苦苦挣扎了一天,再也回不来了。 https://github.com/axios/axios/issues/318 上有一个较长的、多年的线程,人们抱怨无法通过 Axios 进行多部分表单上传。

我切换到 request-promise 模块并在几分钟内让它工作,使用以下简单代码:

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);

尽情享受!!