每次发送 http 请求时,我想将身份验证令牌添加到 http 请求标头,如果授权失败,我想将用户重定向到登录。我应该装饰 Http Driver 还是有更好的方法呢?
我提供了一个装饰 http 驱动程序的解决方案。但我不确定这是正确的做法。这是到目前为止我写的代码:
import Rx from 'rx';
import {makeHTTPDriver} from '@cycle/http';
function makeSecureHTTPDriver({eager = false} = {eager: false}) {
return function secureHTTPDriver(request$) {
const httpDriver = makeHTTPDriver(eager);
const securedRequest$ = request$
.map(request => {
const token = localStorage.getItem('token');
if (token) {
request.headers = request.headers || {};
request.headers['X-AUTH-TOKEN'] = token;
}
return request;
});
const response$ = httpDriver(securedRequest$);
//todo: check response and if it fails, redirect to the login page
return response$;
}
}
export default makeSecureHTTPDriver;
这是我如何使用 makeSecureHttpDriver 的代码
const drivers = {
DOM: makeDOMDriver('#app'),
HTTP: makeSecureHttpDriver()
};