英文:
sending response to postman from dart aqueduct backend
问题
我已创建一个REST POST端点,在此端点中,我正在进行第三方API调用,并将从第三方API获得的响应作为REST端点的响应发送。
以下是代码部分,你提到的问题发生在return Response.ok(contents.toString())
这一行,出现了JSON转换异常。
异常信息如下:
[SEVERE] aqueduct: POST /uploadurl 1047ms 500 {user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\nconnection : keep-alive\
ncache-control : no-cache\npostman-token : 8ba3e1e9-38c7-37ac-da97-5bb3de983622\naccept-encoding : gzip, deflate, br\ncontent-type : application/json\nsec-fetch-site : cross-site\naccept : */*\nsec-fe
tch-mode : cors\naccept-language : en-US,en;q=0.9\norigin : chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop\ncontent-length : 103\nhost : localhost:8888\n} Converting object to an encodable objec
t failed: Instance of 'StringBuffer' ...
以下是你想要发送作为响应的来自第三方API的数据:
{"objectUrls":[{"signedUrl":"https://example.com","path":"folder3/sub1/mysensordata.log"}]}
请注意,异常信息中的"
是HTML实体编码,实际上应该是双引号"
。你需要在发送响应之前将HTML实体编码解码为JSON字符串。
如果你需要更多的帮助来解决这个问题,请提供更多关于代码中的JSON编码和发送响应的详细信息。
英文:
I have created a rest post endpoint, wherein I am making third party API call and the response that I am getting from third party API is being sent as a response from the rest endpoint
here is the code:
@override
Controller get entryPoint {
String dataRecieved;
var completer = new Completer();
var contents = new StringBuffer();
final router = Router();
// Prefer to use `link` instead of `linkFunction`.
// See: https://aqueduct.io/docs/http/request_controller/
router.route("/uploadurl").linkFunction((request) async {
final req = await request.body.decode();
var envalue = json.encode(req);
print(envalue);
// print( await request.body.decode());
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
var auth = 'Bearer ' +
'eyJ...';
await client
.postUrl(Uri.parse(
'https://<removed>/api/datalake/v3/generateDownloadObjectUrls'))
.then((HttpClientRequest requestSend) {
requestSend.headers
.add("Content-Type", "application/json; charset=UTF-8");
requestSend.headers.add("Authorization", auth);
print(req);
requestSend.write(envalue);
return requestSend.close();
}).then((HttpClientResponse response) async {
print(await response.contentLength);
var resStream = response.transform(Utf8Decoder());
await for (var data in resStream) {
print('Received data: $data');
contents.write(data);
}
print(await response.statusCode);
}).catchError((e) {
print("Request error: $e"); // The only case
});
print(contents);
// var filValue = contents.toString();
return Response.ok(contents);
});
at this line return Response.ok(contents.toString()) I am getting json cast exception
here is the exception that I am getting, inserted of getting this exception it should send JSON back to calling postman:
[SEVERE] aqueduct: POST /uploadurl 1047ms 500 {user-agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\nconnection : keep-alive\
ncache-control : no-cache\npostman-token : 8ba3e1e9-38c7-37ac-da97-5bb3de983622\naccept-encoding : gzip, deflate, br\ncontent-type : application/json\nsec-fetch-site : cross-site\naccept : */*\nsec-fe
tch-mode : cors\naccept-language : en-US,en;q=0.9\norigin : chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop\ncontent-length : 103\nhost : localhost:8888\n} Converting object to an encodable objec
t failed: Instance of 'StringBuffer' #0 _JsonStringifier.writeObject (dart:convert/json.dart:649:7)
#1 _JsonUtf8Stringifier.stringify (dart:convert/json.dart:902:17)
#2 JsonUtf8Encoder.convert (dart:convert/json.dart:371:26)
#3 _FusedConverter.convert (dart:convert/converter.dart:69:48)
#4 Codec.encode (dart:convert/codec.dart:23:32)
#5 Request._responseBodyBytes (package:aqueduct/src/http/request.dart:340:18)
#6 Request.respond (package:aqueduct/src/http/request.dart:251:14)
#7 Controller._sendResponse (package:aqueduct/src/http/controller.dart:339:20)
#8 Controller.receive (package:aqueduct/src/http/controller.dart:176:17)
<asynchronous suspension>
#9 Controller.receive (package:aqueduct/src/http/controller.dart:206:28)
<asynchronous suspension>
#10 Router.receive (package:aqueduct/src/http/router.dart:139:18)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#14 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:134:11)
#15 _MapStream._handleData (dart:async/stream_pipe.dart:234:10)
#16 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:166:13)
#17 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#18 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#19 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#20 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
#21 _StreamController._add (dart:async/stream_controller.dart:642:7)
#22 _StreamController.add (dart:async/stream_controller.dart:588:5)
#23 _HttpServer._handleRequest (dart:_http/http_impl.dart:2828:19)
#24 new _HttpConnection.<anonymous closure> (dart:_http/http_impl.dart:2586:19)
#25 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#26 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#27 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#28 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
#29 _StreamController._add (dart:async/stream_controller.dart:642:7)
#30 _StreamController.add (dart:async/stream_controller.dart:588:5)
#31 _HttpParser._headersEnd (dart:_http/http_parser.dart:388:17)
#32 _HttpParser._doParse (dart:_http/http_parser.dart:703:15)
#33 _HttpParser._parse (dart:_http/http_parser.dart:320:7)
#34 _HttpParser._onData (dart:_http/http_parser.dart:812:5)
#35 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#36 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#37 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#38 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
#39 _StreamController._add (dart:async/stream_controller.dart:642:7)
#40 _StreamController.add (dart:async/stream_controller.dart:588:5)
#41 _Socket._onData (dart:io-patch/socket_patch.dart:1831:41)
#42 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#43 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#44 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#45 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
#46 _StreamController._add (dart:async/stream_controller.dart:642:7)
#47 _StreamController.add (dart:async/stream_controller.dart:588:5)
#48 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1379:33)
#49 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:899:14)
#50 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#51 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
#52 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:118:13)
#53 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:175:5)
and this is the data that I got from the third-party API that I am trying to send from my rest API as a response:
{"objectUrls":[{"signedUrl":"https://example.com","path":"folder3/sub1/mysensordata.log"}]}
答案1
得分: 0
以下是您提供的代码的翻译:
在阅读了一些互联网上的博客之后,我找到了一种方法:
@override
Controller get entryPoint {
final router = Router();
HttpClientResponse responseTemp;
// 建议使用`link`而不是`linkFunction`。
// 参见:https://aqueduct.io/docs/http/request_controller/
router.route("/uploadurl").linkFunction((request) async {
final req = await request.body.decode();
final envalue = json.encode(req);
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
var auth = 'Bearer ' +
'eyJ...';
await client
.postUrl(Uri.parse('http://example.com/v2/5e104a9235000079001e68e7'))
.then((HttpClientRequest requestSend) {
requestSend.headers
.add("Content-Type", "application/json; charset=UTF-8");
requestSend.write(envalue);
return requestSend.close();
}).then((HttpClientResponse response) async {
responseTemp = response;
}).catchError((e) {
print("Request error: $e"); // 唯一的情况
});
await for (var contents in responseTemp.transform(Utf8Decoder())) {
print(contents);
return Response.ok(json.decode(contents.toString()));
}
return Response.noContent();
});
router.route("/secondurl").linkFunction((request) async {
return Response.ok({"key": "adf"});
});
return router;
}
这对我有用。
英文:
After reading some blogs on the internet I found a way :
@override
Controller get entryPoint {
final router = Router();
HttpClientResponse responseTemp;
// Prefer to use `link` instead of `linkFunction`.
// See: https://aqueduct.io/docs/http/request_controller/
router.route("/uploadurl").linkFunction((request) async {
final req = await request.body.decode();
final envalue = json.encode(req);
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
var auth = 'Bearer ' +
'eyJ...';
await client
.postUrl(Uri.parse('http://example.com/v2/5e104a9235000079001e68e7'))
.then((HttpClientRequest requestSend) {
requestSend.headers
.add("Content-Type", "application/json; charset=UTF-8");
requestSend.write(envalue);
return requestSend.close();
}).then((HttpClientResponse response) async {
responseTemp = response;
}).catchError((e) {
print("Request error: $e"); // The only case
});
await for (var contents in responseTemp.transform(Utf8Decoder())) {
print(contents);
return Response.ok(json.decode(contents.toString()));
}
return Response.noContent();
});
router.route("/secondurl").linkFunction((request) async {
return Response.ok({"key": "adf"});
});
return router;
}
This is working for me.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论