从 Flutter 前端注册到 aqueduct 后端

Register to aqueduct backend from Flutter frontend

我在从我的 Flutter 前端注册到 aqueduct 后端时遇到了一些困难

这是我的前端代码:

  Future<void> signUp(String email, String password) async {
    final body = "username:$email,password:$password"; //<- return request entity could not be decoded
    //final body = {"username": email, "password": password}; //<- return bad state: Cannot set the body fields of Request with content-type "application/json"

    try {
      final http.Response response = await http.post(
          "http://localhost:8888/register",
          headers: {"Content-Type": "application/json"},
          body: body);
      final jsonResponse = json.decode(response.body);
      if (jsonResponse["error"] != null) {
        throw HttpException(jsonResponse["error"]);
      }
    } catch (error) {
      throw error;
    }
  }

一定有什么愚蠢的错误。我相信它与格式化正文有关,所以我尝试了 2 个选项,并且都抛出了不同的 http 异常(如评论中所示)。

这里是一个从 Flutter 客户端连接到 Aqueduct 服务器的例子。 (不过,这并不是真正的服务器问题,因为客户端和服务器彼此独立。)

注册示例如下:

void _register(String email, String password) async {
  Map<String, String> headers = {"Content-type": "application/json"};
  final jsonString = '{"username":"$email", "password":"$password"}';
  Response response = await post(YOUR_URL_HERE, headers: headers, body: jsonString);
  print('${response.statusCode} ${response.body}');
}

在您的示例中,您没有正确编码 JSON。

这是另一个登录示例。class 是我所说的视图模型架构 here

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

class LoginViewModel extends ChangeNotifier {

  String _token = '';
  bool _isLoggedIn = false;
  bool get isLoggedIn => _isLoggedIn;
  String get token => _token;

  Future onLoginPressed(String username, String password) async {
    if (username.isEmpty || password.isEmpty) {
      return;
    }
    _isLoggedIn = await _login(username, password);
    notifyListeners();
  }

  Future<bool> _login(String username, String password) async {
    var clientID = 'com.example.app';
    var clientSecret = '';
    var body = 'username=$username&password=$password&grant_type=password';
    var clientCredentials = Base64Encoder().convert('$clientID:$clientSecret'.codeUnits);

    Map<String, String> headers = {
      'Content-type': 'application/x-www-form-urlencoded',
      'authorization': 'Basic $clientCredentials'
    };
    var response = await http.post(YOUR_URL_HERE, headers: headers, body: body);
    final responseBody = response.body;
    if (response.statusCode != 200) {
      return false;
    }

    final map = json.decode(responseBody);
    _token = map['access_token'];
    return true;
  }
}