如何正确格式化 json 以使用 RestClient 发送

How to properly format json to send over using RestClient

我正在尝试实现此 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);
    }
  });
}

在rails代码

上进入ruby
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

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

(wrong number of arguments (4 for 2..3))

在线

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}"

根据文档,您应该合并参数并将其作为一个对象传递到方法中:

params = qs.merge(json)
response = RestClient.post(base_uri,
                           params.to_json,
                           content_type: :json, accept: :json)

此方法需要 2 或 3 个参数。在这种情况下,第三个参数是一个散列 { content_type: :json, accept: :json }。由于它是最后一个参数,因此可以省略大括号。