How can i get information about the error when there is no responce in the error? Through postman I see code 404, through catch I see code 0 in the request. How can I get 404 code?
(async () => {
try {
const res = await axios('https://ms.com/s');
}
catch(e) {
console.log(e);
console.log(e.response);
console.log(e.request);
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js"></script>
var response = await axiosbase.get('https://ms.com/s')
.then(response => {
return response;
}).catch(response => {
return response;
});
if(response.status === 200){
// do something here.
}
Related
I am using axios to stream data from an API, something like this
const response = await axios.get(url,
{
responseType: `stream`,
}
);
const stream = response.data;
stream.on(`data`, (data) => {
...
});
stream.on(`error`, (err) => {
...
});
From time-to-time I get an error
{
"code": "ECONNRESET"
}
Does this mean it's the API that is throwing this error as opposed to my application that caused it?
Thank you,
Edit 1:
I am new to Flutter, and coding altogether, so please answer in simple terms.
I can get a JSON string from this API: [https://reqres.in/api/users?page=1][1]. using jsonDecode(response.body)
And I can also get specific part within this JSON using
jsonDecode(response.body)['data'] // 'data' is a List[]
But Postman, generates this completely different code to get data from api.
Postman uses response.stream.bytesToString());
Now I want to keep using Postman's auto generated code, but tweek it such that I get only the List, 'data', from the API.
My full code is:
class ApiService {
Future<List<UserModel>> getData() async {
try{
Response response = await get( Uri.parse('https://reqres.in/api/users?page=2'));
List result = await jsonDecode(response.body)['data'];
if (response.statusCode == 200) {
print(response);
print('');
print(response.body);
print('');
print(result);
print('');
return result.map((e) => UserModel.fromJson(e)).toList();
}
else {
print(response.reasonPhrase);
throw Exception(response.reasonPhrase);
}
} catch(e){
print('Error AA gaya \n\n\n $e') ;
throw e;
}
}
}
------------
Postman generated code is:
==========================
var request = http.Request('GET', Uri.parse('https://reqres.in/api/users?page=2'));
a
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
[1]: https://reqres.in/api/users?page=1
your code is correct but the way you parse is wrong
Future<List<UserModel>> getData() async {
try{
Response response = await get( Uri.parse('https://reqres.in/api/users?page=2'));
if (response.statusCode == 200) {
var jdata = jsonDecode(response.body);
print(response);
print('');
print(response.body);
print('');
print(jdata);
print('');
return jdata['data'].map((e) => UserModel.fromJson(e)).toList();
}
else {
print(response.reasonPhrase);
throw Exception(response.reasonPhrase);
}
} catch(e){
print('Error AA gaya \n\n\n $e') ;
throw e;
}
}
i have a problem with hate. I'm trying to login using dio, the login method works perfectly, but when I put invalid credentials dio gives me this error:
DioError
Error in execution
I created a boolean function that would return true or false if the statuscode was 200 it would return true and if not it would return false, but when logging in with the right credentials everything is ok, everything happens as it should, but when logging in with invalid credentials this error above causes it. I'm using shared preferences to store the tolken in the app, and the logic would be simple, if it was 200 I would log into the app, otherwise it would show me a snackbar I made in another file, this is my code:
loginFinal() async {
if (formKey.currentState!.validate()) {
bool loginIsOk = await loginConect();
if (loginIsOk) {
Get.offAllNamed("/home");
await Future.delayed(const Duration(seconds: 1));
message(MessageModel.info(
title: "Sucesso",
message: "Seja bem vindo(a) influenciador(a)",
));
} else {
loaderRx(false); //LOADER
message(MessageModel.error(
title: "Erro",
message: "Erro ao realizar login",
));
}
}
}
//LOGICA DE ENTRAR NO APP
Future<bool> loginConect() async {
final dio = Dio();
String baseUrl = "https://soller-api-staging.herokuapp.com";
loaderRx(true); //LOADER
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final response = await dio.post(
baseUrl + "/auth",
data: jsonEncode(
{
"login": emailController.text,
"senha": passWordController.text,
},
),
options: Options(
headers: {'Content-Type': 'application/json; charset=UTF-8'},
method: "post",
),
);
if (response.statusCode == 200) {
await sharedPreferences.setString(
"token",
"string: ${response.data["string"]}",
);
print("Resposta: ${response.data["string"]}");
loaderRx(false);
return true;
} else {
print("RESPOSTA: ${response.data}");
return false;
}
}
}
Dio always throw an exception if the status code in the header is not 200,
you will need to catch the exception using try catch.
In the catch method, you can check if the type of the error is DioError and then handle that exception,
Here is a code snippet of a login process that I use in my code to handle this behavior.
Future<SignInApiResponse> signInUser(String _email,String _password) async {
try {
final dio = Dio(ApiConstants.headers());
final Response response = await dio.post(
ApiConstants.baseUrl + ApiConstants.signInUrl,
data: {"email": _email,
"password": _password,
},
);
if (response.statusCode == 200) {
return SignInApiResponse.fromJson(response.data);
} else {
return SignInApiResponse(message: response.toString());
}
} catch (e) {
if (e is DioError) {
if (e.response?.data == null) {
return SignInApiResponse(message: Messages.loginFailed);
}
return SignInApiResponse.fromJson(e.response?.data);
} else {
return SignInApiResponse(message: e.toString());
}
}
}
hopefully, this will help
if not you can always use http package that does not throw an exception in similer case
I am using nextjs api/routes
I have a login and when an issue occurs return a 401 and message text that I would like to show to users.
A minimal example is:
Api : /api/v1/auth/sigin.js
export default async (req, res) => {
const { name, password } = req.body;
const url = process.env.SH_API_BASEURL + 'auth/signin';
console.log(url);
try {
const resp = await axios.patch(url, { name, password });
return res.status(200).send(resp.data);
} catch (err) {
const { response } = err;
const status = response.status;
const message = response.data.errors[0].message;
console.log(`status: ${status}, message ${message}`);
return res.status(status).send(message);
}
};
Pages /pages/auth/signin.js
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log('pages auth in error');
console.log(err);
setSubmitError(true);
console.log('sigin handle submit error');
}
};
console.log(err) shows the output
Error: Request failed with status code 401
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
How do I get access to the statusCode and text in pages code?
Could any answers be in the context of nextjs api/routes
Thanks
You can access the response property of the axios error to get the status
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log(err.response.status);
}
};
Wanted to send following data in to the mangodb using axios but getting error of 400
{"data":{"name":"cvc","lastname":"cv","gender":"Male","dob":"2020-10-27"}}
await this.$axios.$post( 'http://localhost:8000/owner',user,{timeout: 120000 })
.then(response => {
this.errors = [];
this.snackbar = true;
console.log(response)
}).catch((error) => {
console.log(error.response)
this.errors = error.response.data.errors;
console.log('somthing went wrong')
if (error.response.status === 400 ){
console.log(this.errors)
}
})