How to add CORS middleware in shelf with router?

636 views Asked by At

I am new to server side programming with dart. I made a simple API server with a number of get routes. I am handling this as follow,

  Router router = Router();

  router.get('/', checkSTATUS);

  router.get('/login/<user>/<pass>', (Request request, String user, String pass) async {
   id = 0;
    // stuff
      return Response.ok(json.encode({"status":"found","id":id}));
    
   
  });

  router.get('/update', (Request request) async {
      //stuff
      return Response.ok(json.encode({"status": "updated", "data": updated}));
    

  });

//for any other requests
  router.all('/<ignored|.*>', (Request request) {
      return Response.notFound(json.encode('Page not found'));
});

  final server = await serve(
    router,
    InternetAddress.anyIPv4,
    8080,
  );

I can access these routes using postman but making requests using flutter web results in error. I searched and found out that this may be CORS related. But how do I add the CORS headers without disrupting the entire code.

1

There are 1 answers

1
Marvin On

Please refer this document. https://pub.dev/packages/shelf_cors_headers. Install this package