如何创建/添加为每个请求添加默认标头的中间件

时间:2014-10-08 09:22:22

标签: dart cors dart-io dart-shelf

如何将中间件添加到架构管道中,为每个请求添加默认HTTP头?

1 个答案:

答案 0 :(得分:6)

更新

现在有一个pub软件包可以简化添加CORS头文件 见https://pub.dartlang.org/packages/shelf_cors

原始

另见https://groups.google.com/a/dartlang.org/forum/#!topic/cloud/2Vn_IqzGtTc

final Map<String, String> _headers = {'Access-Control-Allow-Origin': '*',
                                      'Content-Type': 'text/html'};

// for OPTIONS (preflight) requests just add headers and an empty response
shelf.Response _options(shelf.Request request) => (request.method == 'OPTIONS') ?
    new shelf.Response.ok(null, headers: _headers) : null;

shelf.Response _cors(shelf.Response response) => response.change(headers: _headers);

shelf.Middleware _fixCORS = shelf.createMiddleware(
    requestHandler: _options, responseHandler: _cors);

final shelf.Handler handler = const shelf.Pipeline()
  .addMiddleware(_fixCORS)
  .addMiddleware(shelf.logRequests())
  .addMiddleware(exceptionResponse())
  .addHandler(routes.handler);

另见http://thomaslockerambling.blogspot.co.at/2014/10/shelf-middleware-adding-cors-headers.html