2

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;
    };
  };
}

1 Answers1

0

try this code to add content-type or other headers to all of your responses. As the document of 'change' explains, it creates new response by copying all of existing data and adding new data to it. you can change headers, context and body.

Middleware addGeneralHeaders(){
  return createMiddleware(
    responseHandler: (response){
      return response.change(headers: {'Content-Type': 'Application/Json'});
    }
  );
}

use uppercase for begining of the header words as the code is e.g. (Content/Type/Application/Json)

Soli
  • 89
  • 5