1

I have a Python cloud function with the following code:

import requests
import json

def make_func(request):

     if request.method == 'OPTIONS':
          headers = {
               'Access-Control-Allow-Origin': '*',
               'Access-Control-Allow-Methods': 'GET, POST',
               'Access-Control-Allow-Headers': 'Content-Type',
               'Access-Control-Max-Age': '3600',
               'Content-Type': '*',
               'Content-Length': "3000"
          }

          return ('', 204, headers)

     request_json = request.get_json()
     print(request_json) #THIS SHOWS "NONE" IN THE LOGS

     domain = request_json['domain']

     headers = {
               'Access-Control-Allow-Origin': '*',
               'Content-Type': '*',
               'Content-Length': "3000"

     }    
     return (str(domain)), 200, headers)

I want to sent json data with a JavaScript xhr post request to this function. The JS code is the following:

const data = {
  domain : "test.com"
}

var domain = "blabla.com";
var xhr = new XMLHttpRequest();
xhr.open('POST', domain, true);
xhr.send(data);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
     var result = xhr.responseText;
     alert(JSON.stringify(result));
  }
}

If I looking into the logs of my GCF and I print the request, it says "None". It can't find the "domain" variable in the request variable in python. Why is this not working?

1 Answer 1

1

you have to set the header:

 xhr.setRequestHeader('Content-Type','application/json');
 xhr.send(JSON.stringify(data));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.