我试图从一个飞镖项目的一些数据发布到另一个并将其存储在MongoDB中帖子列表并使用飞镖
邮编迭代:接收它
import 'dart:io';
void main() {
List example = [
{"source": "today", "target": "tomorrow"},
{"source": "yesterday", "target": "tomorrow"},
{"source": "today", "target": "yesterday"}
];
new HttpClient().post('localhost', 4040, '')
.then((HttpClientRequest request) {
request.headers.contentType = ContentType.JSON;
request.write(example);
return request.close();
});
}
代码,另一个文件中
void start() {
HttpServer.bind(address, port)
.then((HttpServer server) {
// Log in console to show that server is listening
print('Server listening on ${address}:${server.port}');
server.listen((HttpRequest request) {
request.transform(UTF8.decoder).listen(sendToDatastore);
});
});
}
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
dbproxy.write("rawdata", contents);
index++;
// non related to the problem code
}
bool write(collectionName, document)
{
Db connection = connect();
DbCollection collection = connection.collection(collectionName);
connection.open().then((_){
print('writing $document to db');
collection.insert(document);
}).then((_) {
print('closing db');
connection.close();
});
return true;
}
我正在挣扎的是,我使用
request.transform(UTF8.decoder).listen(sendToDatastore);
所以我正在将请求流转换为字符串,因为我找不到将它作为Json发送的方式。
然后在sendToDatastore我无法正确解析它,为了存储它。据我理解,如果我尝试做我需要让每一个JSON对象作为Map来存放它,因为我得到这个错误
Uncaught Error: type 'String' is not a subtype of type 'Map' of 'document'.
感谢,
UPDATE
这样的事情在sendToDatastore
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
var contentToPass = JSON.decode(contents);
contentToPass.forEach((element) => dbproxy.write("rawdata", element));
index++;
// non related to the problem code
}
它提出了这个错误
Uncaught Error: FormatException: Unexpected character (at character 3)
[{source: today, target: tomorrow}, {source: yesterday, target: tomorrow}, ...
^
在使用JSON.decode
UPDATE2
错误的是,我是不是从“邮政编码”发送实际的JSON。我用
// ...
request.write(JSON.encode(example));
// ...
和一切运行良好
感谢
我没有看到你使用'JSON.encode'。另外'rates'在服务器端来自哪里?写入流时,可以使用'JSON.encode(example)'而不是'rates'。 – Robert 2014-09-29 18:50:34
对不起@Robert,费率/例子是一个错误,因为费率对象太大我以相同的方式创建了这个例子,但忘记了在调用中改变它。关于JSON.enconde,它的用法并不在我粘贴的第一个代码中,尽管它是我尝试过的,更新是我尝试使用它的错误。 – mitomed 2014-09-29 18:59:39
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.HttpClientRequest#id_write - 您无法直接将列表传递给写入函数。你必须通过JSON.encode显式地转换它。而在接收端,您应该读取整个内容,将字符串转换为对象并自行调用该函数。 – Robert 2014-09-29 19:06:10