如果我使用axios来发布数据,如何使用formData来发布对象数组?

时间:2020-04-16 13:31:10

标签: javascript reactjs axios multipartform-data http-status-code-500


            const formData = new FormData()
            const my_ingredients = new Array()
            const my_instructions = new Array()

            my_ingredients.push({name:formState.inputs.iName.value,amount:parseFloat(formState.inputs.amount.value),measure:formState.inputs.measure.value})
            console.log(my_ingredients)

            my_instructions.push({content:formState.inputs.content.value})

            formData.append('title',formState.inputs.title.value)
            formData.append('image',formState.inputs.image.value)
            formData.append('ingredients',JSON.stringify(my_ingredients))
            formData.append('instructions',JSON.stringify(my_instructions))
            formData.append('readyInMinutes',formState.inputs.readyInMinutes.value)
            formData.append('servings',formState.inputs.servings.value)
            formData.append('price',formState.inputs.price.value)
            formData.append('creator',auth.userId)


            const responseData = await axios.post(
                process.env.REACT_APP_BACKEND_URL+'/recipes/new',
                 formData,{
                 headers: {Authorization : `Bearer ${auth.token}`} })

基本上,我使用这种方法,但是得到了500个错误代码。当我检查devtools上的network标签时,我没有任何令牌错误。似乎发布了它,但它仍然返回500错误代码。

enter image description here

食谱模型

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
mongoose.set('useCreateIndex', true);


const commentSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  content: {
    type: String,
    required: true,
    maxLength: 280
  }
}, {
  timestamps: true, // this adds `createdAt` and `updatedAt` properties
  toJSON: {
    // whenever the comment is converted to JSON
    transform(doc, json) {
      delete json.__v
      return json
    }
  }
})
const recipeSchema = new mongoose.Schema({
  title:{
    type:String,
    required:true
  },
  image:{
    type:String,
    required:true
  },
  ingredients:[{
    name:{
      type:String,
      required:true
    },
    amount:{
      type:Number,
      required:true
    },
    measure:{
      type:String,
      required:true
    }
  }],
  instructions:[{
    content:{
      type:String,
      required:true
    }
  }],
  readyInMinutes:{
    type:Number,
    required:true
  },
  servings:{
    type:Number,
    required:true
  },
  price:{
    type:Number,
    required:true
  },
  creator:{
    type:mongoose.Types.ObjectId,
    required:true,
    ref:'User'
  },
  ratings:[{
    point:{
      type:Number,
      required:true
    }
  }],
  comments:[commentSchema],
  nutrients:[{
    name:{
      type:String,
      required:true
    },
    amount:{
      type:Number,
      required:true
    }
  }],



})
recipeSchema.plugin(uniqueValidator)                                            //We plugin wiht mogooseValidator with our schema.
module.exports = mongoose.model('Recipe',recipeSchema)                          //We called User model with recipeSchema

收件人控制器

const HttpError = require('../models/HttpError')
const bcrypt = require('bcryptjs')
const jwt= require('jsonwebtoken')
const Recipe = require('../models/Recipe')
const User = require('../models/User')
const {validationResult} = require('express-validator')
const mongoose = require('mongoose')
const uuid = require('uuid/v4')
const fs = require('fs')
const path = require('path')

