提问者:小点点

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


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


共1个答案

匿名用户

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

另见https://groups.google.com/a/dartlang.org/forum/#!主题/云/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