Vue.js vue和Globala axios请求

Vue.js vue和Globala axios请求,vue.js,axios,Vue.js,Axios,目前,我以以下axios post请求为例: 在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.$s

目前,我以以下axios post请求为例:

在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中看到了正确的info key:value,我希望将附加的参数添加到固定的参数中,但它们不是,我缺少什么

编辑2: 通过一个简单的循环修复了它

let theData = {
    API: 2, 
    version: "1", 
};
for (var k in params) {
    theData[k] = params[k];
}

其他方法可以为axios创建自定义实例,以便在调用.get.post等时使用默认值。

e、 g。

编辑:

如果没有它期望的url参数,我如何使用它? 对于仅对url的post调用,您可以通过以下方式执行此操作。$axios.post'/',/**/

仍然需要像以前一样传递数据参数。我想知道是否有一种方法可以使post请求函数全球化。 让$postCall返回axios.post承诺 e、 g

你可以在页面上使用

this.$postCall({ command: "some commmand" })
  .then((response) => {...})
  .catch((err) => {...})
  .finally(() => {...});

好把戏,但是:1。如果没有它期望的url参数,我如何使用它?这个.$axios.postrl?..,2。仍然需要像以前一样传递数据参数。我想知道是否有一种方法可以创建一个全球化的post请求函数。看起来我就快到了,你能在编辑部分后看到我的原始帖子吗?@Amos如果你能使用ES5或最新语法,尝试使用更简单的扩展语法来合并对象,例如,{data:{API:2,version:1,…params}
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(() => {...});