【发布时间】:2015-01-30 16:32:41
【问题描述】:
我正在尝试使用 Dart 在服务器端收听PUT 请求,我选择了Start framework,现在我有点坚持。
假设我在服务器上有这段代码:
class Games {
Future<Server> startGamesServer() {
List<Game> games = [];
return start(port: 3010).then((Server app) {
print("Starting http server");
app.put('/games').listen((Request request) {
request.payload().then((value) => print("hello")); <-- HERE
});
}
}
我正在向 Postman 提出以下请求:
目标网址:localhost:3010/games
请求方法:PUT
JSON 类型的正文:{"hello":"world"}
我尝试使用框架提供的Request 对象,但它不适用于payload() 函数中的一些RangeError 异常:
Unhandled exception:
Uncaught Error: RangeError: index (1) must be in the range [0..1)
Future<Map> payload({ Encoding enc: UTF8 }) {
var completer = new Completer();
_request.transform(const AsciiDecoder()).listen((content) {
final params = new Map.fromIterable(
content.split('&').map((kvs) => kvs.split('=')),
key: (kv) => Uri.decodeQueryComponent(kv[0], encoding: enc),
value: (kv) => Uri.decodeQueryComponent(kv[1], encoding: enc) <-- Fails here
);
completer.complete(params);
});
return completer.future;
}
它甚至不打印“你好”...我觉得我没有正确使用 Request 对象,根据文档:
put // adds a handler, returns a Stream<Request>
请求
header(String name) // get header
accepts(String type) // check accept header
input // raw HttpRequest stream
path // requested URI path
uri // requested URI
cookies // provided cookies
param(String name) // get query param by name
payload(Encoding enc) // get a promise with a Map of request body params
回应
header(String name, [value]) // get or set header
get(String name) // get header
set(String name) // set header
type(contentType) // set Content-Type
cache(String cacheType) // set Cache-Control
status(code) // sets response status code
cookie(name, val) // sets cookie
add(string) // add a string to response
close() // closes response
send(string) // sends string and closes response
json(Map data) // stringifies map and sends it
jsonp(String name, Map data) // stringifies map and sends it in callback as `name(data)`
render(viewName, [Map params]) // renders server view
有没有办法从查询中获取实际的 json 映射?我想要一个包含以下内容的飞镖地图:
{ "hello" : "world" }
编辑:我通过这样做打印了“{hello: world}”:
app.put(GAMES).listen((Request request) {
print("put");
request.input.listen((data) {
print(JSON.decode(new String.fromCharCodes(data)));
});
});
我不知道这是否是最好的方法。
【问题讨论】:
-
你在
final params之前尝试过print(content);吗? -
我不知道该怎么做,因为
payload()方法不是我的(它是开始的)...当我尝试编辑文件时,它不会让我(来自 IntelliJ) -
@GünterZöchbauer 查看我的编辑
-
我明白了。我想我现在明白你的问题,但不知道什么可以解决这个问题。通过在 GitHub 存储库中创建问题,您可能更有机会获得回复。
-
是的,也许。我有你好世界的东西,但我认为这有点乏味,不是吗?我来自 Java 世界,一切都自动转换为对象,现在我必须解码字符串字符哈哈!