【问题标题】:Python Google cloud function and JavaScript Post requestPython 谷歌云函数和 JavaScript Post 请求
【发布时间】:2020-07-06 07:24:17
【问题描述】:

我有一个 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 的请求变量中找不到“域”变量。为什么这不起作用?

【问题讨论】:

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


    【解决方案1】:

    你必须设置标题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2020-11-21
      • 2019-09-14
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多