Python Google云功能和JavaScript发布请求

时间:2020-03-25 17:25:39

标签: javascript python google-cloud-platform google-cloud-functions

我有一个带有以下代码的Python云功能:

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)

我想使用JavaScript xhr post请求向此函数发送json数据。 JS代码如下:

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));
  }
}

如果我查看GCF的日志并打印请求,则该请求将显示“无”。它在python的request变量中找不到“ domain”变量。为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

您必须设置标题:

 xhr.setRequestHeader('Content-Type','application/json');
 xhr.send(JSON.stringify(data));