ruby-on-rails - 如何正确格式化 json 以使用 RestClient 发送

标签 ruby-on-rails ruby json rest-client

我正在尝试实现这个 javascript 代码

var token = "<page_access_token>";

function sendTextMessage(sender, text) {
  messageData = {
    text:text
  }
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token:token},
    method: 'POST',
    json: {
      recipient: {id:sender},
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });
}

进入 ruby​​ on rails 代码

def reply_back(sender, text)
      page_token = "*****"

      base_uri = "https://graph.facebook.com/v2.6/me/messages"

      messageData = {
        text: text
      }

      qs = {
        access_token: page_token
      }

      json = {
        recipient: {
          id: sender
        },
        message: messageData
      }

      response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json
      p "this is the response #{response}"

    end

但显然我做错了什么,我在控制台中得到了这个

(参数数量错误(2..3 为 4 个))

在线

response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json

有什么见解吗?

最佳答案

您应该像这样将所有参数放在一个参数哈希中:

  params = {
    recipient: { id: sender },
    message: { text: text },
    access_token: page_token
  }

  response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
  p "this is the response #{response}"

关于ruby-on-rails - 如何正确格式化 json 以使用 RestClient 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651057/

相关文章:

html tidy 和 rails 应用程序 - erb 或 rthml 文件。 ruby 替代品?

mysql - Ruby/Rails - 动态指定类的连接属性

ruby - Ruby 中的这是什么,它为什么存在?

javascript - 将实例变量转换为 JavaScript 对象数组

ruby-on-rails - 如何在 form_for 中使用多个 "one-to-many"嵌套属性

ruby-on-rails - rails 通常如何知道在什么环境下运行?

ruby-on-rails - 如何在 ruby​​/rails 中将数据附加到 json?

javascript - 在 Jquery 中使用列表框

java - 使用谷歌的 Gson 将 Json 转换为 java 对象

jquery - 使用turbolinks(rails)时,发送多个ajax请求而不是一个