user2019608
user2019608

Reputation:

HttpException: HTTP headers are not mutable

I can't figure out why I'm getting this error in Dart:

HttpException: HTTP headers are not mutable

I have an instance of HttpResponse and I try to add some headers to it:

response.outputStream.writeString(responseData);
response.headers.add('Content-Type', 'text/html');
response.outputStream.close();

What am I supposed to do then if not add to the headers?

Upvotes: 3

Views: 2577

Answers (1)

Kai Sellgren
Kai Sellgren

Reputation: 30212

It's simple to solve, just make sure you add headers before outputting anything:

response.headers.add('Content-Type', 'text/html'); // <-- this line first.
response.write(responseData);
response.close();

All I did was change the order of the lines.

The reason is that if you start outputting the body, you can't simply modify the headers anymore (because the headers are already sent down the wire!). This is how HTTP works. First the headers then the body.

More background: Sometimes HTTP libraries (generally in different programming languages) may be buffering the output data and do not flush the content immediately, resulting in a scenario where you can seemingly modify the headers even after outputting something. In your case that's not happening. The output seems to be flushed already.

Upvotes: 8

Related Questions