目前,我以以下axios发布请求为例:
在boot / axios.js
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs
Vue.prototype.$serverUrl = 'http://localhost:8090/api/';
在我的页面中:
this.$axios.post(this.$serverUrl, null,
{ data: {version: "1", command: "login", email: this.regEmail, password: this.password, API: 2, token: "dummy"},
transformRequest: [(data, headers) => {return this.$qs.stringify(data);}]})
.then((response) => {...})
.catch((err) => {...})
.finally(() => {...})
这可以正常工作,但是我想对其进行全球化,因此基本URL和其他固定参数将已经存在,并且我将仅发送特定呼叫的其他参数:
this.$postCall(call specific params...)
.then((res) => {...})
.catch((err) => {...})
.finally(() => {...})
我知道我应该制作类似的原型
Vue.prototype.$postCall = function(param) {
}
但是我不确定回调应如何返回给调用者...
编辑: 我做了以下事情:
Vue.prototype.$postCall = function (params) {
return this.$axios.post('http://localhost:8090/api', null, { data: { API: 2, version: "1", params}});
}
并命名为:
this.$postCall({ command: "login", email: this.regEmail, password: this.password, token: "dummy" })
在调试中,我看到正确的信息键:params中的值,我希望将其他params添加到固定的param中,但是没有,我丢失了什么?
Edit2: 通过一个简单的循环即可解决
let theData = {
API: 2,
version: "1",
};
for (var k in params) {
theData[k] = params[k];
}
答案 0 :(得分:1)
您可以为axios创建一个自定义实例的其他方法,这样在调用.get()
.post()
等时它将使用默认值。
https://github.com/axios/axios#custom-instance-defaults
例如
import axios from 'axios';
import qs from 'qs';
Vue.prototype.$axios = axios.create({
baseURL: 'http://localhost:8090/api/',
transformRequest: [(data, headers) => qs.stringify(data)],
});
编辑:
仅对URL进行后期调用,您可以通过this.$axios.post('/', /* ... */)
让$postCall
返回axios.post()
承诺
例如
Vue.prototype.$postCall = function (params) {
return this.$axios.post('/', { version: "1", command: params.command /*, other params */ });
}
您可以在页面上使用
this.$postCall({ command: "some commmand" })
.then((response) => {...})
.catch((err) => {...})
.finally(() => {...});