arash karimadini
arash karimadini

Reputation: 23

uploading file in postman works but in axios it throws 500 error

Guys my backend is working and i can send image file with form-data in post man but in my client side with axios i give a header of multipart/form-data and it throws {"statusCode":500,"message":"Internal server error"} in postman the content-type is:

content-type: multipart/form-data; boundary=<calculated when request is sent>

my axios code:

  PostNormalProductsFromServer(context,{formData,tokenSend}) {
const config = {
  headers: { 
            'Authorization': `${tokenSend}`,
            'Content-Type': 'multipart/form-data'
 }
 }
 axios.post('/api/product',addEnamel,config).then(response=>{
   if (response.status == 201) {
     alert(response.status)
     console.log(response.data)
     console.log(addEnamel.file)
   }
 }).catch(error => {
   if (error.response && error.response.status === 400) {
       alert("error.response")
   }
   else if(error.response && error.response.status === 401){
     console.log(tokenSend)
   }
 }) },

The data im sending to formData from component:

var formData = new FormData();
formData.append("name", this.productname);
        formData.append("price", parseInt(this.price));
        formData.append("discount", parseInt(this.discount));
        formData.append("average_rating", this.way);
        formData.append("average_rating", 4);
        formData.append("texture", this.texture);
        formData.append("name_of_artist", this.artist);
        formData.append("time_for_artist_to_finish", parseInt(this.duration));
        formData.append("weight", parseInt(this.weight));
        formData.append("height", parseInt(this.height));
        formData.append("width", parseInt(this.width));
        formData.append("length", parseInt(this.length));
        formData.append("usage_of_product", this.usages.join());
        formData.append("type_of_colors_used", this.color);
        formData.append("washable", Boolean(this.wash));
        formData.append("can_be_heated", this.categoryCode);
        formData.append("description", this.extra);
        formData.append("category", Boolean(this.heat));
        formData.append("file", this.pictures[0]);
 this.$store.dispatch("PostNormalProductsFromServer", {formData,tokenSend});

guys I'm sending easily with postman where the body is in form-data. What is the problem with my axios code?

Upvotes: 1

Views: 2047

Answers (2)

Amin Lak
Amin Lak

Reputation: 11

You probably have a 'CORS' error

Add this code to your backend source (Top of the routes):

const cors = require('cors');
app.use(cors());

then run this in terminal:

npm i cors

Upvotes: 1

Peyman Abbasi
Peyman Abbasi

Reputation: 1

This snippet code works for me

var form = new FormData();
var file = document.querySelector('#file');
form.append("image", file.files[0]);
axios.post('upload_file', form, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Upvotes: 0

Related Questions