如何在axios中创建动态baseURL

时间:2020-06-27 18:26:30

标签: javascript vue.js axios nuxtjs

假设我在给定服务中定义了baseURL,如下所示:

import axios from 'axios'

const myAPI = axios.create({
  baseURL: 'https://api.domaine.com/',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

export default {

  getUsers(){
     MyAPI.get('/users?order=desc&sort=name');
   },

  getUser(id){
      MyAPI.get('/users/'+id+'?order=desc&sort=name');

  }
....
 

}

在此示例中,对每个请求都重复?order=desc&sort=name,如何将其添加到baseURL并使其动态化,如:

 baseURL: 'https://api.domaine.com/%s?order=desc&sort=name',

%s可以用'/users/'+id'/users/'代替,这可能是这样,还是有其他解析URL使其动态化的方法?

1 个答案:

答案 0 :(得分:2)

您应该可以使用params字段,即:

const myAPI = axios.create({
  baseURL: 'https://api.domaine.com/',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  params: {
    order: 'desc',
    sort: 'name'
  }
})

提琴:https://jsfiddle.net/kquvw0jy/(检查控制台网络标签以查看请求)