Node.js multer req文件未定义,但为什么?

Node.js multer req文件未定义,但为什么?,node.js,react-native,expo,multer,Node.js,React Native,Expo,Multer,有人能告诉我为什么我的req.file没有定义吗? 我添加了内容头类型, 我添加了single.photo,但没有数据 前端: ## data is equal to this: Object { "filename": "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg", "type": "image/jpg", "uri": "file:

有人能告诉我为什么我的req.file没有定义吗? 我添加了内容头类型, 我添加了single.photo,但没有数据

前端:

## data is equal to this:
Object {
  "filename": "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
  "type": "image/jpg",
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}

const uploadStory = async data => {
  try {
    const form = new FormData();
    form.append('photo', data);
    const options = {
      headers: {
        'Content-Type':'multipart/form-data',
        'Accept':'application/json'
      },
      method: 'POST',
      body: form
    };
    const res = await fetch('http://xxxxxxx.xx:3000/createstory', options);
    const out = await res.json();
    return out;
  } catch(e) {
    console.log(e);
    return e;
  }
};

export default uploadStory;
后端:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function(req, file, cb) {
    console.log(req);
    cb(null, `${file.filename}-${Date.now()}`)
  }
});

const upload = multer({
  storage: storage
}).single('photo');

module.exports = async (req, res, next) => {
  upload(req, res, function(err) {
    if(err) {
      console.log(err)
      return;
    } else if (err instanceof multer.MulterError) {
      console.log(err);
    } else {
      console.log(req.file);
      console.log('hi')
    }
  });
};

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 .................................. ..................................
确保您的数据对象如下所示

{
    name: "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
    type: "image/jpg",
    uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}
数据
对象中,您的
文件名
而不是
名称

将您的
上传更改为此

const upload = multer({
  storage: storage,
});
然后呢,

module.exports = upload.single('photo'), async (req, res) => {
  try {
    console.log(req.body); // Body Here
    console.log(req.file); // File Here
    res.status(500).send('Fetch Completed Successfully');
  } catch (error) {
    console.log(error);
    res.status(500).send('Error');
  }
}

您的数据对象看起来不是正确的类型。它应该是“USVString或Blob(包括诸如File之类的子类)”。您的数据对象实际上看起来是一个普通对象(即对象类型)。@IAmDranged您有示例吗?什么示例?这正是
FormData.append()的文档所说的。在其他情况下,参数将被假定为文本数据,因此,必要时将强制为字符串。结果最终将显示在服务器端的
req.body
上。