Send “raw” payload to Axios

前端 未结 2 1584
你的背包
你的背包 2021-02-14 15:13

How can I send a raw payload/request body to Axios?

The endpoint I\'m trying to call expects the request body to just be a string which it\'ll scoop up and use.

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 15:53

    As I dropped here having a similar problem, I'd like to supply an additional answer. I am loading an image file (from a element) and sending it to the server using axios - but as raw body as opposed to wrapping it in a multipart/form-data request.

    It seems that in the case of raw data, axios works best if the data is supplied in an ArrayBuffer. This can be achieved e.g. using the following code fragment (ES6):

      const myFile = getMyFileFromSomewhere()
      const reader = new FileReader()
      reader.onload = () => {
        const result = reader.result
        const headers = {
          'Content-Type': file.type,
          'Content-Disposition': 'attachment; filename="' + file.name + '"'
        }
        axios.post('/upload', result, { headers: headers })
      }
      reader.readAsArrayBuffer(myFile)
    

    (using the Content-Type header in this way is slightly non-standard but in my case only used as means of transporting the original file name)

    See:

    https://github.com/axios/axios#request-config - description of data https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer

提交回复
热议问题