【问题标题】:How to use axios.request(config) in Vue.js如何在 Vue.js 中使用 axios.request(config)
【发布时间】:2019-10-18 22:22:32
【问题描述】:

我正在尝试在我的 vue.js 项目中使用 Axios,并且我想发送 HTTP 请求。 我在 github 上阅读了Axios socumentation 并在网上检查了很多样本​​,但我找不到我的答案。 我想定义一个配置文件并从中读取请求路径并使用 Axios 调用它。我需要调用很多 API,并且更喜欢将其保存在单独的文件中。我不想使用axios.getaxios.post 而不是更喜欢使用这种风格:

// in my APIs file 
export default {
  GetAll: {
    method: 'get',
    url: '/Book/GetAll'
  },
  GetById: {
    method: 'GET',
    url: 'Book/GetById/{id}'
  },
  Add: {
    method: 'POST',
    url: 'Book/Add'
  }
}
// Axios instantiation 
import Axios from 'axios'

Vue.use({
  Axios
})

const Server = Axios.create({
  baseURL: myUrl
})

export default Server

// in my component

import Server from './server'
import Api from './api'

export default {
  async mounted() {
    var list = (await Server.request(Api.GetAll)).data

    var book = (await Server.request(Api.GetById)).data
  }
}

在组件中我可以获得列表,但我不知道如何调用GetById API。

【问题讨论】:

  • 我假设您要问的是如何在'Book/GetById/{id}' 中实现相关替换?暂时忽略实现细节,您希望来自组件的调用看起来如何?您希望其他事情如何工作,例如与请求一起传递参数或正文数据?感觉就像您在考虑需求之前选择了架构。如果您可以针对所有这些相关考虑勾勒出调用应该是什么样子,那么也许有人可以提出一种实现方法。
  • @skirtle,感谢您的评论。我以前使用vue resource,发送请求要容易得多,但现在vue resource 似乎已退休。我希望发送带有参数id 的get 请求,例如Book/GetById/1,或者对于发布请求,将其放在请求正文中。我希望这会有所帮助。
  • 我认为这并不能真正回答我的问题。我想知道您希望组件中的代码是什么样子。您已经做出了一些设计决策,但您在设计中留下了重大空白。在目前的形式中,您的问题过于宽泛,无法提供答案。
  • @skirtle 我想像 await Server.request(Api.GetAll)await Server.request(Api.GetById, 2) 或类似的东西使用它。

标签: javascript vue.js vuejs2 axios


【解决方案1】:

我建议像这样包装所有其余的 api 调用:

class RestApi {
    constructor() {
        this.client = axios.create({
            baseURL: 'base-url-here'
        });
    }

    async get(url, params = {}) {
        return this.client.request({
            type: 'get',
            url: url,
            params: params
        })
    }

    async post(url, data = {}) {
        return this.client.request({
            type: 'post',
            url: url,
            data: data
        })
    }

    async getById(id) {
        return this.get(`Book/GetById/${id}`)
    }
}

const api = new RestApi();
const response = await api.getById(1);

【讨论】:

  • 谢谢,但在这种情况下,get 请求将变为myUrl/GetById?id=1 而不是myUrl/GetById/1
  • 每个方法都可以控制如何格式化url,以及如何传递其余的参数,所以在getById的情况下,url应该是/Book/GetById/1,不带任何查询参数。
猜你喜欢
  • 2017-05-16
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2019-03-28
  • 2018-11-15
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多