标签: middleware

在express中有选择地应用中间件

我的路由器中有一个路由/users作为父后缀,所有后续路由将附加父路由,例如。/users/details

在我的 app.js 中

app.use('/api/v1/users', userRoutes);
Run Code Online (Sandbox Code Playgroud)

在我的用户路由中

import express from 'express';
import users from '../controllers/user_controller';

import { authenticateRoute, authenticateSignedRoute, aclAuthenticator } from './../middlewares/AuthenticationMiddleware';

const router = express.Router();


//user routes
router.get('/details', authenticateRoute, aclAuthenticator, users.getDetails);
router.get('/posts', authenticateRoute, aclAuthenticator, users.getPosts);


module.exports = router;
Run Code Online (Sandbox Code Playgroud)

我想做什么

有没有办法让我将authenticateRoute 和aclAuthenticator 中间件添加到父前缀路由中,然后对于一个特定路由有一个例外,即仅应用第三个中间件而不是前两个。

例如 app.use('/api/v1/users',authenticateRoute, aclAuthenticator, userRoutes);

我的新路由器文件

router.get('/details', applyOnlyThisMiddleWare, users.getDetails);
router.get('/posts', No MiddleWareAtAll, users.getPosts);
Run Code Online (Sandbox Code Playgroud)

我基本上试图覆盖最初的中间件,这可能吗?

middleware node.js express

2
推荐指数
1
解决办法
3040
查看次数

有条件地运行中间件 - Laravel

我有一个中间件,用于检查请求中的特定标头参数并基于该参数发回响应。

但是我遇到的问题是我不希望这个中间件总是在我的控制器中的一个函数上运行。如果函数中的条件为真,我希望中间件运行(例如:存储函数)。

我怎样才能做到这一点?

php conditional middleware laravel laravel-5

2
推荐指数
1
解决办法
4766
查看次数

发送变量以在中间件中终止

我正在尝试发送一个变量以从路由终止中间件:

Route::group(['middleware' => 'checkUserLevel'], function () {
    // my routes
});
Run Code Online (Sandbox Code Playgroud)

我可以获取checkUserLevel中间件的句柄,但我也需要在终止方法中访问,我该怎么办?

public function handle($request, Closure $next, $key)
{
     dd($key); // it returns variable
}

public function terminate($request, $response)
{
      //I need that variable here
}
Run Code Online (Sandbox Code Playgroud)

middleware laravel

2
推荐指数
1
解决办法
1009
查看次数

Laravel 组多个中间件

在我的应用程序中,我有三个用户角色:

  1. 用户
  2. 编辑
  3. 行政

当编辑器登录管理部分时,某些部分是隐藏的(用户管理、系统信息等),当然,管理员可以看到所有内容。

因此,为此我创建了两个中间件:Admin 和 Editor。这是代码。

管理中间件。

<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;

use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()) {
          if(Auth::user()->role_id == 3) {
            return $next($request);
          }
        }

        return redirect('/');

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑器中间件:

<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;

use Closure;

class Editor
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request …
Run Code Online (Sandbox Code Playgroud)

middleware routes laravel

2
推荐指数
1
解决办法
4289
查看次数

如何处理 Django 中间件中的异常?

我在正确处理 Django 中间件中的异常时遇到问题。我的例外:

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_403_FORBIDDEN
class MyProfileAuthorizationError(APIException):    
    def __init__(self, msg):
        APIException.__init__(self, msg)
        self.status_code = HTTP_403_FORBIDDEN
        self.message = msg
Run Code Online (Sandbox Code Playgroud)

还有我的中间件:

class PatchRequestUserWithProfile:
def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request, *args, **kwargs):
    patch_request_for_nonanon_user(request)
    if not request.user.profile:
        raise MyProfileAuthorizationError("You are not allowed to use this profile.")

    response = self.get_response(request)
    return response
Run Code Online (Sandbox Code Playgroud)

这个异常抛出 500 而不是 403。我该如何解决?

python django middleware django-rest-framework

2
推荐指数
1
解决办法
1964
查看次数

通过 Axios/Express 返回错误值到 React App

我有一个handleSubmit函数可以从后端获取数据作为更大组件的一部分。当后端出现故障时,我想将错误信息发送到我的 redux 存储和/或本地组件,但我无法这样做。

handleSubmit函数看起来像这样(它使用了正确连接的 React 钩子。如果有用,可以发布完整的组件):

const handleSubmit = async (e, { dataSource, filter, filterTarget }) => {

    e.preventDefault();
    setIsLoading(true);
    setErrorValue(null);
    setError(false);

    const token = localStorage.JWT_TOKEN;
    const link = filterTarget === "Identifier" ? `http://localhost:8081/api/${dataSource}/${filter}`: `http://localhost:8081/api/${dataSource}?filter=${filter}&filterTarget=${filterTarget}`;

    try {
        let data = await axios.get(link, { headers: { authorization: token }});
        props.setData(data);
        setError(false);
        setIsLoading(false);
    } catch (err){           
        setErrorValue(err.message);
        setError(true);
        setIsLoading(false);
    };
};
Run Code Online (Sandbox Code Playgroud)

