1

伙计们,我的后端正在工作,我可以在邮递员中发送带有表单数据的图像文件,但是在我的客户端使用 axios 我给出了一个多部分/表单数据的标题,它{"statusCode":500,"message":"Internal server error"}在邮递员中抛出内容类型是:

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

伙计们,我很容易用邮递员发送身体在表单数据中的地方。我的 axios 代码有什么问题?

4

2 回答 2

1

您可能遇到“CORS”错误

将此代码添加到您的后端源(路线顶部):

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

然后在终端中运行它:

npm i cors

于 2021-02-18T15:39:10.630 回答
0

这个片段代码对我有用

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'
    }
})
于 2021-02-14T16:37:34.013 回答