【发布时间】:2023-01-12 17:01:11
【问题描述】:
我正在尝试使用 httparty gem 实现 post 操作,这就是我所拥有的。我在 docker 中运行所有内容,下面的代码将作为活动作业运行。我在一项服务中,我正在尝试在其他服务中发布到 api。我能够得到但没有任何运气。我在网上看了很多,但我不确定我做错了什么。我总是在 self.class.post 行收到错误 403。我还尝试对 api 进行邮递员调用,我能够访问 api,但下面的代码甚至无法访问其他服务。
任何帮助表示赞赏。谢谢。
require 'uri'
class CustomerProductAPI
include HTTParty
format :json
def initialize(customer_product_id)
@customer_product = CustomerProduct.find(customer_product_id)
@customer = Customer.find(@customer_product.student_id)
@product = Product.find(@customer_product.product_id)
self.class.base_uri environment_based_uri + '/customer_product_api'
end
def create_customer_product
uri = URI(self.class.base_uri + "/customer/#{customer.id}")
self.class.post(uri, body: body_hash).response.value
end
private
attr_reader :customer_product, :customer, :product
def body_hash
{
token: ENV['CUSTOMER_PRODUCT_API_TOKEN'],
customer: customer.name,
product: product.name,
}
end
def environment_based_uri
ENV['CUSTOMER_PRODUCT_URL']
end
end
【问题讨论】:
-
你的帖子成功了。 403 是来自服务器的消息,它拒绝传送您请求的内容,因为它认为您没有足够的权限。因此,您的 Ruby 似乎没有任何问题。根据 API 文档,检查您是否正确使用了 API,是否正在访问您有权访问的资源,是否提供了所需的任何授权令牌/密码等,以及令牌是否正确,并且当前的;如果还是不行,请向 API 的所有者寻求帮助。
-
还要检查
uri是否正确;我不确定,但我有一种直觉,你可能误用了self.class.base_uri(错误的 URI 可能解释了为什么 API 认为你正在访问你不应该访问的东西) -
确保 ENV['CUSTOMER_PRODUCT_URL'] 根据您的环境返回正确的值。
标签: ruby-on-rails ruby httparty