我有一个用节点编写的用户注册 API,但该 API 给了我三种类型的响应
{
"message": "success",
"ccontent": {
"_id": "5ef7c4c414529241205fb590",
"email": "[email protected]",
"password": "$2b$05$4TFPKJ83O7jSPhjtIIDj1ud5pjhS9GY.I0C.IFlBDyUFsd6i4E3Ci",
"__v": 0
}
}
如果用户已经存在,它只会给我一个字符串响应
已经存在
如果发生错误
发生错误
我有一个 future 函数可以从 API 获取响应
class RegistrationService {
String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
Future userRegistration(email, password) async {
Response response = await post(registrationUrl,
body: {"email": email, "password": password});
var result = jsonDecode(response.body);
return RegistrationResponse.fromJson(result);
}
}
仅当用户注册成功时才有效,但当失败时会发生错误,告知未处理的异常“已存在”或“错误发生”
如何在未来的函数中从 API 获取所有类型的响应?
提前致谢。
如果响应为
already-exists
或 error-occurred
,您可以抛出异常
class RegistrationService {
String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
Future<Map<String, dynamic> userRegistration(email, password) async {
Response response = await post(registrationUrl,
body: {"email": email, "password": password});
if (userAlreadyExist(response.body)) {
// already-exists response
throws UserAlreadyExistException();
}
else if (errorOccurred(response.body)) {
// error occurred response
throws SomeOtherException();
}
var result = jsonDecode(response.body);
return RegistrationResponse.fromJson(result);
}
}
您需要实现方法
userAlreadyExist
和 errorOccurred
来检测这种情况并确定每种情况的最佳异常类型。当您调用 userRegistration
时,您还需要捕获异常,以便您可以做出正确反应。
试试这个方法: 例如,在 laravel 控制器 api 中,来自数据库的响应数据:
$data=array(
'a'=>1,
'b'=>2,
'c'=>3
);
$message=true; // for Message
$token='65718766gjasgffjaskahg blablala'; // for token
return response()->json(['data'=>$data,'message'=>$message,'token'=>$token],200);
要从 Api 获取 dart flutter 的响应,请使用以下代码:
try{
final response = await http.post(Uri.parse(ApiConnect.getkhsmhs), body: { ...bla bla bla }
if (response.statusCode == 200) {
var dataResp=json.decode(response.body);
setState(() {
var DataList=dataResp['data'];
});
}else{
print('Data not found!);
}
}catch (e) {
print('Error: $e');
}