首页 > 解决方案 > 如何通过反应传递数据,包括邮递员中表单数据类型的文件?

问题描述

首先,我是新手,我需要通过 API 将数据从前端传递到后端。数据是来自 POSTMAN 的表单数据类型。下图显示了 POSTMAN 中的 API 工作

在此处输入图像描述

我在这里使用表单数据作为我的 api 数据。

所以这里的问题。由于这是我第一次处理将文件传递给表单数据的问题。下面的代码是我所做的:

 constructor (props){
        super(props);
        const supplier_id = parseInt(localStorage.getItem('id'));
        this.state ={
            supplier_id: supplier_id,
            item_name:'',
            item_shortDes: '',
            item_longDes: '',
            price: '',
            terms_agreement: '',
            Location: '',
            selectedFile: null,    // The item file which I need to pass to api.
          redirect: false,
        }
        this.onChange = this.onChange.bind(this);
        this.createItem = this.createItem.bind(this);
      }

      createItem(){
        console.log(this.state)
        fetch(`http://localhost:9000/api/item/submit`, {  // callling the API here
            method: 'post',
            body: JSON.stringify(this.state)   
        }).then ((result) => {  
                let responseJSON = result;
                console.log(responseJSON);
                });
      }

我在这里得到错误:

在此处输入图像描述

所以我相信这是因为我没有通过form-data. 我对吗?我将如何处理这个?

标签: reactjsapifetchform-data

解决方案


首先,您需要发送表单数据,您必须像自爆一样调用表单数据类。

formData = new FormData()

然后开始附加您的表单数据

formData.append("keyName",${键名})


推荐阅读