Skip to content Skip to sidebar Skip to footer

Posting Data With Axios

I need to use a code like this: vr1 = 'firstName' value1 = 'Fred' vr2 = 'lastName' value2 = 'Flinstone' axios({ method: 'post', url: '/user/12345', data: { vr1: Value1,

Solution 1:

Try this one also and replace

baseURL
with your own hostname url
import axios from'axios'let var1 = 'firstName'let value1 = 'Fred'let var2 = 'lastName'let value2 = 'Flinstone'const api = axios.create({baseURL: 'http://example.com'})
api.post('/user/12345', {
    var1: value1,
    var2: value2
})
.then(res => {
     console.log(res)
})
.catch(error => {
     console.log(error)
})

Solution 2:

You can create your own object and pass it to your data request like this:

var obj = {
  [myKey]: value,
}

orvar obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;

Creating object with dynamic keys

Dynamically Add Variable Name Value Pairs to JSON Object

edited: how to post request

const profile = {};
//...fill your object like this for example
profile[key] = value;

axios.post('profile/student', profile)
  .then(res => {
    return res;
  });

Solution 3:

Try this it works for me

const obj = {
  firstName: Fred,
  lastName: Flinstone
}
axios
  .post(
    "url",
    this.obj,
  )
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error);
  });

Solution 4:

To make the keys dynamic, surround them in brackets []

vr1 = 'firstName'
value1 = 'Fred'
vr2 = 'lastName'
value2 = 'Flinstone'

axios({
  method: 'post',
  url: '/user/12345',
  data: {
     [vr1]: Value1,
     [vr2]: Value2
  }
});

Post a Comment for "Posting Data With Axios"