我有以下代码,它基于 Dart 文档中的一个示例,使用了 HTML 维基百科页面中的 HTML 片段。浏览器将其呈现为字符串,如何让浏览器将其呈现为 HTML?我已经浏览了所有 dart 文档和示例,但找不到任何内容,还尝试了不同的内容标题,但没有成功。
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8000);
await for (HttpRequest request in server) {
request.response.write("""<!DOCTYPE html>
<html>
<head>
<title>This is a title</title>
</head>
<body>
<div>
<p>Hello world!</p>
</div>
</body>
</html>""");
await request.response.close();
}
答案 0 :(得分:1)
您需要设置内容类型:
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8000);
await for (HttpRequest request in server) {
request.response.headers.contentType = ContentType.html;
request.response.write("""<!DOCTYPE html>
<html>
<head>
<title>This is a title</title>
</head>
<body>
<div>
<p>Hello world!</p>
</div>
</body>
</html>""");
await request.response.close();
}
}