【问题标题】:FormData sends empty data using axiosFormData 使用 axios 发送空数据
【发布时间】:2020-03-26 03:46:52
【问题描述】:

我想将我的数据从 vue 发送到 api。我不知道为什么我的 formData 是空的。您可以看到附加的快照。我已经尝试了几个小时使用 stackoverflow this link 和 this link 上的几个链接。

我的确认方法:

async confirm () {
      let formData = new FormData()
      let params = {
        name: this.product.name,
        department_id: this.departmentId,
        category_id: this.categoryId,
        sub_category_id: this.subCategoryId,
        brand_id: this.brandId,
        weight: parseInt(this.product.weight),
        unit_weight: this.product.unitWeight === 'gram' ? 'g' : 'ml',
        volume: {
          length: parseInt(this.product.volume.length),
          width: parseInt(this.product.volume.width),
          height: parseInt(this.product.volume.height)
        }
      }
      formData.append('file', this.imageFile)
      formData.append('data', JSON.stringify(params))
      console.log(formData.getAll('data'))
      console.log(formData.getAll('file'))
      console.log('this.imagefile', this.imageFile)
      console.log('this.params', params)
      console.log('formData', formData)
      this.fullscreenLoading = true
      await this.klikdailyAPI().post('products', formData).then(result => {
        let message = this.product.name + ' succesfully created'
        this.$store.commit('products/setMessage', message)
        this.$router.push('/products')
        this.fullscreenLoading = false
      }).catch(err => {
        this.snackbar = true
        this.snackbarObject = {
          color: 'error',
          text: 'ERROR! ' + err.response.data.message
        }
      })
    }

我的api方法:

klikdailyAPI () {
      return axios.create({
        baseURL: `${url}/api/v1/`,
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('tokenApi')}`,
          'Content-Type': 'multipart/form-data'
        }
      })
    }

我的代码有什么问题?

【问题讨论】:

  • Formdata 它没有显示在控制台中,它转换为二进制文件。当您发布您的 API call.form 数据中显示的数据时,
  • 好的,那么如何使用axios将数据从vue发送到api呢?我用这个例子stackoverflow.com/questions/49587831/…
  • axios.post('/api', data, header).then( response => { console.log(response); } ) 试试这个方法。我希望它有效。
  • 错误未定义,因为表单数据仍然为空

标签: javascript vue.js multipartform-data form-data


【解决方案1】:
data = {'file': this.imagefile , 'data': params}

axios.post('/api', data, header).then( response => { console.log(response); } )

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多