处理 HTTP 重定向状态代码

Handling HTTP redirection status codes

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

这是我得到的:

    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)))
    );
};

有谁知道处理这个问题的更好方法,这样我就不必为所有新问题重复 epics?

ajax 操作换行 XMLHttpRequest,并且 XMLHttpRequest 自动跟随重定向。虽然无法阻止重定向,但可以检测到它。这是检测重定向的另一个示例:

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))
        })
      )
    )
  )

如果您想在多个 epics 中重用此逻辑,只需将其导出为可重用函数即可:

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 确实 支持手动处理重定向(您返回的响应 object 将具有 3xx 状态代码)。在 XMLHttpRequestfetch 之间有许多 trade-offs,所以我会研究如果 不是 自动跟随重定向在你的应用程序中更可取。