mardi 2 juin 2020

GitHub Jobs API / Flutter Web

I'm running into CORS errors in Chrome when using GitHub Jobs API to fetch jobs listing blob in Flutter Web app. It's a simple app to make an HTTP call to fetch the data and print it in a Flutter widget. I got it working without any issues on android and ios variants.

Here's code:

import 'dart:convert';

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(
      debugShowCheckedModeBanner: false,
      home: Listing(),
    );
  }
}

Future<List<dynamic>> getJson() async {
  ////https://jobs.github.com/positions.json?description=python&location=new+york
  String loc = 'new+york';
  String keyword = 'python';
  final uri = Uri.https(
    'jobs.github.com',
    'positions.json',
    {'location': loc, 'description': keyword, 'page': '1', 'markdown': 'true'},
  );
  final results = await http.get(uri, headers: headers);
  final jsonObject = json.decode(results.body);

  return jsonObject;
}

Map<String, String> get headers =>
    {'Accept': 'application/json', 'Access-Control-Allow-Origin': '*'};

class Listing extends StatefulWidget {
  @override
  _ListingState createState() => _ListingState();
}

class _ListingState extends State<Listing> {
  var jobs;
  fetchData() async {
    var response = await getJson();

    setState(() {
      jobs = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    fetchData();
    return Scaffold(
      body: SingleChildScrollView(
        child: jobs != null
            ? Text("GitHub Jobs API response\n $jobs")
            : Text("No Response from API"),
      ),
    );
  }
}

Error at Console:

Error: XMLHttpRequest error.
    dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:20      get current
packages/http/src/browser_client.dart 84:22                                       <fn>
dart-sdk/lib/async/zone.dart 1450:54                                              runUnary
dart-sdk/lib/async/future_impl.dart 143:18                                        handleValue
dart-sdk/lib/async/future_impl.dart 696:44                                        handleValueCallback

Error in Chrome:

Access to XMLHttpRequest at 'https://jobs.github.com/positions.json?location=new%2Byork&description=python&page=1&markdown=true' from origin 'http://localhost:63618' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I don't seem to find a solution to this issue. Any thoughts? P.S. I'm exploring GitHubJobs API for a side project. I couldn't find their pricing/api key info for using this API. Did I miss something?

Thanks!




Aucun commentaire:

Enregistrer un commentaire