我经常在Dart中收到错误“HTTP标头不可变”。
我想要做的是当用户在“packages”文件夹中询问某些内容时,它会获取它。
我的错误代码是这样的:
if(new RegExp("/packages/(.*)").hasMatch(request.uri.toString())){
new File(request.uri.toString().substring(1)).readAsString().then((String contents){
request.response.headers.contentType = new ContentType("text", "css", charset: "utf-8");
request.response.write(contents);
request.response.close();
});
}
我的整个代码是这样的:
import "dart:io";
void main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000).then((HttpServer server){
print("Listening on localhost on {$server.port}");
server.listen((HttpRequest request){
switch(request.uri.toString()){
case "/":
request.response.headers.contentType = ContentType.HTML;
new File("static/taskbar.html").readAsString().then((String contents){
request.response.write(contents);
request.response.close();
new File("static/index.html").readAsString().then((String contents){
request.response.write(contents);
request.response.close();
});
});
break;
default:
request.response.statusCode = HttpStatus.NOT_FOUND;
request.response.write("404 Not Found.");
request.response.close();
break;
}
if(new RegExp("/packages/(.*)").hasMatch(request.uri.toString())){
new File(request.uri.toString().substring(1)).readAsString().then((String contents){
request.response.headers.contentType = new ContentType("text", "css", charset: "utf-8");
request.response.write(contents);
request.response.close();
});
}
});
});
}
答案 0 :(得分:7)
基本上,当您收到“HTTP标头不可变”错误时,这意味着您在写入响应后尝试修改标头。
在您的代码中,当请求与/packages/(.*)
模式匹配时,它还会执行交换机的default
子句,从而产生404响应。因此,当您尝试再次写入响应时,服务器会抛出异常。
要解决此问题,您可以使用if else
表达式替换开关。例如:
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000).then((HttpServer server){
print("Listening on localhost on {$server.port}");
server.listen((HttpRequest request){
var uri = request.uri.toString();
if (uri == "/") {
request.response.headers.contentType = ContentType.HTML;
new File("static/taskbar.html").readAsString().then((String contents){
request.response.write(contents);
request.response.close();
new File("static/index.html").readAsString().then((String contents){
request.response.write(contents);
request.response.close();
});
});
} else if(new RegExp("/packages/(.*)").hasMatch(uri)){
new File(uri.substring(1)).readAsString().then((String contents){
request.response.headers.contentType = new ContentType("text", "css", charset: "utf-8");
request.response.write(contents);
request.response.close();
});
} else {
request.response.statusCode = HttpStatus.NOT_FOUND;
request.response.write("404 Not Found.");
request.response.close();
}
});
});