2

我正在尝试使用 API 与 PHP 后端通信,但我无法访问响应的正文。

我从邮递员那里得到了基本代码。这是身体响应的数据: 在此处输入图像描述

我需要获取消息,并在 UI 中显示错误,问题是response.stream它的类型是 Bytesreem,我无法将其转换为 Map

我的代码:

  Future<void> _authenticateUp(String email, String password,
      String passwordconfirmation, String username, String name,
      {String phonenumber}) async {

    var headers = {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    };

    var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));

    request.fields.addAll({
      'email': email,
      'password': password,
      'password_confirmation': passwordconfirmation,
      'username': username,
      'name': name,
      'phone_number': phonenumber
    });

    request.headers.addAll(headers);
    http.StreamedResponse response = await request.send();

    try {
      if (response.statusCode == 200) {
        await response.stream.bytesToString().then((value) {
          print(value);
        });
      } else {
        // here I want to print the message and the errors
      }
    } catch (e) {
      throw e;
    }
  }
4

1 回答 1

2

添加这个至于错误,您的 statusCode 不是 200

       try {
              if (response.statusCode == 200) {
                await response.stream.bytesToString().then((value) {
                  print(value);
                });
              } else {
        await response.stream.bytesToString().then((value) {
                  print(value);
    
    
    var jsonResponse = json.decode(response.body.toString());
    
    
               
        var nameError = jsonResponse["errors"]["name"][0];
        
        var emailError = jsonResponse["errors"]["email"][0];
        var usernameError = jsonResponse["errors"]["username"][0];
        var passwordError = jsonResponse["errors"]["password"][0];

//now can print any print(emailError);
                });
        }
于 2021-05-01T23:40:08.617 回答