score:580

Accepted answer

you can post axios data by using formdata() like:

var bodyformdata = new formdata();

and then add the fields to the form you want to send:

bodyformdata.append('username', 'fred');

if you are uploading images, you may want to use .append

bodyformdata.append('image', imagefile); 

and then you can use axios post method (you can amend it accordingly)

axios({
  method: "post",
  url: "myurl",
  data: bodyformdata,
  headers: { "content-type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

related github issue:

can't get a .post with 'content-type': 'multipart/form-data' to work @ axios/axios

score:0

https://www.npmjs.com/package/axios

its working

// "content-type": "application/x-www-form-urlencoded", // commit this

import axios from 'axios';

let requestdata = {
      username : "abc@gmail.cm",
      password: "123456"
    };
   
    const url = "your url paste here";

    let options = {
      method: "post",
      headers: { 
        'content-type': 'application/json; charset=utf-8',

        authorization: 'bearer ' + "your token paste here",
      },
      data: json.stringify(requestdata),
      url
    };
    axios(options)
      .then(response => {
        console.log("k_____ res :- ", response);
        console.log("k_____ res status:- ", response.status);
      })
      .catch(error => {
        console.log("k_____ error :- ", error);
      });

fetch request

fetch(url, {
    method: 'post',
    body: json.stringify(requestpayload),           
    headers: {
        'content-type': 'application/json; charset=utf-8',
        authorization: 'bearer ' + token,
    },
})
    // .then((response) => response.json()) .  // commit out this part if response body is empty
    .then((json) => {
        console.log("response :- ", json);
    }).catch((error)=>{
        console.log("api call error ", error.message);
        alert(error.message);
});

score:0

 transformrequest: [
  function(data, headers) {
    headers["content-type"] = "application/json";
    return json.stringify(data);
  }
]

try this, it works

score:0

for me it worked using axios, typescript and form-data(v4.0.0):

import formdata from "form-data";
import axios from "axios";

async function login() {
  var data = new formdata();
  data.append("user", "asdf");
  const return = await axios.post(
    "https://ptsv2.com/t/1q9gx-1652805776/post", data,
    { headers: data.getheaders() }
  );
  console.log(return);
}

score:0

in nodejs you can use urlsearchparams instead.

like this:

  const formdata = new urlsearchparams({
     param1: 'this',
     param2: 'is',
     param3: 'neat',
}); 

score:0

a boundary (which is used, by the server, to parse the payload) is set when the request is sent. you can't obtain the boundary before making the request. so, a better way to get this is using getboundary() from your formdata.

var formdata = new formdata();
formdata.append('username', 'fred');
formdata.append('file0', filezero);
formdata.append('file1', fileone);

axios({
  method: "post",
  url: "myurl",
  data: formdata,
  headers: {
      'content-type':  `multipart/form-data; ${formdata.getboundary()}`,
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

score:1

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;
}

score:1

in my case, the problem was that the format of the formdata append operation needed the additional "options" parameter filling in to define the filename thus:

var formdata = new formdata();
formdata.append(fieldname, filebuffer, {filename: originalname});

i'm seeing a lot of complaints that axios is broken, but in fact the root cause is not using form-data properly. my versions are:

"axios": "^0.21.1",
"form-data": "^3.0.0",

on the receiving end i am processing this with multer, and the original problem was that the file array was not being filled - i was always getting back a request with no files parsed from the stream.

in addition, it was necessary to pass the form-data header set in the axios request:

        const response = await axios.post(getbackendurl() + '/api/documents/' + userid + '/createdocument', formdata, {
        headers: formdata.getheaders()
    });

my entire function looks like this:

async function uploaddocumenttransaction(userid, filebuffer, fieldname, originalname) {
    var formdata = new formdata();
    formdata.append(fieldname, filebuffer, {filename: originalname});

    try {
        const response = await axios.post(
            getbackendurl() + '/api/documents/' + userid + '/createdocument',
            formdata,
            {
                headers: formdata.getheaders()
            }
        );

        return response;
    } catch (err) {
        // error handling
    }
}

the value of the "fieldname" is not significant, unless you have some receiving end processing that needs it.

score:1

this should work well when needing to post x-www-form-urlencoded data using axios from a nodejs environment. you may need to add an authorization header to the config.headers object if the endpoint requires authentication.

const config = {
  headers: {
    accept: 'application/json',
    'cache-control': 'no-cache',
    'content-type': 'application/x-www-form-urlencoded'
  }

const params = new urlsearchparams({key1: value1, key2: value2});

return axios
  .post(url, params.tostring(), config)
  .then((response) => {
    return response.data;
  })
  .catch((error) => console.error(error));

score:2

i needed to upload many files at once using axios and i struggled for a while because of the formdata api:

// const instance = axios.create(config);

let fd = new formdata();
for (const img of images) { // images is an array of file object
  fd.append('images', img, img.name); // multiple upload
}

const response = await instance({
  method: 'post',
  url: '/upload/',
  data: fd
})

i did not specify the content-type: multipart/form-data header!

score:3

i needed to calculate the content length aswell

const formheaders = form.getheaders();
formheaders["content-length"] = form.getlengthsync()

const config = {headers: formheaders}

return axios.post(url, form, config)
.then(res => {
    console.log(`form uploaded`)
})

score:6

i had the similar issues when using formdata with axios to make calls on https://apps.dev.microsoft.com service and it error-red out with "the request body must contain the following parameter: 'grant_type'"

after reformatting the data from

{
  grant_type: 'client_credentials',
  id: '123',
  secret: '456789'
}

to

"grant_type=client_credentials&id=123&secret=456789"

and the following code worked:

const config: axiosrequestconfig = {
    method: 'post',
    url: https://apps.dev.microsoft.com/auth,
    data: 'grant_type=client_credentials&id=123&secret=456789',
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
    }
};

axios(config)
.then(function (response) {
  console.log(json.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

score:7

even more straightforward:

axios.post('/adduser',{
    username: 'fred',
    useremail: 'flintstone@gmail.com'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

score:7

import axios from "axios";
import qs from "qs";   

const url = "https://yourapplicationbaseurl/api/user/authenticate";
    let data = {
      email: "testuser@gmail.com",
      password: "admin@123"
    };
    let options = {
      method: "post",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      data: qs.stringify(data),
      url
    };
    axios(options)
      .then(res => {
        console.log("yeh we have", res.data);
      })
      .catch(er => {
        console.log("no data sorry ", er);
      });
  };

score:12

using application/x-www-form-urlencoded format in axios

by default, axios serializes javascript objects to json. to send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

browser

in a browser, you can use the urlsearchparams api as follows:

const params = new urlsearchparams();

params.append('param1', 'value1');

params.append('param2', 'value2');

axios.post('/foo', params);

note that urlsearchparams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

alternatively, you can encode data using the qs library:

const qs = require('qs');

axios.post('/foo', qs.stringify({ 'bar': 123 }));

or in another way (es6),

import qs from 'qs';

const data = { 'bar': 123 };

const options = {

  method: 'post',

  headers: { 'content-type': 'application/x-www-form-urlencoded' },

  data: qs.stringify(data),

  url, };

axios(options);

score:17

2020 es6 way of doing

having the form in html i binded in data like so:

data:

form: {
   name: 'joan cap de porc',
   email: 'fake@email.com',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

onsubmit:

async submitform() {
  const formdata = new formdata()
  object.keys(this.form).foreach((key) => {
    formdata.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formdata)
    this.$emit('formsent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

score:33

upload (multiple) binary files

node.js

things become complicated when you want to post files via multipart/form-data, especially multiple binary files. below is a working example:

const formdata = require('form-data')
const fs = require('fs')
const path = require('path')

const formdata = new formdata()
formdata.append('files[]', json.stringify({ to: [{ phonenumber: process.env.ringcentral_receiver }] }), 'test.json')
formdata.append('files[]', fs.createreadstream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formdata, {
  headers: formdata.getheaders()
})
  • instead of headers: {'content-type': 'multipart/form-data' } i prefer headers: formdata.getheaders()
  • i use async and await above, you can change them to plain promise statements if you don't like them
  • in order to add your own headers, you just headers: { ...yourheaders, ...formdata.getheaders() }

newly added content below:

browser

browser's formdata is different from the npm package 'form-data'. the following code works for me in browser:

html:

<input type="file" id="image" accept="image/png"/>

javascript:

const formdata = new formdata()

// add a non-binary file
formdata.append('files[]', new blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getelementbyid('image')
const file = element.files[0]
formdata.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formdata)

score:51

check out querystring.

you can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

score:86

in my case i had to add the boundary to the header like the following:

const form = new formdata();
form.append(item.name, fs.createreadstream(pathtofile));

const response = await axios({
    method: 'post',
    url: 'http://www.yourserver.com/upload',
    data: form,
    headers: {
        'content-type': `multipart/form-data; boundary=${form._boundary}`,
    },
});

this solution is also useful if you're working with react native.


Related Query

More Query from same tag