【问题标题】:RxJs How to set default request headers?RxJs 如何设置默认请求头?
【发布时间】:2018-01-28 11:01:17
【问题描述】:

不确定是否有任何方法可以像我们使用 axios js as- 那样在 rxjs 中设置默认请求标头 -

axios.defaults.headers.common['Authorization'] = 'c7b9392955ce63b38cf0901b7e523efbf7613001526117c79376122b7be2a9519d49c5ff5de1e217db93beae2f2033e9';

这是我要设置请求标头的史诗代码 -

export default function epicFetchProducts(action$, store) {
    return action$.ofType(FETCH_PRODUCTS_REQUEST)
    .mergeMap(action =>
        ajax.get(`http://localhost/products?${action.q}`)
      .map(response => doFetchProductsFulfilled(response))
    );
}

请帮忙。

【问题讨论】:

    标签: rxjs redux-observable rxjs-dom


    【解决方案1】:

    我正在使用 redux-observable 但这适用于 rxjs;也许下一个答案设计得太过分了,但是我需要根据某些因素来动态获取标题,而不影响单元测试(也与我的史诗解耦),并且不改变 ajax.get/ajax.post 等,这是我发现的:

    ES6有proxies support,在阅读this并改进解决方案here后,我使用高阶函数在原始rxjs/ajax对象中创建一个Proxy,并返回代理对象;以下是我的代码:

    注意:我使用的是 typescript,但你可以将它移植到纯 ES6。

    AjaxUtils.ts

    export interface AjaxGetHeadersFn {
        (): Object;
    }
    
    // the function names we will proxy
    const getHeadersPos = (ajaxMethod: string): number => {
        switch (ajaxMethod) {
            case 'get':
            case 'getJSON':
            case 'delete':
                return 1;
            case 'patch':
            case 'post':
            case 'put':
                return 2;
            default:
                return -1;
        }
    };
    
    export const ajaxProxy = (getHeadersFn: AjaxGetHeadersFn) =>
        <TObject extends object>(obj: TObject): TObject => {
            return new Proxy(obj, {
                get(target: TObject, propKey: PropertyKey) {
                    const origProp = target[propKey];
                    const headersPos = getHeadersPos(propKey as string);
    
                    if (headersPos === -1 || typeof origProp !== 'function') {
                        return origProp;
                    }
    
                    return function (...args: Array<object>) {
                        args[headersPos] = { ...args[headersPos], ...getHeadersFn() };
                        // @ts-ignore
                        return origProp.apply(this, args);
                    };
                }
            });
        };
    

    你这样使用它:

    ConfigureAjax.ts

    import { ajax as Ajax } from 'rxjs/ajax'; // you rename it
    
    // this is the function to get the headers dynamically
    // anything, a function, a service etc.
    const getHeadersFn: AjaxGetHeadersFn = () => ({ 'Bearer': 'BLABLABLA' });
    
    const ajax = ajaxProxy(getHeadersFn)(Ajax); // proxified object
    export default ajax;
    

    在您的应用程序中,您可以从 ConfigureAjax.ts 导入 ajax 并正常使用它。

    如果你使用 redux-observable,你可以这样配置史诗(将 ajax 对象作为依赖注入更多信息 here):

    ConfigureStore.ts

    import ajax from './ConfigureAjax.ts'
    
    const rootEpic = combineEpics(
        fetchUserEpic
    )({ ajax });
    

    UserEpics.ts

    // the same sintax ajax.getJSON, decoupled and
    // under the covers with dynamically injected headers
    const fetchUserEpic = (action$, state$, { ajax }) => action$.pipe(
      ofType('FETCH_USER'),
      mergeMap(({ payload }) => ajax.getJSON(`/api/users/${payload}`).pipe(
        map(response => ({
          type: 'FETCH_USER_FULFILLED',
          payload: response
        }))
      )
    );
    

    希望它可以帮助寻找相同的人:D

    【讨论】:

      【解决方案2】:

      无法使用 RxJS 的 ajax 实用程序为所有 ajax 请求设置默认标头。

      但是,您可以在每个调用中提供标头,或创建自己的简单包装器,默认提供它们。

      utils/ajax.js

      const defaultHeaders = {
        Authorization: 'c7b9392955ce63b38cf090...etc'
      };
      
      export const get = (url, headers) =>
        ajax.get(url, Object.assign({}, defaultHeaders, headers));
      

      my-example.js

      import * as ajax from './utils/ajax';
      
      // Usage is the same, but now with defaults
      ajax.get(`http://localhost/products?${action.q}`;)
      

      【讨论】:

      • 还有@jayphelps 我怎样才能设置 ROOT_URL 像 axios.defaults.baseURL = 'localhost/api' ?
      • 无法设置任何类型的默认值,但您可以将其添加到 auth 标头之类的抽象中。
      猜你喜欢
      • 2021-02-05
      • 2017-12-02
      • 2022-08-12
      • 2018-12-03
      • 2012-04-11
      • 1970-01-01
      • 2017-01-16
      • 2016-06-20
      • 2017-12-28
      相关资源
      最近更新 更多