【问题标题】:Getting req.body and req.file as empty when uploading file with axios使用 axios 上传文件时将 req.body 和 req.file 设为空
【发布时间】:2020-08-08 00:07:18
【问题描述】:

这里是前端:

let file = this.$refs.file.files[0] //"this" refers to vue
  let data = new FormData();
  data.append("image", file, file.fileName);
  data.append("content", this.content);
  data.append("title", this.title);
  data.append("action_type", "add_article");

  axios
    .post("http://localhost:3000/api", data, {
      headers: {
        // "accept": "application/json",
        // "Accept-Language": "en-US,en;q=0.8",
        // "Content-Type": `multipart/form-data; boundary=${data._boundary}`,
        // "auth": util.getCheckedToken(),
        'content-type': 'multipart/form-data'
      }
    })
    .then(response => {
      alert("success!", response);
    })
    .catch(error => {
      alert("fail!", error);
    });

后端的某些部分:

app.use(multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => { cb(null, '../static/images'); },
    filename: (req, file, cb) => { cb(null, my_random.fileName(file.originalname)); }
  }),
  fileFilter: (req, file, cb) => { cb(null, "image/png image/jpg image/jpeg".split(' ').includes(file.mimetype)); }
}).single('image'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

查看我正在使用的工具的标签。我没有收到错误消息,并且 req.file 和 req.body 为空。问题的原因可能是什么?

【问题讨论】:

  • 你用邮递员试过你的api吗?
  • @ali-hosseini 没有。我不知道如何用邮递员尝试我的 api。我什至不明白这是什么意思。
  • 我想证明您的 API 在没有您的 nuxt 应用程序的情况下可以正常工作,因此为此目的,有一个像 postmaninsomnia 这样的软件可以帮助您做到这一点。您可以从https://www.postman.com/ 获得邮递员,从https://insomnia.rest/ 获得失眠症,然后安装您喜欢的一个(这两个做几乎相同的事情,安装其中一个就足够了)然后在应用程序中输入您的 URL 并用‍@调用它987654328@方法(YouTube上有很多这些工具的视频)。然后测试你的 API 看看它是否有效
  • @ali-hosseini api 适用于标准(纯文本)表单。

标签: node.js express vue.js nuxt.js multer


【解决方案1】:

在尝试发送文本/csv 文件时遇到类似问题,已通过在路由之前解析内容类型来解决。 像这样:

app.use(bodyParser.raw({type: multipart/form-data}));

之前

app.use(multer({}))

bodyParser.raw([options]) 返回将所有主体解析为 Buffer 并仅查看 Content-Type 标头与类型选项匹配的请求的中间件

【讨论】:

  • 如果你能解释为什么这是答案,这个答案会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2019-02-10
  • 1970-01-01
  • 2021-06-02
  • 2017-11-24
  • 2021-01-16
相关资源
最近更新 更多