I have a problem getting data from api (GET DATA) with token
I get an error when I try to get dataو While passing the token
this error in my {response.body}
:
ERROR FOR SHOW : {"message":"Unauthenticated."}
class _ResultLadderState extends State<ResultLadder> {
String token = "";
@override
void initState() {
getInfo();
getDataLadder();
super.initState();
}
void getInfo() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
token = pref.getString("login")!;
});
}
Future getDataLadder() async {
print('bye');
var response = await http.get(
Uri.parse('https://pellekani.com/backend/api/v1/pellekan/main/active'),
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print('ERROR FOR SHOW : ${response.body}');
if (response.statusCode == 200) {
print('hi');
setState(() {
stringResponse = response.body;
});
}
}
I received the token successfully but I do not know why the data is not displayed
in the Postman app, works without any problems
CodePudding user response:
Kindly add "Content-Type" in your request headers.
CodePudding user response:
String baseUrl="Your Api Key"
Future<Dio> getApiClient() async {
try {
var token = await storage!.getData(StorageKeys.token.toString());
print(token);
_dio.interceptors.clear();
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, interceptorHandler) {
// Do something before request is sent
options.headers["Authorization"] = "Bearer " token.toString();
return interceptorHandler.next(options);
// ignore: non_constant_identifier_names
},
onResponse: (response, interceptorHandler) {
// Do something with response data
return interceptorHandler.next(response); // continue
// ignore: non_constant_identifier_names
},
one rror: (error, interceptorHandler) async {
// Do something with response error
if (error.response?.statusCode == 403 ||
error.response?.statusCode == 401) {
_dio.interceptors.requestLock.lock();
_dio.interceptors.responseLock.lock();
// ignore: unused_local_variable
RequestOptions options = error.response!.requestOptions;
// ignore: unused_local_variable
Options? opt;
var user = FirebaseAuth.instance.currentUser!;
token = await user.getIdToken(true);
await storage!.setData(StorageKeys.token.toString(), token);
options.headers["Authorization"] = "Bearer " token.toString();
_dio.interceptors.requestLock.unlock();
_dio.interceptors.responseLock.unlock();
// return _dio.request(options.path, options: opt);
} else {
return interceptorHandler.next(error);
}
},
),
);
// _dio.options.baseUrl = baseUrl;
} catch (err) {
print(err);
}
return _dio;
}
getDataLadder() async {
try {
var http = await getApiClient();
var response = await http.get(baseUrl);
return response;
} catch (er) {
// print(er.toString());
}
}