简体   繁体   中英

Flutter post request headers do not appear on Google Cloud Function

I am doing a post request in flutter to a google cloud function:

  final uri = Uri.parse(
      'https://example.cloudfunctions.net/send_to_queue');
  final bearer = 'Bearer ${await user.getIdToken()}';
  final response = await http.post(uri, body: json.encode(data),
      headers: {HttpHeaders.authorizationHeader: bearer, 'Content-Type': 'application/json'});

In the Google Cloud I print(request.headers) I see a bunch of headers but no Authorization or Content-Type headers.

What should I do?

PS Same issue in here Flutter calling firebase cloud function admin.auth.updateUser but I don't want to use a callable function

The browser was sending an OPTIONS request ( preflight ) before the POST.

I needed to change the Google Cloud Function to handle this:

def main(request):
    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
            'Access-Control-Max-Age': '3600'
        }
        return ('', 204, headers)
    # Get token from request
    token = request.headers.get('Authorization').split('Bearer ')[1]
    etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM