[英]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. 我正在尝试从我的网站调用以python编写的Firebase Cloud函数。 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. 当我使用curl
从命令行调用该函数时,该函数可以完美运行,但是,当我尝试从JavaScript进行此操作时,却遇到了以下问题。 Essentially the JSON params are not being received. 本质上,JSON参数没有被接收。
How I am calling in JavaScript 我如何用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. 如果您现在运行此程序,则可能会得到正确的“授权码已过期”之类的信息。
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. 要处理此请求,您将需要在Cloud Function中设置适当的Access-Control-Allow- *标头以匹配您要接受的请求。 Please see an example of a CORS function written in Python. 请查看用Python编写的CORS函数的示例 。
You will notice that CORS consists of two requests: a preflight OPTIONS request, and a main request that follows it. 您会注意到,CORS由两个请求组成:一个预检OPTIONS请求和一个紧随其后的主请求。
The preflight request contains the following headers: 预检请求包含以下标头:
Let me know if it helps. 让我知道是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.