Anters Bear
Anters Bear

Reputation: 1956

Sending a POST request from JavaScript not passing in JSON params

I am trying to call a Firebase Cloud function written in python from my website. The function works perfectly when I call it from command line using curl, however, when I try to do the same from JavaScript I am getting the following issue. Essentially the JSON params are not being received.

enter image description here

How I am calling in JavaScript

var xmlhttp = new XMLHttpRequest();
var theUrl = "https://us-central1-scan2checkout.cloudfunctions.net/registerUser";
xmlhttp.open("POST", theUrl,true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send('{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}');

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {
        console.log(xmlhttp.responseText);
    }
}

Cloud Function

def registerUser(request):
    print(request) # Printing '<Request 'http://us-central1-scan2checkout.cloudfunctions.net/' [OPTIONS]>'
    print(request.json) # Printing 'NONE' :(
    auth = request.json['auth'] # Issue is here
    # ... SOME STUFF ...
    return {...},201

How it works when I use command line

time curl -v -X POST -d '{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}' -H "Content-type: application/json" https://us-central1-scan2checkout.cloudfunctions.net/registerUser

If you run this now you'll probably get something like "Authorization code expired" which is correct.

Upvotes: 0

Views: 132

Answers (1)

Deniss T.
Deniss T.

Reputation: 2642

To handle this request, you will need to set the appropriate Access-Control-Allow-* headers in your Cloud Function to match the requests you want to accept. Please see an example of a CORS function written in Python.

You will notice that CORS consists of two requests: a preflight OPTIONS request, and a main request that follows it.

The preflight request contains the following headers:

  1. Access-Control-Request-Method - indicates which method will be sent in the main request.
  2. Access-Control-Request-Headers - indicates additional headers along with the origin of the main request.

Let me know if it helps.

Upvotes: 1

Related Questions