使用 Axios 发布数据

posting data with Axios

我需要使用这样的代码:

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

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

所以,这将与执行相同:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

这可以使用 Java 脚本 6 吗?

您可以创建自己的对象并将其传递给您的数据请求,如下所示:

var obj = {
  [myKey]: value,
}

or 

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

Creating object with dynamic keys

Dynamically Add Variable Name Value Pairs to JSON Object

已编辑:如何post请求

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

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

也试试这个,用你自己的主机名替换

baseURL
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)
})

试试这个对我有用

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

要使键动态化,请将它们括在方括号中 []

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

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