const getAllRecipes = async (req, res, next) => {                               //We get all recipes to show users' recipes
   let recipes
   try{
     recipes = await Recipe.find({}).exec()
   }
   catch(err){
     const error = new HttpError('Something went wrong',500)
     return next(error)
   }
   if(!recipes){
     const error = new HttpError('Could not find any recipe',404)
     return next(error)
   }

   res.status(200).json({recipes:recipes.map(recipe => recipe.toObject({getters:true}))})
}
const getRecipesByUserId = async (req, res, next) => {                          // We want to get recipes by userId, so we can show user's recipes
   const userId = req.params.uid
   let existingUser
   try{
      existingUser = await User.findById(userId).populate('recipes')
   }
   catch(err){
     const error = new HttpError('Could not find any recipes provided user id',500)
     return next(error)
   }
   if(!existingUser){                                                           // We check if this user exist or not in our database.
     const error = new HttpError('Could not find any user provided user id',404)
     return next(error)
   }
   res.status(200).json({recipes:existingUser.recipes.map(recipe => recipe.toObject({getters:true}))})
}
const createRecipe = async (req, res, next) =>{                                 //We create a new recipe
  const errors = validationResult(req)
  if(!errors.isEmpty()){
    const error = new HttpError('Invalid inputs passed, please check your data.',422)
    return next(error)
  }
  const {title,ingredients,instructions,readyInMinutes, servings, ratings,comments, nutrients,price} = req.body

  const createdRecipe = new Recipe({
    title,
    image:req.file.path,
    ingredients,
    instructions,
    readyInMinutes,
    servings,
    price,
    creator:req.userData.userId,
    ratings:[],
    comments:[],
    nutrients:[],

  })
  let user
  try{
    user = await User.findById(req.userData.userId)                             // When we add a new recipe we need user's recipes array,too.That's why We need user who add this recipe.
  }
  catch(err){
    const errors = new HttpError('Something went wrong',500)
    return next(error)
  }
  if(!user){
    const error = new HttpError('This user does not exist',422)
    return next(error)
  }
  try{                                                                          // We need to do this.Because When we add a new recipe that affect user's recipes array, too.We want to make sure to add this recipe both collections.
      const sess = await mongoose.startSession()
      sess.startTransaction()
      await  createdRecipe.save({session:sess})
      user.recipes.push(createdRecipe)
      await user.save({session:sess})
      await sess.commitTransaction()
  }
  catch(err){
    const error = new HttpError('Created recipe failed, please create again 2',500)
    return next(error)
  }
  res.status(201).json({recipe:createdRecipe})
}
const updateRecipe = async (req, res, next) => {                             
  const errors = validationResult(req)
  if(!errors.isEmpty()){
    const error = new HttpError('Invalid inputs passed, please check your data.',422)
    return next(error)
  }
  const recipeId  = req.params.rid
  let existingRecipe
  try
  {
    existingRecipe = await Recipe.findById(recipeId).populate('creator')
  }
  catch(err){
    const error = new HttpError('Something went wrong could not update place', 500)
    return next(error)
   }
   if(existingRecipe.creator.id !== req.userData.userId){                       // We want to know that creator and currentUser same person or not.
      const error = new HttpError('You are not allowed to update this recipe ',403)
      return next(error)
   }
    const {title,ingredients,instructions,readyInMinutes, servings, nutrients,price} = req.body
    existingRecipe.title = title
    existingRecipe.image = req.file.path
    existingRecipe.ingredients= ingredients
    existingRecipe.instructions = instructions
    existingRecipe.readyInMinutes = readyInMinutes
    existingRecipe.servings = servings
    existingRecipe.nutrients  = nutrients
    existingRecipe.price = price
    try{
      await existingRecipe.save()
    }
    catch(err){
      const error = new HttpError('Something went wrong could not update recipe', 500)
      return next(error)
     }
     res.status(200).json({recipe:existingRecipe.toObject({getters:true})})
}
const deleteRecipe = async (req, res, next) => {
  const recipeId = req.params.rid
  let recipe
  try{
    recipe = await Recipe.findById(recipeId).populate('creator')
  }
  catch(err){
    const error  = new HttpError('Something went wrong',500)
    return next(error)
  }
  if(!recipe){
    const error = new HttpError('This recipe does not exist',404)
    return next(error)
  }
  if(recipe.creator.id !== req.userData.userId){                                // We want to know that creator and currentUser same person or not.
    const error = new HttpError('You are not allowed to delete this recipe',403)
    return next(error)
  }
  const imagePath = recipe.image
  try{
    const sess = await mongoose.startSession()
    sess.startTransaction()
    await recipe.remove({session:sess})
    recipe.creator.recipes.pull(recipe)
    await recipe.creator.save({session:sess})
    await sess.commitTransaction()
  }
  catch(err){
    const error  = new HttpError('Something went me wrong',500)
   return next(error)
  }
  fs.unlink(imagePath, err => {
    console.log(err);
  })

     res.status(200).json({message:'Deleted recipe'})
}


exports.getAllRecipes = getAllRecipes
exports.getRecipesByUserId = getRecipesByUserId
exports.createRecipe = createRecipe
exports.updateRecipe = updateRecipe
exports.deleteRecipe = deleteRecipe

因此,我将mongodb用于数据库。当我检查服务器时,它不会说清除错误。

0 个答案:

没有答案