【问题标题】:vue and globla axios requestvue 和全局 axios 请求
【发布时间】:2020-06-13 11:30:47
【问题描述】:

目前我以 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" })

在调试中,我看到了正确的信息键:参数中的值,我希望将附加参数添加到固定参数中,但它们没有,我错过了什么?

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

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

【问题讨论】:

    标签: vue.js axios


    【解决方案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)],
    });
    

    编辑:

    1. 如果没有预期的 url 参数,我该如何使用它?

    对于网址的后调用,您可以通过this.$axios.post('/', /* ... */) 执行此操作

    1. 数据参数仍然需要像以前一样传递。我想知道是否有办法使发布请求功能全球化。

    使$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(() => {...});
    

    【讨论】:

    • 不错的技巧,但是: 1. 如果没有它期望的 url 参数,我如何使用它? this.$axios.post(URL?...), 2. 数据参数仍然需要像以前一样传递。我想知道是否有办法使全球化发布请求功能。
    • 看来我快到了,你能在编辑部分后看看我的原帖吗?
    • @Amos 如果您可以使用 ES5 或最新语法,请尝试使用“扩展语法”来合并更简单的对象,例如 { data: { API: 2, version: "1", ...params } }developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2020-02-14
    • 2020-12-28
    • 2017-10-02
    • 2020-07-16
    • 2021-04-28
    • 2020-04-03
    • 2018-06-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多