使用Google Apps脚本在Rails中发布JSON数据5

时间:2016-11-09 16:51:21

标签: ruby-on-rails json curl heroku google-apps-script

我有以下Google Apps脚本:

function myFunction() {
   var payload =
   {
     "person": {
    "first_name": "test",
    "last_name": "blah"
    }
   };

  var options =
   {
     "method" : "post",
     "contentType" : "application/json",
     "payload" : payload
   };

   var response = UrlFetchApp.fetch("https://myappherokuapp.com/curl_example", options);
  Logger.log(response);
}

我发布的应用是Rails 5应用。我运行脚本时遇到的错误是......

Request failed for https://myherokuapp.com/curl_example returned code 400

...而在heroku上,这就是我在日志中看到的......

2016-11-09T16:43:37.966300+00:00 heroku[router]: at=info method=POST path="/curl_example" host=myherokuapp.com request_id=51c138b5-ed30-4d4b-aa61-b477de875695 fwd="75.143.171.231,107.178.224.13" dyno=web.1 connect=0ms service=19ms status=400 bytes=179
2016-11-09T16:43:37.960171+00:00 app[web.1]: person=%7Blast_name%3Dblah,+first_name%3Dtest%7D

我可以运行此curl命令并成功发布数据:

curl -X POST -d "person[first_name]=john" -d "person[last_name]=doe" https://myherokuapp.com/curl_example

这也是我在Rails中的控制器...

class PeopleController < ApplicationController
  before_action :set_person, only: [:show, :edit, :update, :destroy]
  skip_before_action :verify_authenticity_token, :only => [:curl_post_example]
...
  def curl_post_example
    Person.create(person_params)
    render plain: "Thanks for sending a POST request with cURL! Payload: #{request.body.read}"
  end
...

2 个答案:

答案 0 :(得分:1)

如果你使用&#34; application / json&#34;你应该对有效负载进行字符串化。内容类型。 或者省略内容类型,然后将其转换为&#39; application / x-www-form-urlencoded&#39;。

我不确定Rails应用程序的期望,但当前请求无效,因为它需要一个json字符串。

答案 1 :(得分:1)

以下是我的完整解决方案,另请参阅Working with JSON文档

function myFunction() {
   var data =
   {
    "person":
     {
      "first_name":"boosy",
      "last_name":"cat"
     }
   };

  var payload = JSON.stringify(data);

  var options =
      {
        "method"  : "POST",
        "payload" : payload,
        "contentType" : "application/json",
        "followRedirects" : true,
        "muteHttpExceptions": true
      };

   var response = UrlFetchApp.fetch("https://myherokuapp.com/people", options);
  Logger.log(response);
}