首页 > 解决方案 > vue 和 globla axios 请求

问题描述

目前我有以下 axios 发布请求作为示例:

在启动/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" })

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

Edit2: 通过一个简单的循环修复它

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

标签: vue.jsaxios

解决方案


您可以为 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 参数,我如何使用它?

对于仅对 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(() => {...});

推荐阅读