标签: interceptor

React Hooks:使用 axios 拦截器显示全局微调器?

我想添加一个 Loader 组件,以便在React 中进行 API 调用时呈现。我想使用react context + hooks 而不是 redux

正如反应钩子的规则所说,我们不应该在反应组件之外使用反应钩子。但是我需要在Axios拦截器内部分派SHOW_LOADER和,如下所示。HIDE_LOADER

有没有办法实现这一目标?

import axios from "axios";
axios.interceptors.request.use(
  config => {
    dispatch({
    type: "SHOW_LOADER"
})
    return config;
  },
  error => {
     dispatch({
    type: "HIDE_LOADER"
})
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    dispatch({
    type: "HIDE_LOADER"
})
    return response;
  },
  error => {
    dispatch({
    type: "HIDE_LOADER"
})
    return Promise.reject(error);
  }
);
function GlobalLoader(){
    const [state,dispatch] = useContext(LoaderContext);
    return(
        <div>
            {
                state.loadStatus …
Run Code Online (Sandbox Code Playgroud)

interceptor reactjs axios react-context react-hooks

9
推荐指数
1
解决办法
8609
查看次数

如何在EJB拦截器的生命周期事件方法中获取调用者名称

我使用Java EE 5.我为所有EJB编写了一个拦截器,它有三种记录方法:

public class DefaultInterceptor {
    public static final String PREFIX = "!!!!!!!!!Interceptor:";

    @PostConstruct
    public void postConstruct(InvocationContext ctx) {
        try {
            System.out.println(PREFIX + " postConstruct");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @PreDestroy
    public void preDestroy(InvocationContext ctx) {
        try {
            System.out.println(PREFIX + " predestroy");
            System.out.println(PREFIX + "ctx.preceed=" + ctx.proceed());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @AroundInvoke
    public Object intercept(InvocationContext ctx) throws Exception {
        System.out.println(PREFIX + "method invocation '" + ctx.getMethod().getName() + "'"); …
Run Code Online (Sandbox Code Playgroud)

java interceptor ejb-3.0

8
推荐指数
1
解决办法
3108
查看次数

阅读Android Spring Interceptor中的响应主体

我正在使用一个简单的Spring Interceptor类来记录我的Android应用程序中RestTemplate对象的所有REST请求/响应.到目前为止一切正常.

public class LoggerInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
  ClientHttpRequestExecution execution) throws IOException {

Log.d(TAG, "Request body: " + new String(body));
// ...more log statements...

ClientHttpResponse response = execution.execute(request, body);

Log.d(TAG, "Response Headers: " + response.getHeaders());

return response;
}
Run Code Online (Sandbox Code Playgroud)

在初始化时我打电话:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
LoggerInterceptor loggerInterceptor = new LoggerInterceptor();
interceptors.add(loggerInterceptor);
restTemplate.setInterceptors(interceptors);
Run Code Online (Sandbox Code Playgroud)

但是我无法登录response.getBody()上面的方法,因为InputStream被消耗一次并在以后再次使用时抛出IllegalStateException.有没有解决方法,以便我也可以记录响应正文?

java spring android inputstream interceptor

8
推荐指数
2
解决办法
4399
查看次数

无法更改HTTP接受标头 - 使用不同的区域设置解析策略

我在Pluralsight上关注Spring mvc课程,在运行我的应用程序时,我有"无法更改HTTP接受标头 - 使用不同的区域设置解析策略"这个错误.在此之前,我将theese beans添加到servlet-config.xml

<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="language" />
</mvc:interceptors>         

<bean id="localResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" p:defaultLocale="en" />
Run Code Online (Sandbox Code Playgroud)

在资源文件夹中我有两个文件.messages_es.properties和messages.properties.一个goal.text=Minutos Ejercicio para el día de hoy:人和另一个人goal.text=Minutes Exercise For The Day Today: 所以目标是选择语言.

在jsp文件中我有关于它的这一行

Language : <a href="?language=en">English</a> | <a href="?language=es">Spanish </a>

那么我怎样才能使它正常工作?

java spring jsp interceptor web

8
推荐指数
2
解决办法
5704
查看次数

仅将IDbInterceptor挂接到EntityFramework DbContext一次

IDbCommandInterceptor接口是不是非常有据可查.我只发现了一些稀缺的教程:

还有一些问题:


这些是关于挂钩的建议我发现:

1 - 静态DbInterception类:

DbInterception.Add(new MyCommandInterceptor());
Run Code Online (Sandbox Code Playgroud)

2 - 在DbConfiguration课堂上做上述建议

public class MyDBConfiguration : DbConfiguration {
    public MyDBConfiguration() {
        DbInterception.Add(new MyCommandInterceptor());
    }
}
Run Code Online (Sandbox Code Playgroud)

3 - 使用配置文件:

<entityFramework>
  <interceptors>
    <interceptor type="EFInterceptDemo.MyCommandInterceptor, EFInterceptDemo"/>
  </interceptors>
</entityFramework>
Run Code Online (Sandbox Code Playgroud)

虽然我无法弄清楚如何将DbConfiguration类挂钩到DbContext,并且既没有放入typeconfig方法的部分.我发现的另一个例子似乎建议您编写记录器的命名空间:

type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"
Run Code Online (Sandbox Code Playgroud)

我注意到了DataBaseLogger工具IDisposable,IDbConfigurationInterceptor
IDbInterceptor.IDbCommandInterceptor也实现了IDbInterceptor,所以我尝试(没有成功)格式化它像这样:

type="DataLayer.Logging.MyCommandInterceptor, DataLayer"
Run Code Online (Sandbox Code Playgroud)

当我DbInterception直接调用静态类时,它每次调用都会添加另一个拦截器.所以我的快速而肮脏的解决方案是利用静态构造函数:

//This partial class is …
Run Code Online (Sandbox Code Playgroud)

c# logging entity-framework interceptor entity-framework-6

8
推荐指数
2
解决办法
4446
查看次数

如何将异步服务用于角度httpClient拦截器

使用Angular 4.3.1和HttpClient,我需要通过异步服务将请求和响应修改为httpClient的HttpInterceptor,

修改请求的示例:

export class UseAsyncServiceInterceptor implements HttpInterceptor {

  constructor( private asyncService: AsyncService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // input request of applyLogic, output is async elaboration on request
    this.asyncService.applyLogic(req).subscribe((modifiedReq) => {
        const newReq = req.clone(modifiedReq);
        return next.handle(newReq);
    });
    /* HERE, I have to return the Observable with next.handle but obviously 
    ** I have a problem because I have to return 
    ** newReq and here is not available. */
  }
}
Run Code Online (Sandbox Code Playgroud)

响应的问题不同,但我需要再次使用apply来更新响应.在这种情况下,角度指南建议如下:

return next.handle(req).do(event => {
    if …
Run Code Online (Sandbox Code Playgroud)

interceptor rxjs typescript angular2-observables angular

8
推荐指数
4
解决办法
5315
查看次数

模块级的角度HTTP拦截器

我刚刚将我的Angular v4.2.5应用升级为Angular v4.3.6主要使用Interceptors.这是一个非常棒的功能,并提供了一种拦截HTTP调用的简洁方法.

但是,我似乎无法在模块级别范围内设置拦截器.例如,我有一个AppModule,还有两个模块AModuleBModule.双方AModuleBModule越来越列入AppModule.

现在,在Angular 4中是否有一种方法,我可以在模块级别范围拦截器,这样我用于HTTP请求的拦截器AModule就不应该与HTTP请求一起使用BModule.目前,拦截器正在所有HTTP调用中共享,这不是我预期的.我知道providers所有模块都会合并到父模块中,但是有什么方法可以限制这样的事情吗?

任何帮助都非常感谢.

javascript module http interceptor angular

8
推荐指数
1
解决办法
3050
查看次数

如何使用 Angular 5 识别来自 HTTP 拦截器的特定请求?

我在 Angular 5 中使用 HTTPInterceptor 功能。它在克隆 http 请求并发送到服务器(后端服务器)时按预期工作。我只从 HTTPInterceptor 显示和隐藏应用程序加载器,这也工作正常,但我对一个 GET 请求使用了轮询,该请求每 5 秒从后端服务器获取数据,这让用户感到恼火。那么,有没有办法检查 HTTPInterceptor 中的特定请求?并且也不允许根据该请求显示/隐藏加载程序。

以下是拦截函数的当前代码片段:

  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.loadingIndicatorService.showLoader();
    this.customAuthorizationHeader();
    const apiRequest = req.clone({headers:this.headers});
    return next.handle(apiRequest).do
    ((response) => {
        if (response instanceof HttpResponse) {
          this.loadingIndicatorService.hideLoader();
        }
      },
      (error) => {
        this.loadingIndicatorService.hideLoader();
      });
  };
Run Code Online (Sandbox Code Playgroud)

提前致谢。

interceptor observable angular

8
推荐指数
1
解决办法
8213
查看次数

如何使用 okhttp 将 Api_KEY 添加到拦截器中

我有这个服务,我想将令牌作为 okhttp 中的拦截而不是作为参数传递给 @Header("MY_API_KEY")

这是我关于服务的代码

/**
     * Provides the [PHService]
     */
    fun provideService(): PHService {

        val logger = HttpLoggingInterceptor()
        logger.level = HttpLoggingInterceptor.Level.BASIC



        val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()

        return Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(PHService::class.java)
    }
Run Code Online (Sandbox Code Playgroud)

如何在此处添加用于标题授权的拦截器?

interceptor kotlin okhttp retrofit2 okhttp3

8
推荐指数
2
解决办法
6805
查看次数

如何在 gRPC python 中定义全局错误处理程序

我试图捕获在任何服务程序中引发的任何异常,以便我可以确保我只传播已知的异常而不是像 ValueError、TypeError 等意外的异常。

我希望能够捕获任何引发的错误,并对它们进行格式化或将它们转换为其他错误,以更好地控制公开的信息。

我不想用 try/except 包含每个服务程序方法。

我试过使用拦截器,但我无法捕捉到那里的错误。

有没有办法为 grpc 服务器指定错误处理程序?就像你对 Flask 或任何其他 http 服务器所做的一样?

python error-handling interceptor grpc-python

8
推荐指数
1
解决办法
1778
查看次数