Vue axios post request passes FormData type parameter

Reference link:

Axios encountered pitfalls when uploading file files, no multipart boundary was found

Axios encapsulation, intercepting specific requests, and judging whether all requests are loaded

In the front-end request method

      const formData = new FormData()

      formData.append('role', 1)
      formData.append('excelFile', fileObj)

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }

      const { data: res } = await this.$http.post('admin/user/add', formData, config)

It is necessary to set the Content-Type of the request header to multipart/form-data (I have found many articles to solve the problem saying that it does not need to be set. I tried it to no avail. If it is not set, it will automatically add the default type instead of the FormData we want. )

Note: Do not serialize formData , post requests need to be serialized (usually with qs.stringify()), but it is not necessary to pass FormData with post requests

If the formData is serialized, the parameter received by the backend will be null (this problem troubled me for a long time before I found out that it was a serialization problem)

Bonus: Determine whether the axios request data is formData type or ordinary Object

The backend receives parameters

@PostMapping("/admin/user/add")
@ResponseBody
public Map<String, Object> addUserByExcel(@ModelAttribute UserExcelVO userExcelVO) throws Exception {

}

The backend uses java objects to receive parameters

Note: cross domain issues

Guess you like

Origin blog.csdn.net/weixin_41786574/article/details/105015565