基本上,我尝试将formdata发布到自己的api中。我想我对对象数组有问题。
const handleSubmit = async e => {
e.preventDefault()
try{
const formData = new FormData()
formData.append('title',formState.inputs.title.value)
formData.append('image',formState.inputs.image.value)
formData.append('ingredients',JSON.stringify(ingredientData))
formData.append("instructions",JSON.stringify(instructionData))
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}`} })
console.log(responseData)
}
catch(err){
console.log(err.message)
}
}
我可以将其发送到我自己的api。我的服务器拒绝发送响应。
这个食谱controller.js
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. 2',422)
return next(error)
}
const {title,ingredients,instructions,readyInMinutes,servings, ratings,comments, nutrients,price} = req.body
console.log(req.file)
let newIngredients = JSON.parse(ingredients)
let newInstructions = JSON.parse(instructions)
const myIngredients = []
let myInstructions = []
console.log(newIngredients)
console.log(newInstructions)
for(let i = 0;newIngredients.length;i++){
let createIngredient = new Ingredient({
name:newIngredients.name,
amount:newIngredients.amount,
measure:newIngredients.measure
})
myIngredients.push(createIngredient)
}
for(let i = 0;i<newInstructions.length;i++){
let createInstruction = new Instruction({
content:newInstructions.content
})
myInstructions.push(createInstruction)
}
console.log(myInstructions)
console.log(myIngredients)
const createdRecipe = new Recipe({
title,
image:req.file.path,
ingredients:myIngredients,
instructions:myInstructions,
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})
}
我获取这些数组并应用Json。parse()将json字符串转换为js对象。
配方模型
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
mongoose.set('useCreateIndex', true);
const ingredientSchema = require("./Ingredient").schema;
const instructionSchema = require("./Instruction").schema;
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:[ingredientSchema],
instructions:[instructionSchema],
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
我使用mongodb作为数据库。
我在for循环中犯了愚蠢的错误:)
for(let i = 0;newIngredients.length;i++){
let createIngredient = new Ingredient({
name:newIngredients.name,
amount:newIngredients.amount,
measure:newIngredients.measure
})