我正在React的在线商店工作,在Rails中使用后端,我使用Stripe。在我向我的充电控制器发送获取请求后,控制器成功发送,我可以看到参数,一切都很好。
Started POST "/charges" for 127.0.0.1 at 2018-02-10 20:22:16 +0000
Processing by ChargesController#create as JSON
Parameters: {"description"=>"Only the Book", "source"=>"tok_1Bu4rRHmkRoa1PQ1R3ndnG2o", "amount"=>100, "charge"=>{"description"=>"Only the Book", "source"=>"tok_1Bu4rRHmkRoa1PQ1R3ndnG2o", "amount"=>100}}
Redirected to http://localhost:3000/charges/new
Completed 302 Found in 2554ms (ActiveRecord: 0.0ms)
但是当控制器创建动作执行重定向到新方法时,我收到此错误:
ActionController::UnknownFormat (ChargesController#new is missing a template for this request format and variant.
request.formats: ["application/json"]
request.variant: []):
我在新方法的控制器中尝试了renspond_to:json,不起作用,我试图反序列化将它们传递给实例变量的params,但它们不能正常工作,因为它们是零,我没有尝试json builder,因为我做不知道这是否会更简单。 这是我的代码如下: charges_controller.rb class ChargesController< ApplicationController中
def new
@amount = params[:stripeAmount]
@description = params[:stripeDescription]
end
def create
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => params[:stripeAmount],
:description => params[:stripeDescription],
:currency => 'GBP'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
这是我的new.html.erb
<%= form_tag charges_path do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: <%= (@amount) %></span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="<%= @description %>"
data-amount="<%= @amount %>"
data-locale="auto"></script>
<% end %>
非常感谢您的帮助!
答案 0 :(得分:2)
看起来你没有回应json。你的救援是一个HTML响应,所以这肯定不会起作用。你需要以json的形式发回响应,因为那是你的反应应用所期望的。自从我使用了条纹以来已经有一段时间了,但是像这样:
以下假设您有respond_with
:
respond_to :json
def create
# ... your stripe customer and charge api requests
respond_with charge
end
或者,如果您没有respond_with
:
def create
# ... your stripe customer and charge
respond_to do |format|
format.json { render json: charge }
end
end