【问题标题】:react js fetch api using file upload not being sent to body使用未发送到正文的文件上传来反应js fetch api
【发布时间】:2021-03-03 09:39:19
【问题描述】:

这是我的代码

   let formData = new FormData(); 
     
      // Update the formData object 
      formData.append( 
        "myFile", 
        this.state.product_picture, 
        this.state.product_picture.name 
      ); 
      var options = { content: formData };
        const token =  JSON.parse(localStorage.getItem('token'));
        const requestOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                product_name:this.state.product_name,
                product_description:this.state.product_description,
                product_picture:formData,
                category_name:this.state.category_choosen,
              })
        };
        fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
            .then(response => response.json())
            .then(data => {
                this.setState({ product: data.product})
            })
            .catch(error =>{
                console.log("Product creation error", error);
            });

我有这个 fetch api,它总是给出 422 响应 这里的身体是问题 state 里面有一些字符串,但是 this.state.product_picture 里面有一个文件

希望有人可以提供帮助!谢谢!

解决方案:使用 axios 调用 api 解决了我的问题

【问题讨论】:

    标签: javascript reactjs api fetch fetch-api


    【解决方案1】:

    您不能在请求中发送 JSON 对象中的文件(至少不能在没有 Base64 编码的情况下)。通过以下方式更改您的代码以发送包含您的表单的文件。

        let formData = new FormData(); 
     
       // Update the formData object 
       formData.append( 
        "myFile", 
        this.state.product_picture, 
        this.state.product_picture.name 
        ); 
    
       formData.append("product_name",this.state.product_name);
       formData.append("product_description",this.state.product_description);
       formData.append("category_name",this.state.category_choosen);
    
       var options = { content: formData };
        const token =  JSON.parse(localStorage.getItem('token'));
        const requestOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
              },
              body: formData
        };
        fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
            .then(response => response.json())
            .then(data => {
                this.setState({ product: data.product})
            })
            .catch(error =>{
                console.log("Product creation error", error);
            });
    

    【讨论】:

    • 数据仍然没有被解析它说所有数据都是无效的
    • 乐于助人!!
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 2021-07-02
    • 2021-02-11
    • 2019-03-26
    • 1970-01-01
    相关资源
    最近更新 更多