处理HTTP重定向状态代码

问题描述 投票:1回答:1

我正在尝试处理HTTP重定向状态代码(例如,当会话超时时302重定向)并且我不知道是否存在使用redux-observable处理特定响应代码的通用方法?我现在遇到的问题是浏览器遵循302响应中指定的位置,我只能点击登录页面的后续200响应。我现在有点破解,我在响应URL中检测到“login”这个词,并使用window.location对象重定向到登录页面。我必须在每一部史诗中都这样做。

这是我得到的:

    export const getData = (action$) => {
    return action$.pipe(
        ofType(GET_DATA_REQUEST),
        mergeMap(action => {
            return ajax(options).pipe(
                map((response) => response.originalEvent.currentTarget.responseURL.endsWith('login') ? window.location.href = 'login' : getDataSuccess(response.response)),
                catchError(error => of(getDataFailure(error)))
            );
        }),
        catchError(error => of(getDataFailure(error)))
    );
};

有谁知道处理这个问题的任何更好的方法,我不必为所有新的史诗重复它?

reactjs react-redux redux-observable
1个回答
1
投票

ajax操作包装XMLHttpRequestXMLHttpRequest自动跟随重定向。虽然无法阻止重定向,但可以检测到重定向。以下是检测重定向的另一个示例:

export const getData = action$ =>
  action$.pipe(
    ofType(GET_DATA_REQUEST),
    mergeMap(action =>
      ajax(options).pipe(
        mergeMap(response => {
          // Navigate to login if the request was successful but redirected
          if (response.status >= 200 && response.status < 300 && response.responseURL !== options.url) {
            window.location.href = 'login'
            return empty()
          }

          return of(getDataSuccess(response.response))
        })
      )
    )
  )

如果要在多个史诗中重用此逻辑,只需将其导出为可重用的函数:

export const ajaxWithLoginRedirect = options =>
  ajax(options).pipe(
    mergeMap(response => {
      // Navigate to login if the request was successful but redirected
      if (response.status >= 200 && response.status < 300 && response.responseURL !== options.url) {
        window.location.href = 'login'
        return empty()
      }

      // Return the raw response
      return of(response)
    })
  )

export const getData = action$ =>
  action$.pipe(
    ofType(GET_DATA_REQUEST),
    mergeMap(action =>
      ajaxWithLoginRedirect(options).pipe(
        // This is only called if we did not redirect
        map(response => getDataSuccess(response.response))
      )
    )
  )

请注意,fetch API确实支持手动处理重定向(您获得的响应对象将具有3xx状态代码)。在XMLHttpRequestfetch之间存在一些权衡,所以我会研究如果不是自动跟随重定向在您的应用程序中更可取。

© www.soinside.com 2019 - 2024. All rights reserved.