How to create/add middleware that adds default headers to each request


How can I add middleware to the shelf pipeline that adds default HTTP headers to each request?



There is now a pub package to simplify adding CORS headers


See also!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()

See also

Answered By – Günter Zöchbauer

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *