簡體   English   中英

在 postman 中上傳文件有效,但在 axios 中會引發 500 錯誤

[英]uploading file in postman works but in axios it throws 500 error

伙計們,我的后端正在工作,我可以在郵遞員中發送帶有表單數據的圖像文件,但在我的客戶端使用 axios 我給了一個 header 的 multipart/form-data 並且它拋出{"statusCode":500,"message":"Internal server error"} postman 中的{"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});

伙計們,我很容易用 postman 發送身體在表單數據中。 我的 axios 代碼有什么問題?

您可能遇到“CORS”錯誤

將此代碼添加到您的后端源(路線頂部):

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

然后在終端中運行它:

npm i cors

這個片段代碼對我有用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM