skip to Main Content

I tried to build an app in Flutter on Android.
There is 'Authorization': 'Bearer $token' HTTP header sent from readData() method. The problem is that $token is not sent properly and Null is received on the server.
I tried to send $token, ${token}, plain text token (String) – none worked.

When I tried sending get request containing token as a plain text from https://reqbin.com/post-online it worked fine.

Could you please advice on what causes the issue?

  Future readData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token').toString();

    print('Token : $token');     // prints $token OK

    final response = await get(
        Uri.parse('https://www.somehost.com/api.php'),
        headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',     // here token is null (read from server log)
        }
      );

    print(response.statusCode);

    var data = jsonDecode(response.body.toString());
    print(data);
    print(data['success']);
    print(data['user']['email']);
  }

and API code:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require __DIR__.'/classes/db.php';
require __DIR__.'/auth.php';

$allHeaders = getallheaders();
$db_connection = new Database();
$conn = $db_connection->dbConnection();
$auth = new Auth($conn, $allHeaders);

echo json_encode($auth->isValid());
?>

2

Answers


  1. Use

    String token = await prefs.getString('token'); 
    

    instead of

    String token = prefs.getString('token').toString();
    

    as prefs.getString() returns a Future, so need to add await.

    Login or Signup to reply.
  2. You need to add await as if you do not add the print command you wrote and the API call will be triggered together so that is why you are seeing the token been printed as well with the correct value but the API is already called. Using await makes sure that you receive the token first and then only calls the API. So i agree with MSC you need that to work

    String token = await prefs.getString('token');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search