我使用 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 应用程序,但这似乎不再起作用了。
最佳答案
我用两种方法解决了这个问题:
使用默认参数并在使用请求时传播它们
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', } });
按照用户建议使用拦截器
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', } });
我更喜欢拦截器方法,因为它将默认参数抽象到实例文件本身,并且您不必每次使用实例时都导入和传播对象。
关于javascript - 默认查询参数未在 axios 请求中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56397239/