简体   繁体   English

为什么服务器从使用 axios 发出的 POST http 请求中获取空的 request.body?

[英]Why is server getting empty request.body from POST http request made with axios?

I'm trying to send a file (.obj file) via formdata to my node server, it appears that everything is fine until the controller of the endpoint on the server throws an error that seems to be like the formdata parser is receiving an empty formdata object, here is the error in question.我正在尝试通过 formdata 将文件(.obj 文件)发送到我的节点服务器,看起来一切都很好,直到服务器上端点的控制器抛出一个错误,似乎 formdata 解析器正在接收一个空formdata 对象,是有问题的错误。 Now, here's my code:现在,这是我的代码:

Fron-end (where the request is being executed):前端(正在执行请求的地方):

const data = new FormData();
data.append('file', this.props.filesSubmit, this.props.filesSubmit.name);
for (var pair of data.entries()) {
  console.log(pair[0] + ', ' + pair[1]);
}
await axios
  .post(
    'https://hushpuppys-3d-hub-api.herokuapp.com/api/v1/modelfiles/',
    data,
    {
      headers: {
        'Content-Type': undefined,
      },
    }
  )
  .then((res) => {
    console.log('File Upload Successful! Res: ', res);
  })
  .catch((err) => {
    console.log(err);
  });

Back-end endpoint Controller (Where request is received):后端端点控制器(接收请求的地方):

const AWS = require('aws-sdk');
const fs = require('fs');
const fileType = require('file-type');
const bluebird = require('bluebird');
const multiparty = require('multiparty');

// Keys Configuration to Access AWS
AWS.config.update({
  accessKeyId: '[I erased this]',
  secretAccessKey: '[I erased this]',
});

// Configuring AWS to work with promises
AWS.config.setPromisesDependency(bluebird);

// Creating S3 instance
const s3 = new AWS.S3();

// abstracts function to upload a file returning a promise
const uploadFile = (buffer, name, type) => {
  const params = {
    ACL: 'public-read',
    Body: buffer,
    Bucket: '[I erased this]',
    ContentType: type.mime,
    Key: `${name}.${type.ext}`,
  };
  return s3.upload(params).promise();
};

exports.fileUploaderController = (req, res) => {
  const form = new multiparty.Form();
  form.parse(req.body, async (error, fields, files) => {
    if (error) throw new Error(error);
    try {
      const path = files.file[0].path;
      const buffer = fs.readFileSync(path);
      const type = fileType(buffer);
      const timestamp = Date.now().toString();
      const fileName = `bucketFolder/${timestamp}-lg`;
      const data = await uploadFile(buffer, fileName, type);
      return res.status(200).send(data);
    } catch (error) {
      return res.status(400).send(error);
    }
  });
};

I want to also add the code of my app.js where other middlewares manipulate the body, maybe that's also relevant to solve the problem:我还想在我的 app.js 中添加其他中间件操作主体的代码,也许这也与解决问题有关:

const express = require('express');

const modelRouter = require('./routes/modelRoutes');
const modelFilesRouter = require('./routes/modelFilesRoutes');
const cors = require('cors');

const app = express();

// MIDDLEWARES
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));

// ROUTES
app.use('/api/v1/models', modelRouter);
app.use('/api/v1/modelfiles', modelFilesRouter);

module.exports = app;

Ok, I got this problem solved a few minutes ago.好的,我几分钟前解决了这个问题。 I was basically passing a wrong parameter in the form.parse() method in the fileUploaderController controller from the Controller file, the method form.parse() needs the whole req variable to be passed as a parameter, not the body of the request ( req.body ) as I did in the code I posted with the question.我基本上是在从控制器文件的fileUploaderController控制器中的form.parse()方法中传递了一个错误的参数,方法form.parse()需要将整个req变量作为参数传递,而不是请求的主体( req.body ),就像我在随问题发布的代码中所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM