上传文件在postman工程,但在axios它抛出500错误

v09wglhw  于 2022-11-29  发布在  iOS
关注(0)|答案(2)|浏览(171)

伙计们,我的后端是工作,我可以发送图像文件与表单数据在后的人,但在我的客户端与axios我给了一个多部分/表单数据的头,它抛出{"statusCode":500,"message":"Internal server error"}在postman的内容类型是:

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

我的axios代码:

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)
   }
 }) },

正在从组件发送到formData的数据:

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});

我用 Postman 很容易地发送的家伙,其中的身体是在形式数据。我的axios代码有什么问题?

1tu0hz3e

1tu0hz3e1#

您可能有一个'CORS'错误
将此代码添加到后端源代码(路径顶部):

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

然后在终端中运行以下命令:
npm i校正

41zrol4v

41zrol4v2#

这段代码很适合我

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'
    }
})

相关问题