后端FormData为空

FormData is empty at the backened

我正在使用 axios post 一个表单(包括文件),在反应中使用 FormData 来支持,但请求数据在支持时是空的。

注意:Chrome 浏览器的负载中的 formData 不为空。
App.js

const App = ({data, id}) => {
  const [temperoryLink, setTemperorylink] = useState('');
 const [assignment, setAssignment] = useState('');

 const handleFileUpload = (e) => {
   const linkObject = e.target.files[0];
   const temperoryLink = URL.createObjectURL(linkObject);
   setTemperorylink(temperoryLink);
   setAssignment(linkObject);
 };

const handleSubmit = async (e) => {
   e.preventDefault();
   try {
     const formData = new FormData();
     formData.append('file', assignment);
     formData.append('ta_id', data.assigned_TA);
     formData.append('assignmentId', id);

       const response = await SubmitAssignmentApi(formData);
      
   } catch (err) {
     console.log(err);
   }
 }

return (
 <div>
  <label className="btn">
    <input
      type="file"
      name="file"
      style={{ display: 'none' }}
      onChange={handleFileUpload}
      required
     />{' '}
     Upload file
   </label>
   <button type="submit" className="btn bg-red-five" onClick={handleSubmit}>
      Submit
   </button>
</div>
)
}

submit.js

export async function SubmitAssignmentApi(formData) {
  try {

    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`
      }
    };
    const response = await axios.post('http://localhost:5000/api/v1/submission/', formData, config);
    return response.data;
  } catch (err) {
    console.log(err);
  }
}

下面的代码是一个后端代码,请求从客户端发送到服务器 backened.js

const SubmitAssignment = require('../../../../controller/api/v1/assignment/submission');
router.post('/', [
  body('assignmentId').not().isEmpty().withMessage('Assignment ID is required'),
  body('ta_id').not().isEmpty().withMessage('Teaching Assistant Id is required'),
], authenticateUserToken, SubmitAssignment.submit);


const upload = multer({ dest: 'uploads/' });

exports.submit = async(req, res) => {
  try {
    // validate client input data
    upload.single('file');
    console.log(req.body);
    console.log(req.file);

    const error = validationResult(req);
    if (!error.isEmpty()) {
      return res.status(422).json({
        type: 'warining',
        message: error.array()[0].msg,
      });
    }

   } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: 'Server Error',
    });
  }
};

如有任何建议,我们将不胜感激。

upload.single('file') returns一个中间件函数。因此,您应该将它添加到 router.post 函数调用的中间件列表中,或者按如下方式正确调用它(这种情况很少见);

const theRealUpload = upload.single('file');
theRealUpload (req, res, function (err) {
    if (err) {
      // Handle error
    }

    // Do your stuff here...
})