Middleware to change content-type in response header

Viewed 15

I am new to server side programming with dart. I made a simple API server with a number routes. I'm using Shelf and ShelfModular packages.

I'm trying to use one Middleware to set the content-type of the response.

When running, the Middleware runs, but even though running, the value of 'content-type' still unchanged.

Thanks.

import 'package:shelf/shelf.dart';
import 'package:shelf_modular/shelf_modular.dart';

import 'src/app_module.dart';

Future<Handler> startShelfModular() async {
  final handler = Modular(module: AppModule(), middlewares: [
    logRequests(),
    jsonResponse(),
  ]);
  return handler;
}

Middleware jsonResponse() {
  return (handler) {
    return (request) async {
      var response = await handler(request);

      response = response.change(headers: {
        'content-type': 'application/json',
        ...response.headers,
      });

      return response;
    };
  };
}
0 Answers
Related