Issue
I need to send my token for my API. I save my token in SharedPreferences and I can recupered this. My API need one, with the Bearer but how do ?
I tested with Authorization, Http etc.
Methods To save in SP
Future<bool> setToken(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString('token', value);
}
Future<String> getToken() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('token');
}
Future<Candidate> candidateAuth({Map map}) async {
String url = 'http://10.0.2.2:3000/v1/api/auth/candidate';
await http
.post(url,
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: jsonEncode(map))
.then((response) {
if (response.statusCode == 201) {
token = Candidate.fromJson(json.decode(response.body)).token;
Candidate().setToken(token);
return Candidate.fromJson(json.decode(response.body));
} else {
throw Exception('Failed auth');
}
});
}
}
My API Call :
Future<List<Theme>> getThemes() async {
String url = 'http://10.0.2.2:3000/v1/api/theme';
String token;
Candidate().getToken().then((value) {
token = value;
});
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);
if (response.statusCode == 200) {
List themesList = jsonDecode(response.body);
List<Theme> themes = [];
for (var themeMap in themesList) {
themes.add(Theme.fromJson(themeMap));
}
return themes;
} else {
throw Exception('Failed to load themes');
}
}
My API return error 401 : unauthorized
Solution
token
might not be set by the time it invokes http.get
. Change it to
String token = await Candidate().getToken();
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);
So that it is for sure set with right value.
Answered By - Chenna Reddy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.