Ajax post 请求 google NLP

Ajax post request to google NLP

我正在尝试向 GCP Natural Language 发送 post 请求以进行情绪分析。

当我在 google 上的代码浏览器上尝试数据格式时,它工作正常,但是当我在 html 页面上 运行 时,我收到一个错误,显示为

{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
          },
          {
            "description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
          }
        ]
      }
    ]
  }
}

我的代码是:

<!DOCTYPE html>
<html>
<body>

<h1> Testing sentiment Analysis </h1>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    var APIKEY = "AN API KEY";

    $.ajax({
        type        : "POST",
        url         : "https://language.googleapis.com/v1/documents:analyzeSentiment?key="+APIKEY,
        data        :   {
                            "document": {
                                "type": "PLAIN_TEXT",
                                "content": "Hello I am great"
                            },
                            "encodingType": "UTF8",
                        },
        success: function(res) {
                console.log(res);
                alert(res['message']);
        },
        error: function(res) {
                console.log(res['message']);
                alert(res);
        },
    });
</script>
</body>
</html>

更新: 一位同事向我指出了我正在犯的错误。我们必须使用 JSON.stringify() 才能发送请求。代码应该是这样的:

$.ajax({
    type        : "POST",
    url         : "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=YOUR-API-KEY", 
    contentType : "application/json; charset=utf-8",
    data        : 
                    JSON.stringify({
                        "document": {
                            "type": "PLAIN_TEXT",
                            "language": "en",
                            "content": "Hola Victor"

                        },
                        "encodingType": "UTF8"}),
    success     : function(_result){ 

        if (_result) { 
            alert('SUCCESS');
        } else {
            alert('ERROR');
        }
    },

    error       : function(_result){

    }
});

我已经测试过它并且有效。