【问题标题】:axios POST request to strapi image upload [Internal Server Error]axios POST请求到strapi图像上传[内部服务器错误]
【发布时间】:2020-02-05 14:27:50
【问题描述】:

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

邮递员

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

【问题讨论】:

  • 你能告诉我们你是如何声明变量strapi的吗?
  • @SydneyY 我添加了用户模型
  • @SydneyY 我删除了bodyFormData.append('field', 'avatar') 部分然后它可以工作,但是,我需要该部分将其上传到用户模型
  • data: JSON.stringify(bodyFormData) 和 "Content-Type": "application/json"?
  • 它返回 400 (Bad Request) id: "Upload.status.empty" message: "Files are empty"。

标签: reactjs axios internal-server-error strapi


【解决方案1】:

解决方法是将 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);

享受!!

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2019-04-27
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多