flutter http get function to azure http trigger

61 views Asked by At

Currently using flutter as my webapp to view data from azure for that, I'm using http trigger function to send data after a request from flutter web app. I created a http trigger in azure and used the function URL to connect with http trigger function. But when I run the below code,

  Future<void> main() async {
  // Construct the URL to fetch data from Azure function
  String url = "https://dashboardfunctionapp.azurewebsites.net/api/http_trigger?code=*************==";

  try {
    // Make the HTTP GET request
    final response = await http.get(
      Uri.parse(url)
      // headers: {
      //   'Authorization': Key,
      //   'Content-Type': 'application/json',
      // },
    );

    // Check if the request was successful (status code 200)
    if (response.statusCode == 200) {
      // Parse the response body (data from Azure IoT Hub)
      String responseBody = response.body;
      print('Data from Azure IoT Hub: $responseBody');
      // Process the data as needed
      // Example: Convert JSON data to Dart objects
    } else {
      // If the request was not successful, print the error
      print('Failed to fetch data from Azure IoT Hub. Error code: ${response.statusCode}');
    }
  } catch (error) {
    // Catch any exceptions that occur during the HTTP request
    print('Error fetching data from Azure IoT Hub: $error');
  }
}

I get this error. What would be the issue.

Error fetching data from Azure IoT Hub: ClientException: XMLHttpRequest error., uri=https://nodereddashboardfunctionapp.azurewebsites.net/api/http_trigger?code=************==

1

There are 1 answers

0
SiddheshDesai On

I agree with @chunhunghan, You need to implement a backend layer that calls this API and also configure CORS setting in your Azure Function App to allow calling the Web app or localhost to communicate with it:-

You can make use of the code below:-

Project/lib/main.dart:-

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Azure Function Data Fetcher',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? data;

  Future<void> fetchData() async {
    String url = "https://siliconfun39.azurewebsites.net/api/Function1?code=Bb_G8tbaTi-dUpdGVt94rY13xCDxOZoctmwXejDojbHwAzFu6bVr3A==";

    try {
      final response = await http.get(Uri.parse(url));

      if (response.statusCode == 200) {
        setState(() {
          data = response.body;
        });
      } else {
        print('Failed to fetch data. Error code: ${response.statusCode}');
      }
    } catch (error) {
      print('Error fetching data: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Azure Function Data Fetcher'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: fetchData,
              child: Text('Fetch Data from Azure Function'),
            ),
            SizedBox(height: 20),
            if (data != null)
              Text(
                'Data from Azure Function: $data',
                style: TextStyle(fontSize: 16),
              ),
          ],
        ),
      ),
    );
  }
}

In the Function App CORS add the Web App url which has your Flutter app deployed also add the localhost url if you are running your Flutter App locally:-

enter image description here

If the error persists, Create a proxy to request this Function Url from your Flutter app.