How can I add middleware to the shelf pipeline that adds default HTTP headers to each request?
Asked
Active
Viewed 2,297 times
1 Answers
9
Update
There is now a pub package to simplify adding CORS headers
see https://pub.dartlang.org/packages/shelf_cors
Original
See also 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);
See also http://thomaslockerambling.blogspot.co.at/2014/10/shelf-middleware-adding-cors-headers.html

Community
- 1
- 1

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
1Ah. I'm trying to implement simple webserver with shelf. it's a bit challenge :( – Sungguk Lim Feb 10 '15 at 13:29
-
1Yeah, I had lot of troubles too. I got most things I needed working but can't claim to understand why ;-) – Günter Zöchbauer Feb 10 '15 at 13:31
-
1shelf_cors 0.2.1 => Dart 2 Incompatible – onetwo12 Aug 16 '20 at 17:37