gpt4 book ai didi

javascript - React Native Http 拦截器

转载 作者:IT王子 更新时间:2023-10-29 05:34:48 27 4
gpt4 key购买 nike

像大多数应用程序一样,我正在编写一个应用程序,它需要在 http 响应/请求处理程序中使用很多类似的逻辑。例如,我必须始终检查刷新 token 并将它们保存到 AsyncStorage,或者始终将 header 设置为我的 AuthService header ,甚至检查 404 以路由到相同的 404 错误页面。

我非常喜欢 Angular 中的 http 拦截器;您可以在其中定义和注册一个 http 拦截器以(没有更好的术语)拦截所有 http 流量,然后运行组合的通用逻辑。

我有两个主要问题:

  1. 既然在 React Native 中,我们定义了这些独立的组件,我们是否应该首先提取通用的 http 逻辑以保持组件的可重用性?
  2. 如果我们不想重复代码,React Native(第一个)或 Objective-C/Swift(第二个)是否有办法拦截 http 流量并为请求提供处理程序?

最佳答案

如果您只想拦截 xhr,您是否考虑过 axios?我正在使用 axios 拦截器 - https://www.npmjs.com/package/axios到目前为止它似乎有效。

这是示例代码

import axios from 'axios';
import promise from 'promise';

// Add a request interceptor
var axiosInstance = axios.create();

axiosInstance.interceptors.request.use(function (config) {
// Do something before request is sent
//If the header does not contain the token and the url not public, redirect to login
var accessToken = getAccessTokenFromCookies();

//if token is found add it to the header
if (accessToken) {
if (config.method !== 'OPTIONS') {
config.headers.authorization = accessToken;
}
}
return config;
}, function (error) {
// Do something with request error
return promise.reject(error);
});

export default axiosInstance;

然后在任何你想进行 xhr 调用的地方导入这个 axiosInstance

关于javascript - React Native Http 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302689/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com