6

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

4

1 回答 1

8

更新

现在有一个 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

于 2014-10-08T09:24:11.180 回答