Send “raw” payload to Axios

久未见 提交于 2019-12-05 21:24:12

问题


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.

If I try to just pass a string to axios.post() for the requestBody, it'll convert it to an object with no value ({ "this+is+my+message": "" }) and ends up getting parsed like this "this+is+my+message=".

I checked the documentation, but couldn't find any option that seemed to work. transformRequest seemed to be the most obvious, but it sent in the string and I sent out the string (literally d => d), but it still seemed to convert it to a valueless JSON object.


回答1:


It turns out, if I set the Content-Type header to text/plain, it won't convert it to JSON or form data and will send it as I want.

axios.post('/my-url', 'my message text', {
  headers: { 'Content-Type': 'text/plain' }
});



回答2:


As I dropped here having a similar problem, I'd like to supply an additional answer. I am loading an image file (from a <input type="file> 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 = getMyFileFrom Somewhere()
  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 })
  }

(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



来源:https://stackoverflow.com/questions/45066928/send-raw-payload-to-axios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!