I have a problem regarding fetching data or using the request API in local in flutter.
I tried to send a request using postman and it works, but when I'm trying to request in flutter, it gives me Connection refuse.
I'm using http package of flutter
This is the error, but i also tried jsonplaceholder api and it works.
I/flutter (10134): 5004/profile URI :>> http://127.0.0.1:5004/profile/v1.0/channels/1?includes=createdByProfile,joinedProfiles
I/flutter (10134): error :>> Connection refused
Heres my code:
Future loadData() async {
try {
var data = await http.get(Uri.parse('http://127.0.0.1:5000/content/v1.0/contents'));
print("data!! :>> $data");
} catch (error) {
print("ERROR! $error");
}
}
it always go to catch and says Connection Refused. But when i tried to request in postman and access the url in browser, it shows the data there
Related
I'm trying to get data from a website that hosts Weather APIs (OpenWeatherMap), but as soon as I use the get() method, I get an error that says :
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Failed host lookup: 'api.openweathermap.org'
Even tho the URL that I provided is working (I tested it, the API key is working), here is the code :
String url = "https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey";
// The latitude, longitude and apiKey aren't not null.
Uri uri = Uri.parse(url);
http.Response response;
try {
response = await http.get(uri);
} on Exception catch (e) {
print("Error when getting data from the url = $url"); // Im getting this line on the console,
// so the error is indeed the line above.
}
I fixed it. My phone had issues reaching Internet, so the code couldn't reach the URL provided.
Is it possible get error message when call rest api in flutter?
Eg.
print(response.statusCode); --return code
How print this error message?
The request could not be processed because an error occurred whilst attempting to evaluate the SQL statement associated with this resource. Please check the SQL statement is
If you are using dio package you can catch DioError and fetch a response from the error.
In my case back returns me the message in ['error'][''message].
I'm not sure how it works with http package. Firstly you can print e.response!.data to see the structure and then get the error text
try {
//make request
} on DioError catch (e, stacktrace) {
final result = e.response!.data as Map<String, dynamic>;
print(result['error']['message']); <---- getting error message from response
}
I have a NestJS application that acts as a BFF (Backend for Frontend) which exposes a certain endpoint. That endpoint uses Axios to send multiple requests to my backend. Some of these requests to the backend can return different status codes, which I want to propagate back to the caller. However, I don't want to catch every request manually. Currently, it throws 500 if any Axios request fails in the pipeline.
I thought about implementing a global exception filter for Axios exceptions, that will check the returned status code from Axios and throw an appropriate HttpException exception that NestJS will catch (e.g. if any Axios request failed and returned 401, throw an UnauthorizedException which NestJS will catch and return back to the client, instead of 500).
Is it a possible approach, or is there anything else I can do?
If you want, you can use Exception filters
So first you need to create a file for the exception filter.
// axios.exception-filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from '#nestjs/common';
import { Request, Response } from 'express';
import { AxiosError } from 'axios';
#Catch(AxiosError)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: AxiosError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
console.log(exception);
response.status(400).json({
statusCode: 400,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
And in your main.ts add this
app.useGlobalFilters(new HttpExceptionFilter());
And now in response.status(400).json({}) you can add everything you want in your body. Like the error message of Axios.
I am trying to know if the connection error is Connection to 'some URL' was not upgraded to websocket. Also identify response code. The server is emitting 401.
I need this to know if I need to refresh the token and then reconnect.
final channel = IOWebSocketChannel.connect(Url)
final sub = channel.stream.listen((data){
//process data
},
onError: (error){
//confirm this error failing to upgrade and
// response code is 401
// then refresh token and reconnect
})
To know the error type
print('error type is ${error.runtimeType}');
then you can handle it
if(error is errorType)
{
...
}
I'm testing a request to get data from an URL using dio in my Dart code.
import 'package:dio/dio.dart';
class Api {
Dio dio = Dio();
var path = 'https://jsonplaceholder.typicode.com/users';
void getHttp() async {
try {
Response response = await dio.get(path);
print(response.data);
} catch (e) {
print(e);
}
}
}
In this case it brings the result correctly.
But, I actually need get data from this URL:
http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbwMPI0sDBxNXAOMwrzCjA0sjIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wNnUwNHfxcnSwBgIDUyhCvA5EawAjxsKckMjDDI9FQE-F4ca/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0KO6H80AU71KG7J0072/res/id=buscaResultado/c=cacheLevelPage/=/?timestampAjax=1588600763910
Using Postman I can access the data:
So, the problem is that, if I try to get data from that URL in my code, I get the following exception error:
I/flutter (23393): DioError [DioErrorType.DEFAULT]: RedirectException: Redirect loop detected
If this URL is redirecting, why is it working when using Postman? Anyway, how could I handle this redirected request in order to access data?
After a while, I noticed that the response to this request is coming as HTML and not as Json. So I needed to create a way to get DOM coming from the request, removing HTML tags and encoding string to Json.