laravel - Flutter 中出现 401 未经授权的错误,但在 Postman 中工作正常

标签 laravel flutter api authorization integration

我有 Laravel 端点。登录、注册和主页(其中 getData() 将起作用)。

注册 API 和登录 API 工作正常,但问题在于 HomePage API,它不会询问用户详细信息,它是一个 get 方法,它将在检查用户是否登录时返回详细信息.

  var token;

  _getKey() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString('key');
    print("this is Key $token");
  }
saveKey(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('key', key);
  }
  getData() async {
    await _getCSRF();
    await _getKey();
    print(_setAuthHeaders());
    String uri = "$baseUrlUser/user_bal";
    try {
      return await http.get(Uri.parse(uri), headers: _setAuthHeaders());
    } catch (e) {
      return e;
    }
  }

  _setAuthHeaders() => {
        'Accept': 'application/json',
        'Connection': 'keep-alive',
        'Authorization': 'Bearer $token',
      };

此处正在打印 token : This is token

在浏览器中点击端点的结果。 This is the header which I want to access

请帮忙。

最佳答案

http 库自动将 header 名称转换为小写,可能您的服务器不接受小写 header 名称。 请按照以下步骤操作:

  1. 在外部库->Dart Packages->http-x.xx->src->io_client.dart中查找io_client.dart
  2. io_client.dart 中找到此代码(第 40 行)
request.headers.forEach((name, value) {
  ioRequest.headers.set(name, value);
});
  • 添加preserveHeaderCase: true
  • request.headers.forEach((name, value) {
      ioRequest.headers.set(name, value,preserveHeaderCase:true);
    });
    
  • 清理您的项目并重建
  • 关于laravel - Flutter 中出现 401 未经授权的错误,但在 Postman 中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73133740/

    相关文章:

    ios - 错误 : unable to read input file as a property list: The operation couldn’t be completed.(XCBUtil.PropertyListConversionError 错误 1。)

    ios - GMSPlace - 我可以从一组坐标中得到它吗

    mysql - Eloquent ——laravel。根据输入用户获取行。输入空时获取全部

    Laravel @push 在 create_category.blade.php 中不起作用

    php - Laravel 使 :seeder is very slow

    php - 为什么在我的 POST 中呈现此 html 错误?

    flutter - 如何在flutter中设置App Bar底部的标题和副标题

    google-maps - Flutter - 谷歌地图在调整大小时崩溃

    c# - 如何确定 Facebook 用户是否登录到 Facebook 从 C# 连接

    ajax - 如何使用新 API 从 Instagram 获取公共(public)数据或标签?