简体   繁体   中英

401 unauthorized error in Flutter but works fine in Postman

I have Laravel endpoints. Login, Register and Home(where getData() will be working).

the register API and Login API is working fine but the problem is with the HomePage API where it will not ask for user details, it's a get method where it will return the details upon checking whether the user is logged-In or not.

  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',
      };

A token is printing here: 这是令牌

result of hitting the endpoint in the browser. 这是我要访问的标题

Please help.

please pass token as

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

http library automatically converts the header name to lower-case, may your server not accepting lower-case header name. Follow this step:

  1. Find io_client.dart in External Libraries->Dart Packages->http-x.xx->src->io_client.dart
  2. Find this code inside io_client.dart (line 40)
request.headers.forEach((name, value) {
  ioRequest.headers.set(name, value);
});
  1. Add preserveHeaderCase: true
request.headers.forEach((name, value) {
  ioRequest.headers.set(name, value,preserveHeaderCase:true);
});
  1. Clean your project and rebuild

If you are making flutter web project then please check at Inspect >> Console, that Refused to set unsafe header "content-length" is printing or not. If its happening then in your code where you have api setup

class ApiServiceProvider extends GetConnect {}
@override
  void onInit() {
    if (kIsWeb) {
      httpClient.addRequestModifier<void>((request) {
        request.headers.remove('user-agent');
        request.headers.remove('content-length');
        return request;
      });
    }
    super.onInit();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM