NodeJS-FormData将未定义的值发送到服务器

时间:2019-04-14 11:28:42

标签: javascript node.js reactjs axios form-data

我正在尝试使用Form-Data和axios将数据发送到服务器,但是它发送未定义的值

用于检测到我尝试在服务器中记录所有值并在客户端中记录formdata,但是服务器记录了未定义的值,并且客户端记录了空对象 这是我的代码

客户:

 handleFormSubmission(e) {
    e.preventDefault();

    var Data = new FormData();    

    Data.append('image', this.fileRef.current.files[0])
    Data.append('name', this.state.name);
    Data.append('time', this.state.time);
    Data.append('portion', this.state.portion);
    Data.append('ingredients', JSON.stringify(this.state.ingredients));
    Data.append('method', this.state.method);
    Data.append('level', this.state.level);
    Data.append('tags', JSON.stringify(this.state.tagsToSend));
      axios.post('/api/post-recipe', Data, {

     headers: {
        'Content-Type': 'multipart/form-data'
     }
   }).then(res => res.data)
     .then(data =>{
      console.log(data.dish)
 })
 .catch(err => {
    if(err.response){
        if(err.response.data.redirect === true){
            window.location.replace(err.response.data.location)
        }
        if(err.response.data.message){
        alert(err.response.data.message)
        }
    }
 })
}

和服务器:

 //multer part
 const storage = multer.diskStorage({

 destination: (req, file, callback) => {
 const userPath = path.join(imgStoragePath, req.userId);
 fs.mkdir(
  userPath,
  () => callback(null, userPath)
 )
 },

filename: (req, file, callback) => {
const filenameParts = file.originalname.split('.');
const ext = filenameParts.pop();
const basename = filenameParts.join('.');
const additionalPath = Date.now() + '' + uuid() + '' + 
Math.floor(Math.random() * (2000 - 500)) + 500;
callback(null, basename + '-' + additionalPath + '.' + ext);
}

})

const upload = multer({
storage,
limits: '1mb',
})

//route handling (i have validation in comments because there are some bugs too and i am concentrated on this problem)

 router.post('/', upload.single('image'), async (req, res) => {
 try {

const {
  name,
  time,
  portion,
  ingredients,
  method,
  level,
  tags
} = req.body
const { filename } = req.file;
 /* if (!req.file) {
  return res.status(409).send({
    message: 'გთხოვთ აირჩიოთ მინიმუმ 1 ფოტო'
  })
}



if (name.trim().length < 1) {
  return res.status(409).send({
    message: 'მიუთითეთ კერძის სახელი'
  })
}

if (time.trim().length < 1) {
  return res.status(409)({
    message: 'მიუთითეთ მომზადების დრო'
  })
}

if (!numberToTest.test(time)) {
  return res.status(409).send({
    message: 'დრო ჩაწერეთ ციფრების საშუალებით'
  })
}

if (portion.trim().length < 1) {
  return res.status(409).send({
    message: 'მიუთითეთ პორციის რაოდენობა'
  })
}

if (!numberToTest.test(portion)) {
  return res.status(409).send({
    message: 'პორცია ჩაწერეთ ციფრების საშუალებით'
  })
}

JSON.parse(ingredients).map(({
  ingredient,
  quantity
}) => {
  if (ingredient.trim().length < 1 || quantity.trim().length < 1) {
    return res.status(409).send({
      message: 'მიუთითეთ ინგრედიენტები სრულად'
    })
  }
})

if (method.trim().length < 20) {
  return res.status(409).send({
    message: '"მომზადების მეთოდი"-ს ველში უნდა იყოს მინიმუმ 20 ასო'
  })
}

if (!level == 'მარტივი' || level == 'საშუალო' || level == 'რთული') {
  return res.status(409).send({
    message: 'მიუთითეთ კერძის მომზადების სირთულე'
  })
}

if (JSON.parse(tags).length < 1) {
  return res.status(409).send({
    message: 'მიუთითეთ მინიმუმ 1 მონიშვნა (თეგი)'
  })
}

/*fs.readFile('../tags.json', 'utf8', function (err, content) {
  if (err) {
    return res.status(500).send({
      message: err.message
    })
  }

  const decodedContent = JSON.parse(content)

  if (!decodedContent.tags.includes(JSON.parse(tags))) {
    return res.status(409).send({
      message: 'მიუთითეთ ჩვენს მიერ შემოთავაზებული მონიშვნები (თეგები)'
    })
  }

})*/

 /*   var duplicateTagsGuard = Object.create(null);

for (var co = 0; co < tags.length; co++) {
  let val = tags[co];

  if (val in duplicateTagsGuard) {
    return res.status(409).send({
      message: 'ნუ გამოიყენებთ ერთ მონიშვნას (თაგს) რამდენჯერმე'
    })
  }

  duplicateTagsGuard[val] = true

}
*/

const user = await User.findById(req.userId, '-password -_id -email -loginAttmepts -lockUntil').lean();

const dish = await Dish.create({
  author: user.username,
  name: name,
  time: time,
  portion: portion,
  ingredients: JSON.parse(ingredients),
  method: method,
  level: level,
  tags: JSON.parse(tags),
  createdAt: 'Date- ' + new Date().toLocaleDateString() + ' Time- ' + new Date().toLocaleTimeString()
})

console.log('დიში ' + dish.toObject())


return res.status(200).send({
  dish: JSON.stringify(dish)
})




} catch (error) {
return res.status(500).send({
  message: error.message
  })
 }
})

,日志为:

name undefined time undefined portion undefined ingredients undefined method undefined level undefined tags undefined

什么问题?我该怎么解决

1 个答案:

答案 0 :(得分:1)

upload.single('image')可能会滤除请求正文,因为它不是图像内容类型,但从注释看来,问题可能出在其他地方。

检查它似乎append似乎是为表单字段添加二进制实体,而set似乎是针对表单字段的添加-请参见 axios post request to send form data