Adding cookies with Dart server?

Issue

So I have a simple HttpServer like this:

import 'dart:io';
main() {
    HttpServer
        .bind("127.0.0.1", 80)
        .then((server) {
            server.listen((request) {             
                // Add cookie here how?                
                request.response.write("Howdy Darty cowboy!");
                request.response.close();
            });
        });    
}

Is there a way to add cookies to the HttpResponse in Dart?
I can see both HttpResponse and HttpRequest classes have cookies properties and I can access them, but I can’t seem to figure out how to add a cookie.

Tried this:

request.response.cookies = ["name", "value"];

But got this error:

Error: The setter 'cookies' isn't defined for the class 'HttpResponse'. 

So there are no predefined methods to work with cookies?
Do I have to add my own HTTP Headers to add cookies?
Again, I can see headers properties in both classes, but no setters or getters!

Just started playing around with Dart.

Note: Please don’t link me external packages, I would like to do it with Dart’s core libraries. Don’t want to get into another npm hell! Moved away from Node.js cause of npm, but looks like pub is identical, just uses yaml.

Solution

request.response.cookies is a List<Cookie>, so you’ll want to add to it (rather than assign it with equals).

Try:

request.response.cookies.add(Cookie('name', 'value'));

Answered By – Richard Heap

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

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