vania-dart/framework

[Feature Request] - How to customize middleware return?

danieldcastro opened this issue · 3 comments

Based on the documentation, the standard approach seems to be using abort(), but this returns a response with a Content-Type of text/html and a status code of 200. I would like to know if it's possible to customize this response to return JSON and a status code of 400, for example. I tried modifying the response directly in the middleware using req.response.write and req.response.close, but this resulted in a loop that broke the application.

My concern also applies to the AuthenticateMiddleware that extends Authenticate, which has the same issue with the response handling.

For API add Accept header with application/json value will return as JSON

For API add Accept header with application/json value will return as JSON

class Authenticate extends Middleware {
  final String? guard;
  Authenticate({this.guard});

  @mustCallSuper
  @override
  handle(Request req) async {
    String? token = req.header('authorization')?.replaceFirst('Bearer ', '');
    try {
      if (guard == null) {
        await Auth().check(token ?? '');
      } else {
        await Auth().guard(guard!).check(token ?? '');
      }
    } on JWTExpiredException {
      throw Unauthenticated(message: 'Token expired');
    }
  }
}

Using this example, can you teach me please?

You don't need this, Use Authentication middleware

And where you make a request to the API with Dio or HTTP you need to send accept header with application/json

Dio dio = new Dio();
dio.options.headers['content-Type'] = 'application/json';

dio.options.headers['accept'] = 'application/json'; // <= Add This line

dio.options.headers["authorization"] = "token ${token}";
response = await dio.post('Api Address', data: data);