invertase / dart_edge

Run Dart on the Edge - supporting Vercel & Cloudflare Workers (more coming soon).
https://docs.dartedge.dev
Apache License 2.0
324 stars 23 forks source link

SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at packageData (ext:deno_fetch/22_body.js:368:14) at consumeBody (ext:deno_fetch/22_body.js:245:12) at eventLoopTick (ext:core/01_core.js:172:13) #35

Closed MichealReed closed 1 year ago

MichealReed commented 1 year ago

Error:

SyntaxError: Unexpected end of JSON input
    at parse (<anonymous>)
    at packageData (ext:deno_fetch/22_body.js:368:14)
    at consumeBody (ext:deno_fetch/22_body.js:245:12)
    at eventLoopTick (ext:core/01_core.js:172:13)

Example:


import 'dart:convert';
import 'package:supabase_functions/supabase_functions.dart' as edge;

void main() {
  edge.SupabaseFunctions(fetch: (request) async {
    final data = await request.json();
    print(data);

    return edge.Response(
      json.encode({'message': 'Message created!', 'id': 'a'}),
      status: 200,
      headers: edge.Headers({
        'Content-Type': 'application/json',
      }),
    );
  });
}

When attempting to get the data included with a request payload I see this. I have not been able to find a way to properly receive the json from the request.

MichealReed commented 1 year ago

The issue was CORS, there is a need to handle request.method to ensure that all appropriate headers are added preflight.

to mirror https://supabase.com/docs/guides/functions/cors in dart:

const defaults = {
  'Access-Control-Allow-Methods': 'POST',
  'Access-Control-Allow-Headers':
      'apikey, Authorization, X-Client-Info, Origin, X-Requested-With, Content-Type, Accept'
};
const corsAll = {...defaults, 'Access-Control-Allow-Origin': '*'};
void main() {
  SupabaseFunctions(fetch: (request) async {
    if (request.method == 'OPTIONS') {
      return Response('ok', status: 200, headers: edge.Headers(corsAll));
    }
    final token = request.headers['Authorization']?.split(' ')[1];
    final data = await request.json() as Map<String, dynamic>;

      return Response(
      json.encode({'message': 'Message created!'}),
      status: 200,
      headers: edge.Headers({...corsAll}),
    );
});
}