Reputation: 15
let formdata = new FormData();
const token = JSON.parse(localStorage.getItem("UserAuth")).token;
formdata.append('model', model)
formdata.append('make', make)
formdata.append('vin', vin)
formdata.append('year', year)
formdata.append('askingprice', askPrice)
formdata.append('customer', _id);
formdata.append('mileage', mileage)
formdata.append('bodytype', bodyType)
formdata.append('condition', condition)
formdata.append('image', pictures)
let data = new FormData()
let headers = {
// withCredentials: true,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
}
axios.post('http://localhost:8000/api/tradein/create/5e838c95f2064847a843a114', data, headers)
.then((res) => {
console.log(res)
}).catch((err) => console.log(err))
So i'm trying to add the the form data object to the backend rest api, but I get an error code 400. I believe my form is not correctly submitting, but I do not see why. When I logged the values into my console, they were correctly named and assigned. For reference, here is where my request is being sent to:
exports.create = (req,res) =>
{
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req,(err,fields,files)=>{
if(err)
{
return res.status(400).json({
error: 'Trade-in car couldnt be uploaded'
})
}
// check for all the required fiels of vehilce and send error msg
const{make,model,year,mileage,bodytype,askingprice} = fields
if(!make || !model|| !mileage|| !year|| !askingprice|| !bodytype)
{
return res.status(400).json({
error: 'all required attributes for tradein-vehicle are needed'
})
}
// get the data from the client or apia
let tradein = new TradeIn(fields)
// load the image
if(files.image){
// verify if image is too large
if(files.image.size > 1000000)
{
return res.status(400).json({
error: 'file size is too large,has to be less than 1mb'
})
}
tradein.image.data = fs.readFileSync(files.image.path)
tradein.image.contentType = files.image.type
}
tradein.save((err,result) =>{
if(err){
return res.status(400).json({
error: err
})
}
//send the form data back to db
res.json(result);
})
})
}
Upvotes: 0
Views: 261
Reputation: 517
It seems like you are posting an empty FormData object here :
axios.post('http://localhost:8000/api/tradein/create/5e838c95f2064847a843a114', data, headers)
I think you want to post the formdata
instance instead of data
–
Upvotes: 2