首页 > 解决方案 > 无法识别的令牌'object':在 [Source: (String)"[object Object]" 处期待 ('true', 'false' 或 'null')↵;行:1,列:8]

问题描述

我想通过 API 将值从前端传递到后端。格式是表单数据(在 POSTMAN 中)但是,我使用的方式是给出标题中提到的错误。

这是邮递员的图片:

在此处输入图像描述

这是我从 react.js 调用 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, 
        }
        this.onChange = this.onChange.bind(this);
        this.createItem = this.createItem.bind(this);
      }
      createItem(){
        const itemData = this.state
        console.log(itemData)

        const formData = new FormData();    
        formData.append('json', itemData)

        fetch(`http://localhost:9000/api/item/submit`, 
        {
            method: 'post',
            body: formData
        }).then ((result) => {  
                let responseJSON = result;
                console.log(responseJSON);
                });
      }

我不知道我应该怎么解决这个问题。任何人都可以为我提供有关此错误的提示吗?我需要做JSON.stringify吗?我

标签: jsonreactjsfetchmultipartform-data

解决方案


我认为因为在你的邮递员中你用两个键发送jsonitemFile然后你不能发送里面的所有数据json

尝试这个:

createItem(){
    // destructuring your data here, seperate json and file
    const {selectedFile, ...rest} = this.state

    const formData = new FormData();    
    formData.append('json', rest)
    formData.append('itemFile', selectedFile) // append the selected file as well

    fetch(`http://localhost:9000/api/item/submit`, 
    {
        method: 'post',
        body: formData
    }).then ((result) => {  
            let responseJSON = result;
            console.log(responseJSON);
            });
  }

我希望它的工作


推荐阅读