我使用 axios.create() 传递一个 baseURL 和一些像这样的默认查询参数

axios.create({ 
    baseURL: 'http://somebigurlhere', 
    params: { 
        part: 'part', 
        maxResults: 5, 
        key: 'key' 
   } 
}); 

当我使用时

axios.get('/search', { 
    params: { 
        q: 'word' 
    } 
}); 

默认参数不会合并到 GET 调用中。

我得到的是 http://somebigurlhere/search?q=word

而不是 http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

我尝试了许多其他方式进行配置,但仍然不起作用。 我在这里做错了什么吗?

我在其他项目中尝试过同样的方法,并且它在那里工作。刚刚使用 create-react-app 创建了一个新的 React 应用程序,但这似乎不再起作用了。

请您参考如下方法:

我用两种方法解决了这个问题:

  1. 使用默认参数并在使用请求时传播它们

    export const API_DEFAULT_PARAMS = { 
      part: 'part', 
      maxResults: 5, 
      key: 'key' 
    } 
     
    export default axios.create({ 
      baseURL: 'http://somebigurlhere', 
    }); 
    

    然后使用它:

    import api, { API_DEFAULT_PARAMS } from './place/where/previous/file/is'; 
        .... 
    api.get('/search', { 
       params: { 
        // spread the default params 
         ...API_DEFAULT_PARAMS, 
        // add your own parameters here 
         q: 'word', 
       } 
    }); 
    
  2. 按照用户建议使用拦截器

    const instance = axios.create({ 
      baseURL: 'http://somebigurlhere', 
    });  
     
    instance.interceptors.request.use(config => { 
      config.params = { 
       // add your default ones 
       part: 'part', 
       maxResults: 5, 
       key: 'key', 
       // spread the request's params 
        ...config.params, 
      }; 
      return config; 
    }); 
     
    export default instance;  
    

    然后使用它

    import api from './place/where/previous/file/is'; 
    ... 
    api.get('/search', { 
     params: { 
       q: 'word', 
     } 
    }); 
    

我更喜欢拦截器方法,因为它将默认参数抽象到实例文件本身,并且您不必每次使用实例时都导入和传播对象。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!