Javascript 使用 Axios 发布数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43484017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:57:46  来源:igfitidea点击:

posting data with Axios

javascriptpostaxios

提问by Jose Cabrera Zuniga

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,
     vr2: Value2
  }
});

so, it will be the same as executing:

因此,它将与执行相同:

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

Is this possible using Java Script 6?

这可以使用 Java Script 6 吗?

采纳答案by Rafa? Schmidt

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

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

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

将变量名值对动态添加到 JSON 对象

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

回答by Njeru Cyrus

Try this one also and replace

也试试这个并替换

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

回答by wanje

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