axios post request to send form data

后端 未结 9 2407
走了就别回头了
走了就别回头了 2020-11-22 03:40

axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload conta

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:58

    The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT

    packageData: (data) => {
      const form = new FormData()
      for ( const key in data ) {
        form.append(key, data[key]);
      }
      return form
    }
    

    Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following

    packageData: (obj, form, namespace) => {
      for(const property in obj) {
        // if form is passed in through recursion assign otherwise create new
        const formData = form || new FormData()
        let formKey
    
        if(obj.hasOwnProperty(property)) {
          if(namespace) {
            formKey = namespace + '[' + property + ']';
          } else {
            formKey = property;
          }
    
          // if the property is an object, but not a File, use recursion.
          if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
            packageData(obj[property], formData, property);
          } else {
            // if it's a string or a File
          formData.append(formKey, obj[property]);
          }
        }
      }
      return formData;
    }
    

提交回复
热议问题