简体   繁体   English

如何在 axios 中制作动态 baseURL

[英]How to make a dynamic baseURL in axios

Let's say that i have baseURL defined inside a given service as follows:假设我在给定服务中定义了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');

  }
....
 

}

In this example ?order=desc&sort=name is repeated for each request how can add it to baseURL and make it dynamic like:在此示例中?order=desc&sort=name为每个请求重复,如何将其添加到 baseURL 并使其成为动态的,如:

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

where %s could be replaced by '/users/'+id or '/users/' , it's possible like this or there's any other way to parse the URL to make it dynamic?其中%s可以替换为'/users/'+id'/users/' ,可能是这样,或者还有其他方法可以解析 URL 以使其动态化?

You should be able to use params field, ie:您应该能够使用 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'
  }
})

Fiddle: https://jsfiddle.net/kquvw0jy/ (check console network tab to see request)小提琴: https://jsfiddle.net/kquvw0jy/ (检查控制台网络选项卡以查看请求)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM