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
posting data with Axios
提问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
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);
});