我故意通过表单提出错误的请求,这将在我的后端触发错误。这些是通过我的自定义 Express 中间件函数处理的,它看起来像这样(一旦我让这个框架工作,我会添加更多):

  handleOtherError: (error, req, res, next) => { // Final custom error handler, with no …
Run Code Online (Sandbox Code Playgroud)

javascript error-handling middleware express reactjs

2
推荐指数
1
解决办法
2122
查看次数

将参数传递给 Echo 路由中间件

如何将参数传递给 Echo 中的中间件?有一个我想要实现的例子。

func (h *handlers) Check(pm string, next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        if pm == "test" {
            return next(c)
        }
        return echo.NewHTTPError(http.StatusUnauthorized, "")
    }
}

Run Code Online (Sandbox Code Playgroud)

我想像这样设置中间件:

route.Use(middleware.Check("test input"))
Run Code Online (Sandbox Code Playgroud)

middleware go go-echo

2
推荐指数
1
解决办法
2778
查看次数

初始化 DefaultHttpContext.Response.Body 到 MemoryStream 抛出 NullReferencePointer

我正在研究全局异常中间件的实现,我想用单元测试来覆盖中间件。下面你看看我走了多远。

这是单元测试的代码。

    [Fact]
    public async Task MethodName_StateUnderTest_ExpectedBehavior()
    {
        //Arrange
        IExceptionHandlerFeature exceptionHandlerFeature = new ExceptionHandlerFeature {Error = new NotFoundException()};

        IFeatureCollection features = new FeatureCollection();
        features.Set(exceptionHandlerFeature);

        var context = new DefaultHttpContext(features);
        context.Response.Body = new MemoryStream();
        //Act
        await ExceptionMiddleware.HandleException(context);

        //Assert
        context.Response.StatusCode.Should().Be((int) HttpStatusCode.NotFound);
    }
Run Code Online (Sandbox Code Playgroud)

这是 ExceptionMiddleware.Handle 方法的代码

public static async Task HandleException(HttpContext context)
{
    var contextFeature = context.Features.Get<IExceptionHandlerFeature>();

    if (contextFeature == null)
    {
        return;
    }

    if (contextFeature.Error is AppValidationException validationException)
    {
        context.Response.StatusCode = (int) HttpStatusCode.BadRequest;

        var failures = JsonConvert.SerializeObject(validationException.Failures);

        await context.Response.WriteAsync(
            new ErrorDetails
            { …
Run Code Online (Sandbox Code Playgroud)

unit-testing middleware httpcontext exceptionhandler .net-core

2
推荐指数
1
解决办法
1700
查看次数

如何在trapi中设置自定义中间件?

我只是想在 Strapi 中设置一个简单的自定义中间件。我已经尝试过他们在文档中编写的内容,但我发现环境文件夹和内部配置已被删除。以下是我目前所写的。

/config/environments/development/middleware.json

{
  "subscribers": {
    "enabled": true
  }
}
Run Code Online (Sandbox Code Playgroud)

/config/middleware.json

{
  "timeout": 100,
  "load": {
    "before": ["responseTime", "logger", "cors", "responses", "gzip"],
    "order": ["parser", "subscribers"],
    "after": ["router"]
  }
}
Run Code Online (Sandbox Code Playgroud)

/中间件/订阅者/index.js

module.exports = (strapi) => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        console.log("I have been called!");
        await next();
      });
    },
  };
};

Run Code Online (Sandbox Code Playgroud)

请帮我在trapi api中实现一个中间件。事先谢谢。

middleware strapi

2
推荐指数
1
解决办法
2743
查看次数

多个中间件(REST + SOAP)

我遵循了本教程:custom-asp-net-core-middleware-example

现在我想添加一个默认的 REST 中间件,它处理所有带有 JSON 内容的请求,但当我不注册自己的中间件时,找不到来自 ASP.NET 的 REST 中间件。

有人能告诉我如何使用多个中间件,其中一个是 SOAP,另一个是 REST 中间件吗?

这是我注册中间件的代码:

public static class SOAPEndpointExtensions
{
    public static IApplicationBuilder UseSOAPEndpoint(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<SOAPEndpointMiddleware>();
    }

    public static IApplicationBuilder UseSOAPEndpoint<T>(this IApplicationBuilder builder, string path, MessageEncoder encoder)
    {
        return builder.UseMiddleware<SOAPEndpointMiddleware>(typeof(T), path, encoder);
    }

    public static IApplicationBuilder UseSOAPEndpoint<T>(this IApplicationBuilder builder, string path, Binding binding)
    {
        var encoder = binding.CreateBindingElements().Find<MessageEncodingBindingElement>()?.CreateMessageEncoderFactory().Encoder;
        return builder.UseMiddleware<SOAPEndpointMiddleware>(typeof(T), path, encoder);
    }
}
Run Code Online (Sandbox Code Playgroud)

SOAPEndpointMiddleware.cs与教程中的大致相同。

c# rest soap middleware asp.net-core

2
推荐指数
1
解决办法
63
查看次数